模型表单

模型表单

  1、首先在app文件夹中创建一个 forms.py 文件

  2、在 forms.py 中编写模型表单,如下:

from django import forms
from .models import ShopInfo,Invest #表示导入模型文件中的模型类
class ShopInfoForm(forms.ModelForm): #继承模型表单的基类
class Meta:
model = ShopInfo #指定当前表单是由哪个模型类生成的,所有字段都会被渲染
# fields = [''] #表示要渲染的哪几个字段可以用列表形式 fields = [' ']
exclude = ['logic_delete'] #表示哪个字段不用渲染的用 exclude = [' '], 这个就表示logic_delete字段不用渲染

class InvestForm(forms.ModelForm):
class Meta:
model = Invest
exclude = ['shop_info'] #表示这个字段是一对一的字段,所以不需要

3、编写views.py 视图
from .forms import ShopInfoForm, InvestForm
def new_shop_info_add(request):
section = '添加店铺信息'
if request.method == "GET":
shop_info_from = ShopInfoForm()
invest_from = InvestForm()
context={
'from': shop_info_from,
'section': section,
'invest_from': invest_from,
}
return render(request,'shopincomes/new_shopinfo_add.html',context=context)

if request.method == "POST":
shop_info_from = ShopInfoForm(request.POST)
invest_from = InvestForm(request.POST)
if shop_info_from.is_valid() and invest_from.is_valid():
shop_info = shop_info_from.save() # 真保存,已保存到数据库
invest = invest_from.save(commit=False)
shop_info.invest = shop_info
invest.save()
return redirect(reverse('shopincomes:shop_info_view'))
return render(request,'shopincomes/new_shopinfo_add.html',context={
'from': shop_info_from,
'section': section,
'invest_from': invest_from,
})
 
4、创建一个new_shopinfo_add.html文件
{% extends 'shopincomes/base.html' %}
{% block title %}添加店铺信息{% endblock title %}
{% block info %}
<h2 class="sub-header">{{ section }}</h2>

<form class="active" method="post">
{% for field in from %}
<div class="form-group">
<label class="col-sm-1 control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
{% for field in invest_from %}
<div class="form-group">
<label class="col-sm-1 control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}

<div class="form-group">
<button type="submit" class="btn btn-primary" value="保存" style="width:100px;margin-top: 100px;margin-left: 300px">保存</button>
</div>
</form>
{% endblock info %}
5、配置url路由
  path('incomes/add/new/', views.new_shop_info_add, name='new_shop_info_add'),

  

posted on 2019-04-18 17:13  nickshen  阅读(133)  评论(0编辑  收藏  举报

导航