https://docs.djangoproject.com/en/2.2/intro/tutorial01/
django-admin startproject mysite
cd mysite
django-admin startapp polls
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
]
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/',include('polls.urls')),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是index页面</title>
</head>
<body>
<h1>这是index页面</h1>
</body>
</html>
os.path.join(BASE_DIR,'polls/templates')
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
python manage.py runserver
返回结果
image.png
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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
python manage.py makemigrations polls
python manage.py sqlmigrate polls 0001
python manage.py migrate
from polls.models import Choice, Question
Question.objects.all()
from django.utils import timezone
q = Question(question_text="你的性别是?", pub_date=timezone.now())
q.save()
q.choice_set.create(choice_text='男', votes=0)
q.choice_set.create(choice_text='女', votes=0)
q.choice_set.create(choice_text='不告诉你', votes=0)
q = Question(question_text="你喜欢的运动是?", pub_date=timezone.now())
q.choice_set.create(choice_text='篮球', votes=0)
q.choice_set.create(choice_text='足球', votes=0)
q.choice_set.create(choice_text='排球', votes=0)
q.choice_set.create(choice_text='不告诉你', votes=0)
Question.objects.all()
Choice.objects.all()
python manage.py createsuperuser
依次输入用户名,邮箱,密码
python manage.py runserver
访问 http://127.0.0.1:8000/admin/ 结果
image.png
from django.contrib import admin
# Register your models here.
from .models import Question
admin.site.register(Question)
刷新,重新访问http://127.0.0.1:8000/admin/
结果
image.png
image.png
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from .models import Question
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {"latest_question_list":latest_question_list}
return render(request,'index.html',context= context)
def detail(request,question_id):
question = get_object_or_404(Question,pk=question_id)
return render(request,'detail.html',context={'question':question})
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
path('<int:question_id>/',views.detail,name="detail"),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是index页面</title>
</head>
<body>
<h1>这是index页面</h1>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{{ question.id }}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是详情页面</title>
</head>
<body>
<h1>这是详情页面</h1>
<h2>{{ question.question_text }}</h2>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</body>
</html>
结果
image.png
image.png
li a {
color:green
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是index页面</title>
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
<h1>这是index页面</h1>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{{ question.id }}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是详情页面</title>
</head>
<body>
<h1>这是详情页面</h1>
<h2>{{ question.question_text }}</h2>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</labelfor>
{% endfor %}
<input type="submit" value="Vote">
</form>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</body>
</html>
results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是结果页面</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li>
{% endfor %}
</ul>
<a href="{% url 'detail' question.id %}"> Vote again ?</a>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index,name='index'),
path('<int:question_id>/',views.detail,name="detail"),
path('<int:question_id>/vote/',views.vote,name='vote'),
path('<int:question_id>/results/',views.results,name="results"),
]
views.py
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import Http404
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Question
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {"latest_question_list":latest_question_list}
return render(request,'index.html',context= context)
def detail(request,question_id):
try:
question = get_object_or_404(Question,pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist!")
return render(request,'detail.html',context={'question':question})
def vote(request,question_id):
question = get_object_or_404(Question,pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError,choice.DoesNotExist):
return render(request,'detail.html',context={'question':question,
'error_message':"You did not select a choice!"})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('results',args=(question_id,)))
def results(request,question_id):
question = get_object_or_404(Question,pk=question_id)
return render(request,'results.html',context={'question':question})
model.py
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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
image.png
image.png
image.png
image.png
image.png
至此这个例子就重复完了!