Django - 具有相同操作属性的单个页面上的两个表单标记

时间:2016-12-09 17:35:16

标签: django forms django-forms

好的,所以我试图在页面中用两个不同的标签分隔单个页面中的两个表单标签。我只是想知道如何处理这个问题。 我知道如果我使用不同的动作网址,我可以轻松处理它们。但是当出现验证错误时,它会转到提交表单的URL,我不希望这样。我希望它留在页面里面,这就是为什么我要做动作=''。

在HTML中

<!-----------template.html----------->
<div class=" tab">
    <!-- Nav tabs -->
    <div class="card">
        <ul class="nav navbar-nav nav-tabs" role="tablist">
            <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Info 1</a></li>
            <li role="presentation"><a href="#groups" aria-controls="groups" role="tab" data-toggle="tab">Info 2</a></li>
        </ul>
    </div>
</div>
<div class="tab-content">
    <!--Personal Info -->
    <div class="row tab-pane active" role="tabpanel" id="home">
        <!-- edit form column -->
        <div class="info1">
            {% include template1 %}
        </div>
    </div>
    <div role="tabpanel" class="tab-pane" id="groups">
        <div class="info2">
            {% include template2 %}
        </div>
    </div>
</div>

<!-----------template1----------->
<form method='post' action='' class="form-horizontal" role="form">
{%csrf_token%}
<input value=something>
<input type="submit" value="Save Changes" name="{{formA.prefix}}">
</form>

<!-----------template2----------->
<form method='post' action='' class="form-horizontal" role="form">
{%csrf_token%}
<input value=something>
<input type="submit" value="Save Changes" name="{{formA.prefix}}">
</form>

以下是尝试解决此问题的代码:

VIEWS.PY

def _get_form(request, form_class, prefix):
    data = request.POST if prefix in request.POST else None
    return form_class(data, prefix = prefix)
class MyView(LoginRequiredMixin,TemplateView):
    login_url = '../login/'
    template_name = 'template.html'

    def get(self, request, *args, **kwargs):
        return self.render_to_response({'formB':FormB(prefix='prefixA-'),'formB':FormB(prefix='prefixB-')})

    def post(self, request, *args, **kwargs):
        formA = _get_form(request, FormA, 'payment-')
        formB = _get_form(request, FormB, 'user-')
        if formA.is_bound and formA.is_valid():
            # Do Something
        elif formB.is_bound and formB.is_valid():
            # Do Something
            # Update user
            obj = userForm.save(commit=False)
            logger.error(obj.first_name)
            obj.save()
        return self.render_to_response({'paymentForm':paymentForm, 'userForm':userForm})

FORMS.PY

class FormB(forms.ModelForm):
    class Meta:
        model = User
        fields = [some fields]
        widgets = {
            'password': forms.PasswordInput(),
        }
    def save(self, commit=True):
        user = super(FormB, self).save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user

class FormA(forms.ModelForm):
    class Meta:
        model = User
        fields = [some fields]
    def save(self, commit=True):
        user = super(FormA, self).save(commit=False)
        return user

不确定我做错了什么,但是表单要么没有提交,要么失败了.is_valid()失败,表单没有做任何事情。有谁可以请,请帮我解决这个问题? 谢谢!

1 个答案:

答案 0 :(得分:0)

您应该只需清理代码即可解决所有问题:

  1. 您的第二个表单前缀错误。

    <!-----------template1----------->
    <form method='post' action='' class="form-horizontal" role="form">
    {% csrf_token %}
    {{ formA }}
    <input type="submit" value="Save Changes" name="{{ formA.prefix }}">
    </form>
    
    <!-----------template2----------->
    <form method='post' action='' class="form-horizontal" role="form">
    {% csrf_token %}
    {{ formB }}
    <input type="submit" value="Save Changes" name="{{ formB.prefix }}">
    </form>
    
  2. get()也有错误的前缀

    def get(self, request, *args, **kwargs):
        return self.render_to_response({
            'formA': FormA(prefix='prefixA-'),
            'formB': FormB(prefix='prefixB-')
        })
    
  3. post()包含错误的前缀和变量名称:

    def post(self, request, *args, **kwargs):
        formA = _get_form(request, FormA, 'prefixA-')
        formB = _get_form(request, FormB, 'prefixB-')
        if formA.is_bound and formA.is_valid():
            # Do Something
        elif formB.is_bound and formB.is_valid():
            # Do Something
            # Update user
            obj = formB.save(commit=False)
            logger.error(obj.first_name)
            obj.save()
    
        return self.render_to_response({
            'formA': formA,
            'formB': formB
        })
    
  4. https://docs.djangoproject.com/en/1.10/ref/forms/api/#prefixes-for-forms