modify index and detail view with render template.

main
roger 2 years ago
parent a8ab36ffd6
commit dcb683de36
  1. 6
      polls/models.py
  2. 10
      polls/templates/detail.html
  3. 18
      polls/templates/index.html
  4. 28
      polls/views.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

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title-{{ question }}</title>
</head>
<body>
{{ question }}
</body>
</html>

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="https://127.0.0.1/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>

@ -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):

Loading…
Cancel
Save