在django中,可以使用表单提交数据到数据库中,django表单与HTML表单有区别,接下来看表单创建要点:
第一要点:forms文件夹创建,在需要APP中创建froms项目文件夹。
第二要点:创建表单代码
froms.py
from django import forms
class MessageBoardForm(forms.Form):
title=forms.CharField(max_length=100,min_length=2)
content=forms.CharField(widget=forms.Textarea)
#可以输入多行
email=forms.EmailField()
reply=forms.BooleanField(required=False)
第三个要点:
view.py
from django.shortcutsimport render,HttpResponse
from django.views.genericimport View
from .froms import MessageBoardForm
#先导入render,django.views. View, froms.MessageBoardForm(这是上面表单class)
class IndexView(View):#记得一定要继承View
def get(self,request):
form = MessageBoardForm()
return render(request,'index.html',context={'from':form})
def post(self,request):
form = MessageBoardForm(request.POST)
if form.is_valid():
title=form.cleaned_data.get('title')
content = form.cleaned_data.get('content')
email=form.cleaned_data.get('email')
reply=form.cleaned_data.get('reply')
return HttpResponse('验证成功')
else:
print(form.errors)
HttpResponse("验证失败")
当然,title,content等参数现在只是验证赋值但是没有使用。
第四个要点:
urls.py
from django.urlsimport path
from front_appimport views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.IndexView.as_view())
#默认就用主页访问,views.IndexView.as_view()这里的后面as_view()带括号,如果不带括号则出现as_view() takes 1 positional argument but 2 were given错误
]
![](https://img-blog.csdnimg.cn/img_convert/c62f55b0ae371b12265e1b3e84a8e224.webp?x-oss-process=image/format,png)
当然要连接数据可以,插入数据也是可以的。
在models.py中创建一个Article模板,这里直接说表格,通过迁移到数据库中。
![](https://img-blog.csdnimg.cn/img_convert/d33387867d0a82876658463423aef096.webp?x-oss-process=image/format,png)
然后在视图中加入
article=Article(title=title,content=content,email=email,reply=reply)
article.save()
如下图所示。
![](https://img-blog.csdnimg.cn/img_convert/3b29f053dcc967329d89b6172091bffc.webp?x-oss-process=image/format,png)
进入网页中提交数据,最后在数据库找到成功插入的数据。