1

我的主要問題是:如果用戶是素數的所有者,那麼它應該返回True。但它總是返回錯誤Django如果在DetailView中的語句返回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 %} 

回答

4

總理是一個模型,而不是對象。
嘗試更改總理到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 
+1

是究竟這是我錯過了。非常感謝你的朋友 –

+1

歡迎:)如果答案解決了問題,請將其標記爲正確答案。 –

+1

我會但你回答這麼快,我仍然需要5分鐘,直到我可以 –