Django if 语句在 DetailView returns False
Django if statement in DetailView returns False
我的主要问题是:如果用户是 prime 的所有者,那么它应该 return True。但它总是 returns False.
我的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 %}
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
我的主要问题是:如果用户是 prime 的所有者,那么它应该 return True。但它总是 returns False.
我的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 %}
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