具有隐藏形式的Django clean()

2024-05-15 21:15:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里遇到了一个问题,我的def clean()无法使用我的隐藏form。在

我有三个forms,我用jquery来用select来隐藏它,所以如果我想要form1我只需要选择form1,它将隐藏其他2个。在

现在我尝试使用clean(),但是当我得到我的raise ValidationError时,我看不到它,因为我的form是隐藏的。在

所以我需要点击form1,然后,我可以看到我的error

有没有可能看到我的error即使它被隐藏了?在

因为有时候在我点击form1之前,我不知道为什么会出错。在

我一直在寻找一个可能的解决办法,但什么也没找到。在

模板

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
{{ titulo }}
<hr/>
<br/>

  {% if messages %}
    <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        {% for message in messages %}
        {% if message.tags %}<div  class="alert alert-{{ message.tags }}">{{ message }}</div>{% endif %}
        {% endfor %}
      </div>
  {% endif %}

  <center>
    <label for="protocolo">Protocolo de Activos</label>
      <select id="protocolo" name="protocolo">
      {% for x,y in form.fields.protocolo.choices %}
          <option value="{{ x }}"{% if form.fields.protocolo.value == x %} selected{% endif %}>{{ y }}</option>
      {% endfor %}
      </select>
  </center>
<br>

<div id="form1" style="display:none;">
  <form method="POST" action="">{% csrf_token %}
    {{ form1.as_p }}
    <input type="submit" value="Enviar Datos" />
  </form>
</div>

<script>
    $('#protocolo').on('change',function(){
         var selection = $(this).val();
        switch(selection){
        case "form1":
        $("#form1").show()
       break;
        default:
        $("#form1").hide()
        }
    });
</script>

如您所见,我使用jqueryshow()和{}form1。在

如果name存在,这个代码可以正常工作,我会得到Error,但是当我点击我的select并选择form1时,就会看到这条消息

我想在我点击我的submit时看到它。。。有可能吗?在

注意

这一次我只有一个form作为form1,但是我很快就会添加更多的,这就是为什么我使用select和{}一起使用的原因。在

谢谢!!

编辑:

表单.py

^{pr2}$

py.py视图

def user_form(request):
    titulo = "Activos"
    form1 = userForm(request.POST or None)
    queryset = user.objects.all()
    context = {
    "form1": form,
    "queryset": queryset,
    }
    if form1.is_valid():
        instance = form.save()
        messages.success(request, 'Has been added')
        return redirect('/')
    return render(request, "user.html", context)

我刚刚用viewsform编辑了我的代码。在

一旦我进入我的表单,我试图注册一个已经存在的用户,我得到错误消息,没关系。但是我前面解释了Jquery效果,它阻止我看到错误消息,除非我单击select并选择表单,然后我可以看到我的标志错误Error, already exists

我想看到Error, already exists一旦我点击submit并重定向我。在

clean()方法只在我选择form时起作用


Tags: divformcleanmessageforifrequestscript
1条回答
网友
1楼 · 发布于 2024-05-15 21:15:10

答案是您不需要在这里重写clean方法because

The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of model fields that are marked as unique, unique_together or unique_for_date|month|year.

If you would like to override the clean() method and maintain this validation, you must call the parent class’s clean() method.

所以你需要的就是 表单.py在

class userForm(forms.ModelForm):
    class Meta:
        model = user
        fields = ["name"]

就这样!在

相关问题 更多 >