程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python full stack 100 day learning notes] day43 Django static resources and Ajax requests

編輯:Python

Static resources and Ajax request

Based on the previous knowledge , We can already use Django Framework to complete Web Application development . Next, we will try to implement a voting Application , The specific requirement is that users first view “ Subject introduction ” page , This page shows all the subjects offered by a school ; By clicking on a subject , Can enter the “ Teacher introduction ” page , This page shows the details of all teachers in this subject , You can click on this page for the teacher “ Praise ” or “ Bad review ”; If the user is not logged in , When voting, you will jump to “ The login page ” Ask the user to log in , You can vote only after you login successfully ; For unregistered users , Can be in “ The login page ” Click on “ New user registration ” Get into “ Registration page ” Complete the user registration operation , After successful registration, you will jump to “ The login page ”, If the registration fails, you will get the corresponding prompt .

preparation

Because I have explained in detail how to create Django Project and related configuration of the project , So let's skip this part , The only thing to say is , From the above description of voting application requirements, we can analyze three business entities : Discipline 、 Teachers and users . There is usually a one to many relationship between subjects and teachers ( There are many teachers in a subject , A teacher usually belongs to only one subject ), Users vote for teachers , So there is a many to many relationship with teachers ( A user can vote for multiple teachers , A teacher can also receive votes from multiple users ). First, modify the models.py File to define the data model , First, give the model of subject and teacher .

from django.db import models
class Subject(models.Model):
""" Discipline """
no = models.IntegerField(primary_key=True, verbose_name=' Number ')
name = models.CharField(max_length=20, verbose_name=' name ')
intro = models.CharField(max_length=511, default='', verbose_name=' Introduce ')
create_date = models.DateField(null=True, verbose_name=' Date of establishment ')
is_hot = models.BooleanField(default=False, verbose_name=' Is it hot ')
def __str__(self):
return self.name
class Meta:
db_table = 'tb_subject'
verbose_name = ' Discipline '
verbose_name_plural = ' Discipline '
class Teacher(models.Model):
""" teacher """
no = models.AutoField(primary_key=True, verbose_name=' Number ')
name = models.CharField(max_length=20, verbose_name=' full name ')
detail = models.CharField(max_length=1023, default='', blank=True, verbose_name=' details ')
photo = models.CharField(max_length=1023, default='', verbose_name=' Photo ')
good_count = models.IntegerField(default=0, verbose_name=' Good reviews ')
bad_count = models.IntegerField(default=0, verbose_name=' Bad reviews ')
subject = models.ForeignKey(to=Subject, on_delete=models.PROTECT, db_column='sno', verbose_name=' Subject ')
class Meta:
db_table = 'tb_teacher'
verbose_name = ' teacher '
verbose_name_plural = ' teacher '

After model definition , Can pass “ Generate migration ” and “ Perform the migration ” To complete the creation of two-dimensional tables in relational databases , Of course, this requires starting the database server in advance and creating the corresponding database , At the same time, we have installed PyMySQL And the corresponding configuration is completed , These contents will not be repeated here .

(venv)$ python manage.py makemigrations vote
...
(venv)$ python manage.py migrate
...

Be careful : To give vote Application generates migration files , Need modification Django project settings.py file , stay INSTALLED_APPS Add vote application .

After model migration , We can use it directly Django Provide background management to add subject and teacher information , You need to register model classes and model management classes first .

from django.contrib import admin
from poll2.forms import UserForm
from poll2.models import Subject, Teacher
class SubjectAdmin(admin.ModelAdmin):
list_display = ('no', 'name', 'create_date', 'is_hot')
ordering = ('no', )
class TeacherAdmin(admin.ModelAdmin):
list_display = ('no', 'name', 'detail', 'good_count', 'bad_count', 'subject')
ordering = ('subject', 'no')
admin.site.register(Subject, SubjectAdmin)
admin.site.register(Teacher, TeacherAdmin)

Next , We can modify views.py file , By writing the view function, first realize “ Subject introduction ” page .

def show_subjects(request):
""" View all disciplines """
subjects = Subject.objects.all()
return render(request, 'subject.html', {
'subjects': subjects})

thus , We also need a template page , The configuration of the template and the usage of the template language in the template page have been briefly introduced before , If you are not familiar with it, you can take a look at the following code , Believe that this is not a difficult thing .

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> All subject information </title>
<style>/* The selector of cascading style sheets is omitted here */</style>
</head>
<body>
<h1> All subjects </h1>
<hr>
{% for subject in subjects %}
<div>
<h3>
<a href="/teachers/?sno={
{ subject.no }}">{
{ subject.name }}</a>
{% if subject.is_hot %}
<img src="/static/images/hot.png" width="32" alt="">
{% endif %}
</h3>
<p>{
{ subject.intro }}</p>
</div>
{% endfor %}
</body>
</html>

In the template above , We added a hyperlink for each subject , Click the hyperlink to view the lecturer information of the subject , To do this, we need to write a view function to process and view the information of teachers in the specified subject .

def show_teachers(request):
""" Show the teacher of the specified subject """
try:
sno = int(request.GET['sno'])
subject = Subject.objects.get(no=sno)
teachers = subject.teacher_set.all()
return render(request, 'teachers.html', {
'subject': subject, 'teachers': teachers})
except (KeyError, ValueError, Subject.DoesNotExist):
return redirect('/')

Template page showing teacher information .

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title> teacher </title>
<style>/* The selector of cascading style sheets is omitted here */</style>
</head>
<body>
<h1>{
{ subject.name }} Subject teacher information </h1>
<hr>
{% if teachers %}
{% for teacher in teachers %}
<div>
<div>
<img src="{% static teacher.photo %}" alt="">
</div>
<div>
<h3>{
{ teacher.name }}</h3>
<p>{
{ teacher.detail }}</p>
<p class="comment">
<a href=""> Praise </a>
(<span>{
{ teacher.good_count }}</span>)
<a href=""> Bad review </a>
(<span>{
{ teacher.bad_count }}</span>)
</p>
</div>
</div>
{% endfor %}
{% else %}
<h3> There is no teacher information of this subject for the time being </h3>
{% endif %}
<p>
<a href="/"> Back to the home page </a>
</p>
</body>
</html>

Load static resources

In the template page above , We used <img> Tag to load the teacher's photo , Template instructions that reference static resources are used {% static %}, To use this instruction , The first thing to use {% load static %} Instruction to load static resources , We put this code at the beginning of the page . In the above project , We put static resources under the name static In the folder of , Three more folders have been created under this folder :css、js and images, Respectively used to save external cascading style sheets 、 external JavaScript File and picture resources . In order to find the folder where static resources are stored , We still need to revise it Django The configuration file for the project settings.py, As shown below :

# The above code is omitted here 
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_URL = '/static/'
# The following code is omitted here 

I'm going to modify urls.py file , Configure user requested URL The corresponding relationship with the view function .

from django.contrib import admin
from django.urls import path
from vote import views
urlpatterns = [
path('', views.show_subjects),
path('teachers/', views.show_teachers),
path('admin/', admin.site.urls),
]

Start the server to run the project , Go to the homepage to check the subject information .

Click on the subject to view the teacher information .

Ajax request

Next we can achieve “ Praise ” and “ Bad review ” The function of , Obviously, if you can implement these two functions without refreshing the page, it will bring a better user experience , So we consider using Ajax Technology to implement “ Praise ” and “ Bad review ”,Ajax Technology we are Web The front-end part has been introduced , No more details here .

First modify the project's urls.py file , by “ Praise ” and “ Bad review ” Function mapping corresponds to URL.

from django.contrib import admin
from django.urls import path
from vote import views
urlpatterns = [
path('', views.show_subjects),
path('teachers/', views.show_teachers),
path('praise/', views.prise_or_criticize),
path('criticize/', views.prise_or_criticize),
path('admin/', admin.site.urls),
]

Design view functions praise_or_criticize To support “ Praise ” and “ Bad review ” function , The view function passes Django Packaged JsonResponse Class serializes the dictionary into JSON String as the response content returned to the browser .

def praise_or_criticize(request):
""" Praise """
try:
tno = int(request.GET['tno'])
teacher = Teacher.objects.get(no=tno)
if request.path.startswith('/praise'):
teacher.good_count += 1
else:
teacher.bad_count += 1
teacher.save()
data = {
'code': 200, 'hint': ' Successful operation '}
except (KeyError, ValueError, Teacher.DoseNotExist):
data = {
'code': 404, 'hint': ' operation failed '}
return JsonResponse(data)

Modify the template page that displays teacher information , introduce jQuery Library to implement event processing 、Ajax Request and DOM operation .

<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title> teacher </title>
<style>/* The selector of cascading style sheets is omitted here */</style>
</head>
<body>
<h1>{
{ subject.name }} Subject teacher information </h1>
<hr>
{% if teachers %}
{% for teacher in teachers %}
<div class="teacher">
<div class="photo">
<img src="{% static teacher.photo %}" height="140" alt="">
</div>
<div class="info">
<h3>{
{ teacher.name }}</h3>
<p>{
{ teacher.detail }}</p>
<p class="comment">
<a href="/praise/?tno={
{ teacher.no }}"> Praise </a>
(<span>{
{ teacher.good_count }}</span>)
&nbsp;&nbsp;
<a href="/criticize/?tno={
{ teacher.no }}"> Bad review </a>
(<span>{
{ teacher.bad_count }}</span>)
</p>
</div>
</div>
{% endfor %}
{% else %}
<h3> There is no teacher information of this subject for the time being </h3>
{% endif %}
<p>
<a href="/"> Back to the home page </a>
</p>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script> $(() => {
 $('.comment>a').on('click', (evt) => {
 evt.preventDefault() let anchor = $(evt.target) let url = anchor.attr('href') $.getJSON(url, (json) => {
 if (json.code == 10001) {
 let span = anchor.next() span.text(parseInt(span.text()) + 1) } else {
 alert(json.hint) } }) }) }) </script>
</body>
</html>

Summary

Only this and nothing more , The core function of this voting project has been completed , In the following section, we will require users to log in to vote , Users without an account can register an account through the registration function .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved