表单
必须指定的东西
- 目的地 用户将数据发送的目的
- 方式 发送数据的HTTP方法
Django自带表单类
编写表单类
- 提前导入forms模块
- 所有的表单类都要继承forms.Form类
- 每个表单字段都有自己的字段类型比如CharField
- 例子中的label用于设置说明标签
from django import forms
class MessageForm(forms.Form):
title = forms.CharField(max_length=20, min_length=3)
content = forms.CharField(widget=forms.Textarea)
email = forms.EmailField()
reply = forms.BooleanField(required=False)
渲染表单views.py
from django.shortcuts import render
from django.http import HttpResponse
from .form import MessageForm #导入包
from django.views.generic import View #类视图
class IndexView(View):
def get(self, request):
form = MessageForm
return render(request, 'index.html', context={'form':form})
def post(self, request):
form = MessageForm(request.POST)
print(form.cleaned_data)
if form.is_valid(): #数据验证
title = form.cleaned_data('title')
content = form.cleaned_data('content')
email = form.cleaned_data('email')
reply = form.cleaned_data('reply')
print(title, content, email, reply)
return HttpResponse('Success')
#用来发表文章的视图
def Test(request):
context = {}
if request.method == 'GET':
form = ArticleForm
print("GET\n", form)
if request.method == 'POST':
form = ArticleForm(request.POST)#表单绑定
print("POST\n", form)
if (form.is_valid()): # 数据校验
print(form.cleaned_data)
title = form.cleaned_data['title']
content = form.cleaned_data['content']
c = Article(title=title, content=content) #保存数据库
c.save()
context['form'] = form
return render(request, 'test.html', context=context)
模板处理
<form action="# " method="post">
{% csrf_token %}
form
<input type="submit" value="Submit" />
</form>
常用字段
- CharField
- max_length
- required 字段是否是必须的
- EmailField
- FloatField
- max_value
- min_value
- IntegerField
- URLField 接受
URL
格式的字符串
验证数据
- 错误提示
email = forms.EmailField(error_messages = { 'invalid':'请输入正确的邮箱' })
常用验证器
- MaxValueValidator 最大值
- MinValueValidator 最小值
- MinLengthValidator 验证最小长度
- EmailValidator 验证邮箱格式
- URLValidator验证URL格式
- RegexValidator 正则表达式验证器
form django.core import validators
class SForm(forms.Form):
phone = forms.CharField(validators=[validators.RegexValidator('1[345678]\d{9}', message='请输入正确手机号')])
表单渲染格式
- form.as_table
- form.as_p
- form.as_ul
手动渲染表单字段
form.name_of_field
文件上传
前端
form
标签内 指定enctype="multipart/form-data"
form
标签内input
标签 指定name以及type=‘file’
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="提交"></input>
</form>
from django.shortcuts import render
from django.views.generic import View
import os
from django.http import HttpResponse
class IndexView(View):
def get(self, request):
return render(request, 'index.html')
def post(self, request):
myFile = request.FILES.get('myfile')
with open('Main.png', 'wb') as f:
for chunk in myFile.chunks():
f.write(chunk)
return HttpResponse('OK')
使用模型来处理上传文件
通过models.py
中指定的文件目录可以直接保存
#models.py
from django.db import models
class Article(models.Model):
file = models.FileField(upload_to='Image')
# views.py
from django.shortcuts import render
from django.views.generic import View
from .models import Article
from django.http import HttpResponse
class IndexView(View):
def get(self, request):
return render(request, 'index.html')
def post(self, request):
file = request.FILES.get('myfile')
Article.objects.create(file=file)
return HttpResponse('OK!')
指定MEDIA_ROOT 与 MEDIA_URL
#settings.py
#添加
MEDIA_ROOT = os.path.join(BASE_DIR, 'Image') #设置访问路径
MEDIA_URL = ''
限制上传的文件扩展名:
from django.db import models
from django.core import validators #验证
class Article(models.Model):
file = models.FileField(validators=[validators.FileExtensionValidator(['txt'],message='必须为TXT格式的文件')])
# forms.py
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__'
上传图片
models.py
- ImageField()
forms.py
class MyForm(forms.ModelForm):
class Meta:
model = Article #数据模型
fields = '__all__'
注意使用ImageField必须安装Pillow库pip install pillow