先看效果图:
当没有添加数据,就按 提交
键就会出现报错
下面是操作步骤
1. 先在 views.py 文件里做添加
# 在 views.py class AssetModelForm(forms.ModelForm):#newField = forms.CharField()class Meta:model = models.AssetSet fields = ['name', 'price', 'category', 'depart']#fields = "__all__""""# 单一的给某个field添加样式widgets = {'category': forms.Select(attrs={'style': "width: 300px;"})}"""# 给所有的 field 提供样式def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)for name, field in self.fields.items():if name == "price":continuefield.widget.attrs['style'] = "width: 100px"def asset_add(request):"""# 获取所有类型cat_list = models.AssetSet.category_choicesdp_list = models.Department.objects.all()form = AssetForm()"""if request.method == "GET":cat_list = models.AssetSet.category_choicesdp_list = models.Department.objects.all()form = AssetModelForm()return render(request, 'asset_add.html', {'cat_list': cat_list, 'dp_list': dp_list, 'form': form})# print(request.POST)# 隐含功能:字段不能为空form = AssetModelForm(data=request.POST)if form.is_valid():# data_dict = form.cleaned_data# 在数据库里创建一条数据# 第一种写法# models.AssetSet.objects.create(name=data_dict['name'], price=data_dict['price'], category=data_dict['category'], depart_id=data_dict['depart'].id)"""obj = models.Department.objects.filter(id = 1).first()models.AssetSet.objects.create(name="", price="", category=1, depart=obj)"""# 第二种写法# models.AssetSet.objects.create(name=data_dict['name'], price=data_dict['price'], category=data_dict['category'], depart=data_dict['depart'])# 第三种方法# models.AssetSet.objects.create(**data_dict)# 第四种方法# 用户提交的数据,直接写入数据库# 这种写法更快地将数据保存到数据表里form.save()return redirect('/asset/list/')else:print(form.errors)#return HttpResponse("失败")# 传 form 是为了保存表格输入的数据return render(request, "asset_add.html", {"form": form})
2. 在 asset_add.html 文件里修改
<form method="post" action="/asset/add/" novalidate><!-- {{ form.name }}{{ form.price }} -->{% csrf_token %}{% for field in form %}<div><label>{{ field.label }}</label><div>{{ field }}<!-- 取错误里的第一个字段,会显示英文 --><span style="color: red;">{{ field.errors.0 }}</span></div></div>{% endfor %}<button type="submit">提 交</button>
</form>
3. 为了使网页呈现中文
在 settings.py
文件里修改
#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
点个赞呗~