[Web Development 2] Deploy a set of voting websites in the Django framework

The principle of Django, URLS routing receives the client access request ------> view view function to process the request --------> models model (database) to process the data ------ ---> View view function to process the data ---------> template template (HTML) to display the data, feedback to the client

1. Initialize the database and generate users in the management background. Login management background

python manage.py migrate #Initialize the database

python manage.py createsuperuser #Create super user

Second, create a model, a model, that is, a class function associated with a database, such as a voting system, then there are voting items, voting item creation time, voting content options, voting content option creation time, and number of votes. Following the guidelines of the database, we separate the voting items and the voting content options in two tables.

Open models.py

from django.db import models

# Create your models here.
Class Question (models.Model):
    #Create such a class, inherited from the parent class question_text = models.CharField (max_length = 200) #Create an instance, the type is character, the maximum length is 200
    publish_date = models.DateTimeField ( 'publish date')         #Create an instance of type time, declared as xxxx
    
    def __str __ (self): use the str method to return the question content
return self.question_text

class Choice (models.Model):
    #Create such a class, inherited from the parent class choice_text = models.CharField (max_length = 100) #Create an instance, the type is character, the maximum length is 100
    publish_date = models.DateTimeField ('publish date') # Create instance, type is time, declared as xxxx
    vote = models.IntegerField (default = 0) #Create instance, type is number, default is 0
    question = models.ForeignKey (Question, on_delete = models.CASCADE) #Create instance, type For (Question) foreign key, delete the associated
    
    def __str __ (self): Use the str method to return the question option content
        return self.choice_text

3. Add the application to the project and register the model to the background management. And optimize the management background.

1. Open settings.py

2. Open admin.py

from django.contrib import admin
from .models import Question, Choice #Import module
class QuestionAdmin (admin.ModelAdmin): #New model, integrated in the parent class
    list_display = ('question_text', 'publish_date') #Optimize the background manager to display
    list_filter = ('publish_date',) #Use time as a filter
    search_fields = ('question_text',)
    #Use content as a searcher ordering = ('-publish_date', 'question_text') #Use descending time to sort, use question sorting
    date_hierarchy = 'publish_date' #Use time as the timeline

class ChoiceAdmin(admin.ModelAdmin):
    list_display = ('question', 'choice_text', 'vote', 'publish_date')
    list_filter = ('publish_date',)
    search_fields = ('choice_text',)
    ordering = ('-publish_date', 'vote')
    date_hierarchy = 'publish_date'
    raw_id_fields = ('question',)                                                     #优化选项,效果是显示question详情

admin.site.register (Question, QuestionAdmin)
#Register to the management background admin.site.register (Choice, ChoiceAdmin)

3. The effect is shown in the figure

4. We all said that the model is related to the database. Now the model is there. Then you should put the model. Apply to the database and let the database generate the fields in the model.

python manage.py makemigrations #Generate database statements

python manage.py migrate #execute statement

3. Create questions and related options on the web page.

Generate a problem

Options for generating corresponding questions

Fourth, check the database, you can get, polls_question and polls_choice these two tables, with the content we just entered. And, Django automatically added the id primary key for them. And there are foreign key constraints in the choice table.

5. Make a homepage and walk through how Django works

According to the working principle of Django, the first step we need to modify is the application urls file

1. Open urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

The route to index has already been written here. The index function in the dating view.

2. Open views.py

from django.shortcuts import render, HttpResponse
from .models import Question, Choice                                          #导入模块

# Create your views here.
Def index (request): #Create index function
    question = Question.objects.all () #Define an instance question, an object query collection with a value of Question
    return render (request, 'polls / index.html', {'question': question}) #Send data to index.html under polls, parameter name is question, value is question

3. Create a template directory, create a template file

mkdir -p  polls/templates/polls

4. Write index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls主页</title>
</head>
<body>
<ul>
    {% for q in question %}
    <li>
        <a href="此处填写的是超链接跳转的页面,暂时留空">
            {{ q.question_text }}
        </a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ q.publish_date }}
    </li>
    {% endfor%}
</ul>
</body>
</html>

The effect is as shown

6. Make a detail page for each question, access the homepage, and jump.

1. It is customary to modify the urls file.

Open urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url (r '^ $', views.index, name = 'index'),
    url (r '(? P <question_id> \ d +) / $', views.detail, name = 'detail') # ## Planning url, we use numbers to make a variable. Then match the id of polls_question according to the number to achieve accurate positioning to question_text.
]

2. Modify the views.py file. Added detail view function to get the data and send it to the template file.

def detail (request, question_id): #question_id is the
    question obtained from url = Question.objects.get (id = question_id) #Through the get method, get the corresponding question instance
    return render (request, 'polls / detail.html ', {' question ': question})

3. Create the detail.html file, and then write the corresponding view interface according to actual needs

<! DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <title> vote details page </ title>
</ head>
<body>
<p> {{question} } </ p>
<form action = "Leave blank here, the role is to submit data to vote">
    {% for c in question.choice_set.all%}
        <input type = "radio" name = "c_id" value = "{{c.id}}"> {{c.choice_text}} ## name and value, which will be explained later
    {% endfor%}
    <input type = "submit" value = "Submit">
</ form>
< / body>
</ html>

4. Modify the homepage index.html to match the template of detail.tml for the hyperlink

Open index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls主页</title>
</head>
<body>
<ul>
    {% for q in question %}
    <li>
        <a href="{% url 'detail' question_id=q.id %}">    #调用url模块,匹配detail视图函数,作为参数的question。值为q.id
            {{ q.question_text }}
        </a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ q.publish_date }}
    </li>
    {% endfor%}
</ul>
</body>
</html>

At this point, we have achieved. The problem of hyperlink jump.

Seven, the work of producing voting results

1. New record in urls.py file

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'(?P<question_id>\d+)/$', views.detail, name='detail'),
    url(r'(?P<question_id>\d+)/result/$', views.result, name='result'),   #新增
]

2. Added functions in views.py file

def result(request, question_id):
    question = Question.objects.get(id=question_id)
    return render(request, 'polls/result.html', {'question': question})

3. Add the result.html file in the template to plan the data according to actual needs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>投票结果页</title>
</head>
<body>
<table border="1px">
    <tr>
        <td colspan="2">{{ question }}</td>
    </tr>
    {% for c in question.choice_set.all %}
    <tr>
        <td>
            {{ c.choice_text }}
        </td>
        <td>
            票数:{{ c.vote }}
        </td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

The effect is as shown

Eight, create a voting program, the idea should be like this, in the home page, choose which question is equivalent to using question_id, open the corresponding detail page, and then in the details page, choose which option, the id of the option will be from the form Post to vote program. The vote program + 1s the data to vote. Then, after the voting is over, feedback the result page to the client. Let's make the code of the detail homepage first, and then perfect the voting procedure.

1、

1. New code for urls.py file

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'(?P<question_id>\d+)/$', views.detail, name='detail'),
    url(r'(?P<question_id>\d+)/result/$', views.result, name='result'),
    url(r'(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
]

2. Added views.py file record.

def vote (request, question_id):
    #Create a vote program, the parameter question_id is to get choice_id = request.POST.get ('c_id') from the detail #Use the request method to get the parameter c_id
    c = Choice.objects.get (id = choice_id) #Get an instance of Choice
    c.vote + = 1
    #Number of votes +1 c.save ()
    return redirect ('result', question_id = question_id) #Redirect to the result page.

3. Modify the detail.py file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>投票详情页</title>
</head>
<body>
<p>{{ question }}</p>
<form action="{% url 'vote' question_id=question.id %}" method="post">    #方式为post,然后提交数据到vote,参数为XXXXX
    {% for c in question.choice_set.all %}
        <input type="radio" name="c_id" value="{{ c.id }}">{{ c.choice_text }}
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

almost done

The effect is as follows

CSS styles, bootstrap styles, returning to the homepage, etc. can be added.

Published 73 original articles · praised 4 · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_27592485/article/details/102958808