在我的项目中,我有一个模板,我试图为不同的用例放置两个表单。我以前从未遇到过这个问题,所以我真的不知道从这里到哪里去在同一页面中使用两个表单。
起初我想创建另一个 View 来处理每个表单,但我认为这个解决方案会给我的模板渲染带来问题,如果我在另一个模板中再次遇到这个问题,那么它就不可持续。
经过一些研究,我找到了一个解决方案,但它适用于基于类的 View ,但我想避免这种情况,因为我的 View 已经是基于函数的 View ,并且我必须在我的 View 中进行很多更改代码。然而,如果 CBV 是最好的选择,我可以做出改变。
感谢每一条建议
第一个字段
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>
views.py
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})
我被告知要在我的 View 中使用上下文,但我不知道如何将它集成到我的 View 中。这是一个可行的解决方案,还是有更好的方法?
context = {
'first_form': TradingForm(request.POST or None),
'second_form': LimitSellForm(request.POST or None),
}
最佳答案
这是一种方法。向按钮添加 name
属性,如下所示:
<button name="button1" type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
...
<button name="button2" type="submit" class="btn btn-danger" style="background-color: red;">SUBMIT</button>
然后在您的 View 中,您可以通过查找帖子中的按钮名称来检查已提交的表单:
def myview(request):
if request.method == 'POST':
if 'button1' in request.POST:
form1 = FirstForm(request.POST)
if form1.is_valid():
# do what needs to be done and redirect
if 'button2' in request.POST:
form2 = form = SecondForm(request.POST)
if form2.is_valid():
# do what needs to be done and redirect
else:
form1 = FirstForm()
form2 = SecondForm()
return render(request, "main/mytemplate.html",
context={'form1': form1, 'form2': form2})
关于python - Django 模板中有两种不同的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57261684/