首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$.get()在回调(?)上出现错误

$.get()在回调(?)上出现错误
EN

Stack Overflow用户
提问于 2017-12-28 15:11:55
回答 1查看 53关注 0票数 0

我知道有很多这样的问题,但我找不到解决问题的办法。

MyScript.js

代码语言:javascript
复制
$('#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

代码语言:javascript
复制
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空跟踪错误:

代码语言:javascript
复制
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不为空:

代码语言:javascript
复制
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

也许可以帮助标记模型,它来自于taggit:

代码语言:javascript
复制
@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

代码语言:javascript
复制
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

代码语言:javascript
复制
{% 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')中,这样它就足够工作了。

/edit

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-28 17:20:12

您的错误是由从您的视图返回一些不是HttpResponse的内容造成的。

从代码中还不清楚您想要发送到JavaScript的是什么,但是不管是什么,它都需要封装在HttpResponse或其中的一个子类中。也许你想序列化一个查询集?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48009862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档