Django验证用户请求

时间:2019-03-17 08:16:41

标签: django django-views django-users

我只是一名学生,目前正在学习django。我的Users / models.py

中有这个
class Membership(models.Model):
membership_type = models.CharField(max_length=50)
price = models.IntegerField(default=100)
description = models.CharField(max_length=200)

def __str__(self):
    return self.membership_type





class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
membership = models.ForeignKey(Membership, on_delete=models.CASCADE,null=True)
reference = models.CharField(max_length=50, null=True)

def __str__(self):
    return self.user.email

这是我的views.py

def BookDetail(request, id):
most_recent = Book.objects.order_by('-timestamp')[:3]
user_membership = get_object_or_404(Customer, user=request.user)
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
        }))
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 request.user != user_membership.user %}
          <button class="site-btn" disabled="disabled">Read</button>
          {% else %}
          {% for content in book.pages %}
         <a href="{{ content.get_absolute_url }}" class="site-btn">Read</a>
          {% endfor %}
        {% endif %}

我遇到了“没有客户与给定查询匹配的错误”的错误。嗯,我在管理面板的“客户”模型中手动添加了用户。它不会在注册(信号)期间自动添加。但我可以。

2 个答案:

答案 0 :(得分:0)

您应该使用类似..

    {% if request.user != customer.user %}
         # disable read btn
    {% else %}
         # show read link
    {% endif %}

答案 1 :(得分:0)

您正在为user_membership对象使用上下文变量Customer。这意味着在模板中查找Customer对象时应使用该名称。例如:

{% if request.user != user_membership.user %}

此外,您还应确保在settings.py中设置了Django的request context processor,以便您可以在模板中使用request对象:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': (
                'django.template.context_processors.request',
            ),
        }
    },
]

更新

如果没有为当前登录用户配置Customer记录,则该代码当前将向浏览器返回404。但是,如果您希望在这种情况下继续渲染模板,则应该修改视图,以便将user_membership变量设置为None:

def BookDetail(request, id):
    most_recent = Book.objects.order_by('-timestamp')[:3]
    try: 
        user_membership = Customer.objects.get(user=request.user)
    except Customer.DoesNotExist:
        user_membership = None

然后修改模板以检查是否设置了user_membership

{% 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">Read</button>
{% endif %}