我是 Django 和 Python 的新手。当我单击管理页面中的用户答案时,我收到错误消息。我知道错误的位置是“返回 self.answer.answer”,但我不知道为什么或如何解决它。
错误
AttributeError at /admin/questions/useranswer/
'NoneType' object has no attribute 'answer'
Request Method: GET
Request URL: hxxp://x.x.x.x:8000/admin/questions/useranswer/
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'answer'
Exception Location: /Users/xxx/Desktop/matchmaker/src/questions/models.py in unicode line 31 "which is return self.answer.answer"
Python Executable: /Users/xxx/Desktop/matchmaker/bin/python
Python Version: 2.7.5
模型.py
from django.db import models
from django.contrib.auth.models import User
class Question(models.Model):
user = models.ForeignKey(User)
question = models.CharField(max_length=120)
timestamp = models.DateField(auto_now_add=True, auto_now=False)
update = models.DateField(auto_now_add=False, auto_now=True)
def __unicode__(self, ):
return self.question
class Answer(models.Model):
question = models.ForeignKey(Question)
answer = models.CharField(max_length=120)
timestamp = models.DateField(auto_now_add=True, auto_now=False)
update = models.DateField(auto_now_add=False, auto_now=True)
def __unicode__(self, ):
return self.answer
class UserAnswer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
answer = models.ForeignKey(Answer, null=True, blank=True)
timestamp = models.DateField(auto_now_add=True, auto_now=False)
update = models.DateField(auto_now_add=False, auto_now=True)
def __unicode__(self, ):
return self.answer.answer
视图.py
from django.contrib.auth.models import User
from django.shortcuts import render_to_response, RequestContext, Http404, HttpResponseRedirect
from .models import Question, Answer, UserAnswer
def all_questions(request):
questions = Question.objects.all()
if request.method == 'POST':
question_id = request.POST['question_id']
answer_form = request.POST['answer']
user = User.objects.get(username=request.user)
question = Question.objects.get(id=question_id)
answer = Answer.objects.get(question=question, answer=answer_form)
answered, created = UserAnswer.objects.get_or_create(user=user, question=question)
answered.answer = answer
answered.save()
return render_to_response('questions/all.html', locals(), context_instance=RequestContext(request))
管理员.py
from django.contrib import admin
from .models import Question, Answer, UserAnswer
class QuestionAdmin(admin.ModelAdmin):
class Meta:
model = Question
admin.site.register(Question, QuestionAdmin)
class AnswerAdmin(admin.ModelAdmin):
class Meta:
model = Answer
admin.site.register(Answer, AnswerAdmin)
class UserAnswerAdmin(admin.ModelAdmin):
class Meta:
model = UserAnswer
admin.site.register(UserAnswer, UserAnswerAdmin)