繁体   English   中英

如何在同一个Django模板中使用更多不同的形式?

[英]How can i use more different forms in the same Django template?

在我的项目中,我有一个模板,试图在此模板中针对不同的用例放置两种形式。 我以前从未遇到过这个问题,所以我真的不知道从哪里可以在同一页面中使用两种形式。

起初,我想创建另一个视图来处理每种表单,但是我认为这种解决方案会给模板渲染带来问题,但如果我应该再次对另一个模板遇到这个问题,那将是不可持续的。

经过研究后,我找到了一个解决方案,但它适用于基于类的视图,但是我想避免这种情况,因为我的视图已经是基于函数的视图,因此我必须在代码中进行很多更改。

是否可以使用基于功能的视图解决此问题? 每个建议都值得赞赏

第一场

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})

这个答案有点笼统,因为您还没有包含视图功能。 您可以将每种形式添加到视图的上下文中。 像这样:

views.py

...
from .forms import FirstForm, SecondForm
...

def some_view(request):

    context = {
        'first_form': FirstForm(request.POST or None),
        'second_form': SecondForm(request.POST or None)
    }
    return render(request, "app/some_template.html", context)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM