创建项目

Django 命令

  1. (learnDjango) ~\> django-admin
  2. Type 'django-admin help <subcommand>' for help on a specific subcommand.
  3. Available subcommands:
  4. [django]
  5. check
  6. compilemessages
  7. createcachetable
  8. dbshell
  9. diffsettings
  10. dumpdata
  11. flush
  12. inspectdb
  13. loaddata
  14. makemessages
  15. makemigrations
  16. migrate
  17. runserver
  18. sendtestemail
  19. shell
  20. showmigrations
  21. sqlflush
  22. sqlmigrate
  23. sqlsequencereset
  24. squashmigrations
  25. startapp
  26. startproject
  27. test
  28. testserver
  29. Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE
  30. or call settings.configure() before accessing settings.).

创建一个项目并尝试运行

  1. django-admin startproject demo
  2. cd demo
  3. python manage.py runserver

创建管理员用户

  1. python manage.py migrate
  2. python .\manage.py createsuperuser

运行项目

  1. # http://127.0.0.1:8000/
  2. python manage.py runserver
  3. # http://127.0.0.1:8080/
  4. python manage.py runserver 8080
  5. # http://ip:8000/ 可以从外部访问
  6. python manage.py runserver 0:8000

Hello world!

创建应用

  1. python manage.py startapp helloworld

编辑 settings.py ,添加如下代码

  1. INSTALLED_APPS = [
  2. 'helloworld.apps.HelloworldConfig',
  3. ]

编辑 helloworld/templates/helloworld/index.html

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Hello world!</title>
  6. </head>
  7. <body>
  8. <h1>{{ text }}</h1>
  9. </body>
  10. </html>

编辑 helloworld/views.py

  1. from django.shortcuts import render
  2. def index(request):
  3. return render(request, 'helloworld/index.html', {'text': "Hello world!"})

编辑 helloworld/urls.py

  1. from django.urls import path
  2. from . import views
  3. urlpatterns = [
  4. path('', views.index, name='index'),
  5. ]

编辑 urls.py

  1. from django.contrib import admin
  2. from django.urls import include, path
  3. urlpatterns = [
  4. path('helloworld/', include('helloworld.urls')),
  5. ]

编写一个投票应用

创建应用

  1. python manage.py startapp polls

编辑 settings.py ,添加如下代码

  1. INSTALLED_APPS = [
  2. 'polls.apps.PollsConfig',
  3. ]

定义模型

编辑 polls/models.py ,定义模型并创建表结构

  1. from django.db import models
  2. # 话题
  3. class Topic(models.Model):
  4. topic_text = models.CharField(max_length=200)
  5. topic_date = models.DateTimeField('date published')
  6. # 返回对象描述信息
  7. def __str__(self):
  8. return self.topic_text
  9. # 投票选项
  10. class Choice(models.Model):
  11. topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
  12. choice_text = models.CharField(max_length=200)
  13. choice_count = models.IntegerField(default=0)
  14. # 返回对象描述信息
  15. def __str__(self):
  16. return self.choice_text
  1. # 让 Django 知道模型变更
  2. python manage.py makemigrations polls
  3. # 创建表结构
  4. python manage.py migrate polls

编辑模板

编辑 index.html

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>polls</title>
  6. {% load static %}
  7. <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
  8. </head>
  9. <body>
  10. {#显示话题列表#}
  11. {% if latest_topic_list %}
  12. <ul>
  13. {% for topic in latest_topic_list %}
  14. <li><a href="{% url 'polls:detail' topic.id %}">{{ topic.topic_text }}</a></li>
  15. {% endfor %}
  16. </ul>
  17. {% else %}
  18. <p>话题列表为空!</p>
  19. {% endif %}
  20. </body>
  21. </html>

编辑 detail.html

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>detail</title>
  6. </head>
  7. <body>
  8. {#话题内容#}
  9. <p>{{ topic.topic_text }}</p>
  10. {#错误信息#}
  11. {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %}
  12. {#表单部分#}
  13. <form action="{% url 'polls:vote' topic.id %}" method="post">
  14. {% csrf_token %}
  15. {% for choice in topic.choice_set.all %}
  16. <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
  17. <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
  18. <br>
  19. {% endfor %}
  20. <br>
  21. <input type="submit" value="Vote">
  22. </form>
  23. </body>
  24. </html>

编辑 result.html

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>results</title>
  6. </head>
  7. <body>
  8. {#话题内容#}
  9. <p>{{ topic.topic_text }}</p>
  10. {#投票结果#}
  11. <table border="1">
  12. {% for choice in topic.choice_set.all %}
  13. <tr>
  14. <td>{{ choice.choice_text }}</td>
  15. <td>{{ choice.choice_count }}</td>
  16. </tr>
  17. {% endfor %}
  18. </table>
  19. <br>
  20. {#再次投票#}
  21. <a href="{% url 'polls:detail' topic.id %}">再次投票</a>
  22. </body>
  23. </html>

编辑视图

编辑 polls/views.py

  1. from django.shortcuts import render, get_object_or_404
  2. from django.http import HttpResponseRedirect
  3. from django.urls import reverse
  4. from django.views import generic
  5. from django.utils import timezone
  6. from .models import Topic, Choice
  7. # 主页视图
  8. class IndexView(generic.ListView):
  9. template_name = 'polls/index.html'
  10. context_object_name = 'latest_topic_list'
  11. def get_queryset(self):
  12. return Topic.objects.filter(
  13. topic_date__lte=timezone.now()
  14. ).order_by('-topic_date')[:5]
  15. # 话题详情页视图
  16. class DetailView(generic.DetailView):
  17. model = Topic
  18. template_name = 'polls/detail.html'
  19. # 投票结果视图
  20. class ResultsView(generic.DetailView):
  21. model = Topic
  22. template_name = 'polls/result.html'
  23. # 投票
  24. def vote(request, topic_id):
  25. topic = get_object_or_404(Topic, pk=topic_id)
  26. try:
  27. choice_selected = topic.choice_set.get(pk=request.POST['choice'])
  28. except (KeyError, Choice.DoesNotExist):
  29. return render(request, 'polls/detail.html', {
  30. 'topic': topic,
  31. 'error_message': "你没有选择一个选项!",
  32. })
  33. else:
  34. choice_selected.choice_count += 1
  35. choice_selected.save()
  36. # 重定向到 result 页面
  37. return HttpResponseRedirect(reverse('polls:result', args=(topic.id,)))

编辑路由

编辑路由 polls/urls.py

  1. from django.urls import path
  2. from . import views
  3. app_name = 'polls'
  4. urlpatterns = [
  5. # ex: /polls/
  6. path('', views.IndexView.as_view(), name='index'),
  7. # ex: /polls/5/
  8. path('<int:pk>/', views.DetailView.as_view(), name='detail'),
  9. # ex: /polls/5/results/
  10. path('<int:pk>/result/', views.ResultsView.as_view(), name='result'),
  11. # ex: /polls/5/vote/
  12. path('<int:question_id>/vote/', views.vote, name='vote'),
  13. ]

编辑全局路由 urls.py

  1. from django.contrib import admin
  2. from django.urls import include, path
  3. urlpatterns = [
  4. path('polls/', include('polls.urls')),
  5. ]