python web

1.关系(必考)
①#models.py
class banj(models.Model):
mc=models.CharField(max_length=8)
def str(self):
return self.mc
class xues(models.Model):
xm=models.CharField(max_length=8)
bj=models.ForeignKey(banj,on_delete=models.CASCADE,null=True)
def str(self):
return self.xm
②创建班级对象

from faqs.modles import banj
b=banj(mc=”2019级1班”)
b2=banj(mc=”2019级2班”)
b.save()
b2.save()
③创建学生对象

from faqs.models import xues
x=xues(xm=’张三’,bj=b)
x.save()
x2=xues(xm=’李四’,bj=b2)
x2.save()
④通过班级创建学生

x3=b.xues_set.create(xm=”韩梅梅”)
2.用模板实现数据分页(选)
①模型models.py
from django.db import models
class score(models.Model):
kh=models.CharField(max_length=8) #考号
xm=models.CharField(max_length=8) #姓名
yw=models.IntegerField() #语文成绩
sx=models.IntegerField() #数学成绩
yy=models.IntegerField() #英语成绩
②视图views.py
from django.score.paginator import Paginator
from django.shortcuts import render
from . import models
def useTempaltePaginator(request):
objects=models.score.objects.all()
pages=Paginator(objects,10)
page_number=request.GET[‘page’]
page=pages.get_page(page_number)
return render(request,‘pagetemplate.html’,{‘scores’:page})
③配置URL访问视图
from django.contrib import admin
from django.urls import path
from guyunsu6 import views
urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘scores’,views.useTempaltePaginator),
]
1)模型表单
①模型models.py
from django.db import models
class person(models.Model):
name=models.CharField(max_length=8)
age=models.SmallIntegerField()
②模型表单views.py
from django.forms import ModelForm,ValidationError
from .models import person
class personForm(ModelForm):
class Meta:
model = person #指定模型
fields =[‘name’, ‘age’] #指定字段
③视图中使用模型表单
def usePersonForm(request):
if request.method == ‘POST’: #在提交表单时采用POST方法
mform = personForm(request.POST)#用提交的方法初始化表单
if mform.is_valid():#在表单通过验证时执行数据处理
ps=person.objects.filter(name=request.POST[‘name’])#用表单数据查询
if ps.count()==0:
mform.save()#不存在相同姓名时,将数据存入数据库
msg=‘数据已保存!’
else:
msg=‘数据库已存在相同姓名的数据,请勿重复提交!’
else:msg=‘表单数据有错’
else:
mform = personForm()#创建空白表单
msg=“请输入数据添加新记录”
return render(request, ‘temmodelform.html’, {‘mform’: mform,‘msg’:msg})
④自定义模型表单字段
def validate_age(value):
if int(value) < 20:
raise ValidationError(‘年龄不能小于20!’,code=‘min_value’)
elif int(value) > 50:
raise ValidationError(‘年龄不能大于50!’,code=‘max_value’)
class personFormDIY(ModelForm):
#重定义age字段
age=forms.CharField(validators=[validate_age],label=‘年龄’,
widget = forms.NumberInput(),
help_text = ‘年龄为[20,50]以内的整数’)
class Meta:
model = person #指定模型
fields = [‘name’, ‘age’] #指定字段
labels = { ‘name’: ‘姓名’,} #设置字段渲染后的内容
help_texts = {‘name’:‘姓名为中英文字符串’,}#设置字段帮助文本
widgets = {‘name’: forms.Textarea(attrs={‘cols’: 30, ‘rows’: 2}),}
⑤模型表单
def usePersonFormDIY(request):
if request.method == ‘POST’:
mform = personFormDIY(request.POST)
if mform.is_valid():
ps=person.objects.filter(name=request.POST[‘name’])
if ps.count()==0:
mform.save()
msg=‘数据已保存!’
else:
msg=‘数据库已存在相同姓名的数据,请勿重复提交!’
else:msg=‘表单数据有错’
else:
mform = personFormDIY()
msg=“请输入数据添加新记录”
return render(request, ‘temmodelformdiy.html’, {‘mform’: mform,‘msg’:msg})
1.为HelloWorld项目添加导航链接(可能)
①#chapter3\HelloWorld\about\views.py
from django.http import HttpResponse
from django.urls import reverse
def about(request):
s=“HelloWold项目是在本书第一章实践环节中创建的一个Django项目!
创建时间:2019-3-27。
”+
“”+“返回首页”
return HttpResponse(s)
②#chapter3\HelloWorld\HelloWorld\views.py
from django.http import HttpResponse
from django.urls import reverse
def hello(request):
ht=“Hello Wold!
导航列表:
” +
“”+“关于HelloWord”
return HttpResponse(ht)
③#chapter3\HelloWorld\HelloWorld\urls.py
from django.urls import path
from . import views
from about import views as about_views
urlpatterns = [
path(’’,views.hello,name=‘hello’),
path(‘about/’, about_views.about,name=“about”),
]

你可能感兴趣的:(sqlite)