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


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

Django创建投票应用_第1张图片

创建应用

python manage.py startapp polls

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

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

INSTALLED_APPS = [

    "polls.apps.PollsConfig",

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

]

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

python manage.py makemigrations polls


应用数据库迁移

python manage.py migrate


创建管理员账号

python manage.py createsuperuser

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

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

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

from django.urls import path
from . import views

app_name = "polls"
urlpatterns = [
    path("", views.index, name="index"),
    path("/", views.detail, name="detail"),
    path("/results/", views.results, name="results"),
    path("/vote/", views.vote, name="vote"),
]

mysite\\urls.py

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







    

    

    Document



  



    {% if latest_question_list %}

    
            {% for question in latest_question_list %}         
  • {{ question.question_text }}
  •         {% endfor %}     
    {% else %}     

No polls are available.

    {% endif %}

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







    

    

    Document






    
        {% csrf_token %}         
                             

{{ question.question_text }}

            
            {% if error_message %}

{{ error_message }}

{% endif %}             {% for choice in question.choice_set.all %}                          
            {% endfor %}         
             
  

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







    

    

    Document





    

{{ question.question_text }}

   
            {% for choice in question.choice_set.all %}        
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  •         {% endfor %}    
    Vote again?

启动开发服务器
python manage.py runserver

管理地址
http://127.0.0.1:8000/admin/
应用地址
http://127.0.0.1:8000/polls/

你可能感兴趣的:(django,python)