【发布时间】:2020-05-13 11:35:58
【问题描述】:
我尝试了 django polls 应用程序但得到了这个,我的模型包含外键但我不明白问题出在哪里
from django.db import models
class Question(models.Model):
question = models.CharField(max_length = 200)
pub_date = models.DateTimeField('published date')
def __str__(self):
return self.question
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
vote = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
这是视图:
def vote(request , primary_key):
question = get_object_or_404(models.Question, id=primary_key)
try:
selected_choice = question.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request,'polls/detail.html',{
'question' : question ,
'error_message' : "u didn't select a choice."
})
else:
selected_choice.vote += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args = (question.id)))
网址:
urlpatterns = [
re_path(r'^$', views.index , name = 'index'),
re_path(r'^(?P<primary_key>[0-9]+)/$',views.detail, name = 'detail'),
re_path(r'^(?P<primary_key>[0-9]+)/results/$' , views.results , name = 'results'),
re_path(r'^(?P<primary_key>[0-9]+)/vote/$' , views.vote , name = 'vote'),
]
【问题讨论】:
-
能否提供完整的错误回溯?
-
能否提供在
views.py上进行的导入
标签: django python-3.x django-models django-views