【发布时间】:2019-07-22 19:57:39
【问题描述】:
在我的项目中,我有一个模板,我试图为不同的用例放置两种表单。我以前从来没有遇到过这个问题,所以我真的不知道从哪里开始在同一个页面中使用两个表单。
起初我想创建另一个视图来处理每个表单,但我认为这个解决方案会给我的模板的渲染带来问题,除了如果我再次使用另一个模板遇到这个问题时不可持续。
经过一些研究,我找到了一个解决方案,但它适用于基于类的视图,但我想避免这种情况,因为我的视图已经是基于函数的视图,我必须在我的代码。
是否可以使用基于函数的视图来解决这个问题?每一个建议都值得赞赏
第一个字段
class FirstForm(forms.ModelForm):
firstfield = forms.CharField()
secondfield = forms.CharField()
class Meta:
model = MyModel
fields = ("firstfield", "secondfield")
def save(self, commit=True):
send = super(FirstForm, self).save(commit=False)
if commit:
send.save()
return send**
第二种形式
class SecondForm(forms.ModelForm):
firstfield = forms.FloatField()
secondfield = forms.Floatfield()
thirdfield = forms.CharField()
class Meta:
model = MyModelTwo
fields = ("firstfield", "secondfield", "thirdfield")
def save(self, commit=True):
send = super(SecondForm, self).save(commit=False)
if commit:
send.save()
return send
模板
<h3> First Form </h3>
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
</form>
<h3> Second Form </h3>
<form method="post" novalidate>
{% csrf_token %}
{% include 'main/includes/bs4_form.html' with form=form %}
<button type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
</form>
编辑:我的观点:
def myview(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FirstForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
send = form.save()
send.save()
messages.success(request, f"Success")
# if a GET (or any other method) we'll create a blank form
else:
form = FirstForm()
return render(request,
"main/mytemplate.html",
context={"form":form})
【问题讨论】:
-
除此之外,请注意您的两个
save方法完全复制了超类保存方法的作用;它们毫无意义,您应该删除它们。 -
能否包含您当前的视图代码?
-
我正在删除它们@DanielRoseman,谢谢!我还添加了视图
标签: python django django-forms django-templates