在Django模板中具有两种不同的形式

时间:2019-07-29 21:33:26

标签: python django django-models django-forms django-templates

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

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

进行了一些研究之后,我找到了一个解决方案,但它适用于基于类的视图,但是我想避免这种情况,因为我的视图已经是基于函数的视图,因此我必须对其进行很多更改。码。但是,如果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})

有人告诉我在我的视图中使用上下文,但是我不知道如何在我的视图中集成它。这是可行的解决方案,还是有更好的方法呢?

context = {
        'first_form': TradingForm(request.POST or None),
        'second_form': LimitSellForm(request.POST or None),
    }

2 个答案:

答案 0 :(得分:1)

您可以使用TemplateView代替常规视图功能,并将其添加到下面

 def get_context_data(self, **kwargs):
        context = {
        'first_form': TradingForm(request.POST or None),
        'second_form': LimitSellForm(request.POST or None),
         }

您可以签入文档: https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/#templateview

答案 1 :(得分:1)

这是一种方法。向您的按钮添加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>

然后,在您的视图中,您可以通过在帖子中查找按钮名称来检查已提交的表单:

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