即使我没有调用GET请求,我的GET请求也会出错

时间:2017-01-23 12:05:50

标签: javascript jquery python ajax django

所以当点击一个元素时,我会触发这个ajax GET函数:

$('a.username').on('click', function() {

    var username = $(this).html();
    var url = window.location.href.split('?')[0];

    $.ajax({
        type: 'GET',
        url: url,
        data: {
            username_clicked: username,
            csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val()
        },
        success: function (data) {
            console.log(data.username_clicked)
        }
    })
});

获取单击元素的文本(也就是用户名)。这成功发送到我的视图,它通过以下代码捕获GET数据:

username_clicked = request.GET.get('username_clicked')
print(username_clicked) #prints the correct text

但是,当我在视图中的上述文本下添加此代码时:

profile = Profile.objects.get(username=username_clicked)
if username_clicked:
    print(profile.age)

它给了我这个错误ONLOAD:

DoesNotExist at /news/151/
    Profile matching query does not exist.

如果我甚至没有触发click()事件,怎么会引发这个错误?加载页面时出现错误。当我手动添加用户名实例时,也可以放心。像这样:profile = Profile.objects.get(username='zorgan'),这很好。但出于某种原因,它不会采用变量。

如果你想知道,这是我的模型

class Profile(models.Model):
    username = models.CharField(max_length=32, default='AnonymousUser')
    age = models.IntegerField(default=0)

    def __str__(self):
        return self.username

有什么想法吗?

完整视图

def article(request, category, id):

    name = resolve(request.path).kwargs['category']
    for a, b in CATEGORY_CHOICES:
        if b == name:
            name = a
            instance = get_object_or_404(Post, id=id, category=name)

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)

    #comments
    comment = CommentForm(request.POST or None)
    ajax_comment = request.POST.get('text')
    comment_length = len(str(ajax_comment))

    comment_list = Comment.objects.filter(destination=id)
    score = CommentScore.objects.filter(comment=comment_list)

    if request.is_ajax():
        if comment.is_valid():
            comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
            comment.save()

            score = CommentScore.objects.create(comment=comment)
            score.save()
            username = str(request.user)
            return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
        else:
            print(comment.errors)


    username_clicked = request.GET.get('username_clicked')
    print(username_clicked)
    profile = Profile.objects.get(username=username_clicked)
    if username_clicked:
        print(profile.age)


    context = {
        'score': score,
        'comment_list': comment_list,
        'comment': comment,
        'instance': instance,
        'allauth_login': allauth_login,
        'allauth_signup': allauth_signup
    }

    return render(request, 'article.html', context)

0 个答案:

没有答案