我知道有很多这样的问题,但我找不到解决问题的方法。
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为空的跟踪错误:
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'
),所以它足够工作。
/编辑
您的错误是由您从视图中返回不是HttpResponse的内容引起的。
从代码中确切地知道你想要发送给JavaScript的内容并不清楚,但无论它是什么,它都需要包装在HttpResponse或它的子类中。也许你想序列化一个查询集?