diff --git a/polls/models.py b/polls/models.py index 41459ac..a8bab74 100644 --- a/polls/models.py +++ b/polls/models.py @@ -6,8 +6,14 @@ class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateField('date published') + def __str__(self): + return self.question_text + class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) + + def __str__(self): + return self.choice_text diff --git a/polls/templates/detail.html b/polls/templates/detail.html new file mode 100644 index 0000000..1a9dfba --- /dev/null +++ b/polls/templates/detail.html @@ -0,0 +1,10 @@ + + + + + Title-{{ question }} + + +{{ question }} + + \ No newline at end of file diff --git a/polls/templates/index.html b/polls/templates/index.html new file mode 100644 index 0000000..d2d2b1b --- /dev/null +++ b/polls/templates/index.html @@ -0,0 +1,18 @@ + + + + + Title + + + {% if latest_question_list %} + + {% else %} +

No polls are available.

+ {% endif %} + + \ No newline at end of file diff --git a/polls/views.py b/polls/views.py index 2c3dbe7..9d1a7ec 100644 --- a/polls/views.py +++ b/polls/views.py @@ -1,15 +1,39 @@ from django.shortcuts import render from django.http import HttpResponse +from django.http import Http404 +from .models import Question +from django.template import loader # Create your views here. def index(request): - return HttpResponse("Hello, Django. U are at the polls index") + latest_question_list = Question.objects.order_by('-pub_date')[:5] + # output = ', '.join([q.question_text for q in latest_question_list]) + # return HttpResponse(output) + # 模板使用方式1 + # template = loader.get_template('index.html') + # context = { + # 'latest_question_list': latest_question_list, + # } + # return HttpResponse(template.render(context, request)) + # 模板使用方法2 + context = { + 'latest_question_list': latest_question_list, + } + return render(request, 'index.html', context) def detail(request, question_id): - return HttpResponse(f"You're looking at question {question_id}.") + # return HttpResponse(f"You're looking at question {question_id}.") + # 添加404页面展示 + try: + question = Question.objects.get(pk=question_id) + context = {'question': question} + print(context) + except Question.DoesNotExist: + raise Http404("Question does not exist") + return render(request, 'detail.html', context) def result(request, question_id):