这一部分涉及一下几个模块:前端HTML表单,表单验证的Form,数据库结构Model,后端处理的View
文章目录
前端HTML
网页文件:save_data.html
:
<form action="" method="post">
<input type="text" name="name" placeholder="Name"> {# 这里的name属性是后端验证的唯一标识,不能重复 #}
<input type="text" name="email" placeholder="Email">
<input type="submit" value="提交">
{% csrf_token %}
</form>
表单验证Form
如果app中没有form.py
文件,新建一个即可:
from django import forms
class SaveDataForm(forms.Form):
name = forms.CharField(max_length=255, required=True)
email = forms.EmailField(required=True)
数据库结构Model
在model.py
文件中写入:
from django.db import models
class SaveDataModel(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
写完文件后,定位到django项目中的manage.py
文件,在命令行中运行:
python manage.py makemigrations
python manage.py migrate
后端处理的View
from django.views.generic import View
from .form import SaveDataForm
from .models import SaveDataModel
class SaveDataView(View):
def get(self, request):
return render(request, 'save_data.html')
def post(self, request):
save_data_form = SaveDataForm(request.POST)
if save_data_form.is_valid():
save_data_model = SaveDataModel()
save_data_model.name = request.POST['name']
save_data_model.email = request.POST['email']
save_data_model.save()
# 可以使用这行代码确认是否添加成功:
# SaveDataModel.objects.all().values()
return render(request, 'save_data.html')
更多数据库操作
请参考:
django models进行数据库增删查改:https://my.oschina.net/leeyd/blog/367688
一文读懂|Django之Model操作数据库详解:https://zhuanlan.zhihu.com/p/74423815