Django尝试为“ AnonymousUser”添加错误

时间:2019-03-17 19:30:36

标签: django django-templates django-views

我只是一个学生。我有这种代码。我对用户成员使用“尝试除外”条件。但我想知道如果用户未登录,该如何解决'AnonymousUser'对象不可迭代错误。我试图通过使用user.is_authenticated隐藏禁用的按钮,但它无法正常工作。 (注意:我认为BookDetail中需要登录才能解决此问题,但我希望即使用户未登录也可以使用它)

views.py

def BookDetail(request, id):
most_recent = Book.objects.order_by('-timestamp')[:3]
book= get_object_or_404(Book, id=id)
form = CommentForm(request.POST or None)
if request.method == "POST":
    if form.is_valid():
        form.instance.user = request.user
        form.instance.post = book
        form.save()
        return redirect(reverse("book-detail", kwargs={
            'id': book.pk
        }))
try: 
    user_membership = Customer.objects.get(user=request.user)
except Customer.DoesNotExist:
    user_membership = None

context = {
    'user_membership': user_membership,
    'form': form,
    'book': book,
    'most_recent': most_recent,

}
return render(request, 'catalog/book_detail.html', context)

和我的book_detail.html

{% if user_membership and user_membership.user == request.user %}
        {% for content in book.pages %}
            <a href="{{ content.get_absolute_url }}" class="site-btn">Read</a>
        {% endfor %}
        {% else %}
        <button class="site-btn" disabled="disabled">VIP</button>
        {% endif %}

1 个答案:

答案 0 :(得分:0)

您可以使用is_anonymous属性检查AnonymousUser-您可以在docs中阅读更多内容。

例如,您可以像这样编辑代码:

def BookDetail(request, id):
    most_recent = Book.objects.order_by('-timestamp')[:3]
    book= get_object_or_404(Book, id=id)
    form = CommentForm(request.POST or None)
    if request.method == "POST":
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = book
            form.save()
            return redirect(reverse("book-detail", kwargs={
                'id': book.pk
            }))

    if request.user.is_anonymous:
        user_membership = None
    else:
        try:
            user_membership = Customer.objects.get(user=request.user)
        except Customer.DoesNotExist:
            user_membership = None

    context = {
        'user_membership': user_membership,
        'form': form,
        'book': book,
        'most_recent': most_recent,

    }
    return render(request, 'catalog/book_detail.html', context)