Django创建投票应用

目录

创建应用

创建模型mysite\\polls\\models.py

激活模型mysite\\setting.py

为模型的改变生成迁移文件

应用数据库迁移

创建管理员账号

管理投票应用mysite\\polls\\admin.py

添加视图mysite\\polls\\views.py

添加路径mysite\\polls\\urls.py

创建模版mysite\\polls\\templates\\polls\\index.html

[启动开发服务器python manage.py runserver](#启动开发服务器python manage.py runserver)


关于数据库配置,更多内容请看在Django中配置PostgreSQL-CSDN博客

创建应用

bash 复制代码
python manage.py startapp polls

创建模型

mysite\\polls\\models.py

python 复制代码
from django.db import models


class Question(models.Model):

    question_text = models.CharField(max_length=200)

    pub_date = models.DateTimeField("date published")

  
class Choice(models.Model):

    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    choice_text = models.CharField(max_length=200)

    votes = models.IntegerField(default=0)

激活模型

mysite\\setting.py

python 复制代码
INSTALLED_APPS = [

    "polls.apps.PollsConfig",

    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

]

为模型的改变生成迁移文件

bash 复制代码
python manage.py makemigrations polls

应用数据库迁移

python 复制代码
python manage.py migrate

创建管理员账号

python 复制代码
python manage.py createsuperuser

管理投票应用

mysite\\polls\\admin.py

python 复制代码
from django.contrib import admin
from .models import Question,Choice

# class ChoiceInline(admin.StackedInline):

#     model = Choice

#     extra = 3

# 通过 TabularInline (替代 StackedInline )  单行显示关联

class ChoiceInline(admin.TabularInline):

    model = Choice

    extra = 3

  

class QuestionAdmin(admin.ModelAdmin):

    fieldsets = [

        (None, {"fields": ["question_text"]}),

        ("Date information", {"fields": ["pub_date"], "classes": ["collapse"]}),

    ]

    inlines = [ChoiceInline]

  
  

admin.site.register(Question, QuestionAdmin)

添加视图

mysite\\polls\\views.py

python 复制代码
from django.shortcuts import render, get_object_or_404,HttpResponseRedirect
from django.http import HttpResponse
from django.urls import reverse
from .models import Question,Choice

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = "polls/index.html"
    context = {
        "latest_question_list": latest_question_list,
    }
    return render(request,template,context)

def detail(request,question_id):
    question = get_object_or_404(Question,pk=question_id)
    template = "polls/detail.html"
    context = {
        "question":question,
    }

    return render(request,template,context)

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    template = "polls/results.html"
    context = {
        "question": question,
    }

    return render(request,template,context)

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):
        template = "polls/detail.html"
        context = {
                "question": question,
                "error_message": "You didn't select a choice.",
        }
        return render(request,template,context)
    else:

        selected_choice.votes += 1
        selected_choice.save()

        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))

添加路径

mysite\\polls\\urls.py

python 复制代码
from django.urls import path
from . import views

app_name = "polls"
urlpatterns = [
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:question_id>/results/", views.results, name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

mysite\\urls.py

python 复制代码
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path("polls/",include("polls.urls")),
    path("admin/", admin.site.urls),
]

创建模版

mysite\\polls\\templates\\polls\\index.html

html 复制代码
<!DOCTYPE html>

<html lang="zh">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

  

<body>

    {% if latest_question_list %}

    <ul>

        {% for question in latest_question_list %}

        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

        {% endfor %}

    </ul>

    {% else %}

    <p>No polls are available.</p>

    {% endif %}

</body>

</html>

mysite\\polls\\templates\\polls\\detail.html

html 复制代码
<!DOCTYPE html>

<html lang="zh">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>


<body>

    <form action="{% url 'polls:vote' question.id %}" method="post">

        {% csrf_token %}

        <fieldset>

            <legend>

                <h1>{{ question.question_text }}</h1>

            </legend>

            {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

            {% 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 }}</label><br>

            {% endfor %}

        </fieldset>

        <input type="submit" value="Vote">

    </form>

  

</body>

</html>

mysite\\polls\\templates\\polls\\results.html

html 复制代码
<!DOCTYPE html>

<html lang="zh">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</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 'polls:detail' question.id %}">Vote again?</a>

</body>

</html>

启动开发服务器

python manage.py runserver

管理地址

http://127.0.0.1:8000/admin/
应用地址

http://127.0.0.1:8000/polls/

相关推荐
紫雾凌寒41 分钟前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
jay丿1 小时前
Django模板系统深入
数据库·django·sqlite
程序员杰哥1 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋10 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户11 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿11 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别