私はこのような多くの質問があることを知っていますが、私の問題の解決策を見つけることができません。
MyScript.js
:
$('#id_tags').keyup(function(){
var query;
query = $(this).val();
$.get('/blog/suggest-category/', {suggestion: query}, function(data){
console.log('data')
$('#suggestion_div').html(data);
});
});
マイview.py
:
def get_category_list(max_results=0, starts_with=''):
print('get_category_list')
cat_list = []
if starts_with:
cat_list = Tag.objects.filter(slug__istartswith=starts_with)
if max_results > 0:
if len(cat_list) > max_results:
cat_list = cat_list[:max_results]
return cat_list
def suggest_category(request):
print('suggest_category')
cat_list = []
starts_with = ''
if request.method == 'GET':
starts_with = request.GET['suggestion']
cat_list = get_category_list(5, starts_with)
print('cat_list', cat_list)
#return render(request, 'blog/suggest_tag.html', {'suggestions': cat_list })
return cat_list
query
、MyScript.js
では文字列です。ビューは(私はprint('cat_list', cat_list)
を読むことができる)と呼ばれるが、それはエラーをスローされます。リストが空の場合
を=>AttributeError: 'list' object has no attribute 'get'
ときではありません(例:cat_list [<Tag: Home>]
)=>ValueError: too many values to unpack (expected 2)
トレースバックエラー:
cat_list []
Internal Server Error: /blog/suggest-category/
Traceback (most recent call last):
File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\handlers\base.
py", line 235, in get_response
response = middleware_method(request, response)
File "D:\Python\Envs\possedimenti\lib\site-packages\django\middleware\clickjac
king.py", line 31, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'list' object has no attribute 'get'
[28/Dec/2017 16:25:08] "GET /blog/suggest-category/?suggestion= HTTP/1.1" 500 14
867
または空でないcat_listと:
cat_list [<Tag: Home>]
Internal Server Error: /blog/suggest-category/
Traceback (most recent call last):
File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\handlers\base.
py", line 235, in get_response
response = middleware_method(request, response)
File "D:\Python\Envs\possedimenti\lib\site-packages\django\middleware\clickjac
king.py", line 31, in process_response
if response.get('X-Frame-Options') is not None:
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\query.py"
, line 378, in get
clone = self.filter(*args, **kwargs)
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\query.py"
, line 790, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\query.py"
, line 808, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\sql\query
.py", line 1243, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\sql\query
.py", line 1269, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "D:\Python\Envs\possedimenti\lib\site-packages\django\db\models\sql\query
.py", line 1146, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
[28/Dec/2017 16:08:23] "GET /blog/suggest-category/?suggestion=h HTTP/1.1" 500 1
5797
たぶんTagモデルを助けることができる、それがtaggitから来ている:
@python_2_unicode_compatible
class TagBase(models.Model):
name = models.CharField(verbose_name=_('Name'), unique=True, max_length=100)
slug = models.SlugField(verbose_name=_('Slug'), unique=True, max_length=100)
def __str__(self):
return self.name
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self.pk and not self.slug:
self.slug = self.slugify(self.name)
from django.db import router
using = kwargs.get("using") or router.db_for_write(
type(self), instance=self)
# Make sure we write to the same db for all attempted writes,
# with a multi-master setup, theoretically we could try to
# write and rollback on different DBs
kwargs["using"] = using
# Be oportunistic and try to save the tag, this should work for
# most cases ;)
try:
with atomic(using=using):
res = super(TagBase, self).save(*args, **kwargs)
return res
except IntegrityError:
pass
# Now try to find existing slugs with similar names
slugs = set(
self.__class__._default_manager
.filter(slug__startswith=self.slug)
.values_list('slug', flat=True)
)
i = 1
while True:
slug = self.slugify(self.name, i)
if slug not in slugs:
self.slug = slug
# We purposely ignore concurrecny issues here for now.
# (That is, till we found a nice solution...)
return super(TagBase, self).save(*args, **kwargs)
i += 1
else:
return super(TagBase, self).save(*args, **kwargs)
def slugify(self, tag, i=None):
slug = default_slugify(unidecode(tag))
if i is not None:
slug += "_%d" % i
return slug
class Tag(TagBase):
class Meta:
verbose_name = _("Tag")
verbose_name_plural = _("Tags")
app_label = 'taggit'
編集: 私は私のview.py
を変更:
def suggest_category(request):
print('suggest_category')
cat_list = []
starts_with = ''
if request.method == 'GET':
starts_with = request.GET['suggestion']
cat_list = get_category_list(5, starts_with)
print('cat_list', cat_list)
return render(request, 'blog/suggest_tag.html', {'suggestions': cat_list })
、ここでは私のテンプレートsuggest_tag.html
です:
{% load i18n %}
<ul>
{% if suggestions %}
{% for c in suggestions %}
<li>{{ c.name }}</li>
{% endfor %}
{% else %}
<li>{% trans "There are no tag present." %}</li>
{% endif %}
</ul>
今作成した部門に書き込みを行います(id='suggestion_div'
)それで十分です。
/編集
Pythonの世界からのバックトレースは、どこにエラーがあったのかを示していますが、あなたはそれを含めていませんでした。どこにでも '.get'を呼び出すことはできません。私はそれを見逃しましたか? –
.getは4行目のスクリプトで呼び出されますが(おそらくあなたは別のことを言っています...)とにかくトレースバックが追加されました。 – fabio
これはJavaScriptの.get呼び出しですが、Pythonエラーが発生しています –