详细信息中的Django if语句返回False

时间:2015-10-12 21:17:47

标签: django if-statement django-models django-views django-users

对我来说,主要的问题是:如果用户是素数的所有者,那么它应该返回 True 。但它总是返回错误

我的models.py:

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse


class Prime(models.Model):
    prime_owner = models.ForeignKey(User, null=True)
    prime_name = models.CharField(max_length=100)
    prime_address = models.CharField(max_length=250)

我的views.py:

class PrimeDetails(generic.DetailView):
    template_name ='prime/primedetails.html'
    model = Prime


    def get_context_data(self, **kwargs):
        context = super(PrimeDetails, self).get_context_data(**kwargs)
        user = self.request.user
        prime_owner = Prime.prime_owner
        if user == prime_owner:
            owner = True
        else:
            owner = False
        context['owner'] = owner
        return context

primedetails.html

{% extends 'prime/base.html' %}

{% block content %}
<div class="container">
    <h1>{{ owner }}</h1>
    <h1>{{object.prime_name }}</h1>
    <h3>{{object.prime_address}}</h3>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:4)

Prime是一个模型,而不是对象 尝试将Prime更改为self.get_object(),如下所示:

 def get_context_data(self, **kwargs):
        context = super(PrimeDetails, self).get_context_data(**kwargs)
        user = self.request.user
        prime_owner = self.get_object().prime_owner
        if user == prime_owner:
            owner = True
        else:
            owner = False
        context['owner'] = owner
        return context