繁体   English   中英

Django空表单字段验证不适用于clean方法

[英]Django empty form field validation is not working with clean method

我有一个django表单,我想验证当我要保存时字段不为空,让我们说例如“description”字段(charfield)....这是我的form.py代码:

from django.core.exceptions import ValidationError

class CostItemsForm(ModelForm):

    groupid = forms.CharField(required=True)

    def __init__(self, *args, **kwargs):
        super(CostItemsForm, self).__init__(*args, **kwargs)

    class Meta:
        model = CostItems
        fields = [
                    'description', 
                    'usd_value', 
                    'rer',
                    'pesos_value', 
                    'supplier', 
                    'position',
                    'observations',
                    'validity_date',
                ]

    def clean_description(self):
        des = self.cleaned_data['description']
        if des==None:
            raise ValidationError("Description cannot be empty")
        return des

但没有任何反应,已经尝试过这样返回: return self.cleaned_datareturn clean_description但仍然相同。

这是我的view.py

class CostItemInsert(View):
    template_name='cost_control_app/home.html'

    def post(self, request, *args, **kwargs):
        if request.user.has_perm('cost_control_app.add_costitems'):
            form_insert = CostItemsForm(request.POST)
            if form_insert.is_valid():
                form_save = form_insert.save(commit = False)
                form_save.save(force_insert = True) 
                messages.success(request, "Record created")
            else:
                messages.error(request, "Could not create record, please check your form")
        else:
            messages.error(request, "Permission denied")
        form_group = GroupsForm()
        form_subgroup= SubGroupsForm()
        form_cost_item = CostItemsForm()
        return render(request, self.template_name,{
                                    "form_subgroup":form_subgroup,
                                    "form_cost_item":form_cost_item,
                                    "form_group":form_group,
                                })  

和costitems模型:

class CostItems(ModelAudit):
    cost_item = models.AutoField(primary_key = True, verbose_name = 'Item de costo')
    group = models.ForeignKey(Groups, verbose_name = 'Grupo')
    description = models.CharField(max_length = 100, verbose_name =' Descripcion')
    usd_value = models.IntegerField(verbose_name ='Valor en USD')
    rer = models.IntegerField(verbose_name = 'TRM negociado')
    pesos_value = models.IntegerField(verbose_name = 'Valor en pesos')
    supplier = models.ForeignKey(Suppliers, verbose_name = 'Proveedor')
    position = models.ForeignKey(Positions, verbose_name = 'Cargo')
    observations = models.TextField(max_length = 500, verbose_name = 'Observación')
    validity_date = models.DateField(verbose_name = 'Fecha de vigencia')

    def __str__(self):
        return self.description

    class Meta:
            ordering = ['cost_item']
            verbose_name = 'Item de costos'
            verbose_name_plural = 'Items de costo'

这是我从html模板中的输入按钮调用的模态代码,我调用该视图:

<div class="modal fade bs-example-modal-lg" id="myModals" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Registrar item de costo</h4>
      </div>
      <form method="post" action="{% url 'cost_control_app:cost_item_insert' %}">
      {% csrf_token %}
          <div class="modal-body">
            <br/>
            <div class="row">
                {%include "partials/field.html" with field=form_cost_item.groupid|attr:"readonly:True" %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.description %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.usd_value|attr:"value:0"|attr:"id:id_usd_value" %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.rer|attr:"value:0"|attr:"id:id_rer_value" %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.pesos_value|attr:"value:0"|attr:"id:id_pesos_value" %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.supplier %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.position %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.observations %}<br clear="all"/>
                {%include "partials/field.html" with field=form_cost_item.validity_date %}<br clear="all"/>
                </br>

            </div>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            <button type="submit" class="btn btn-primary">Guardar</button>
          </div>
       </form>
    </div>
  </div>
</div> 

最后,partials / fields.html也是:

{% load widget_tweaks%}
<div class="col-md-10">
    <div class="form-group {% if field.errors %}has-error{% endif %}">
        <label class="col-sm-2 control-label">{% if field.field.required %}{% endif %}{{ field.label }}<label style="color:red">*</label></label>
            <div class="col-sm-10">
                {% if type == 'check' %}
                    {{ field|add_class:"check" }}
                {% elif type == 'radio' %}
                    {{ field|add_class:"radio" }}
                {% else %}                
                    {{ field|add_class:"form-control" }} 
                {% endif %}
            </div>
            {% for error in field.errors %}
                <div class="error_msg">- {{ error }}</div>
            {% endfor %}
    </div>
</div>

有帮助吗?

提前致谢

des never将等于None ,默认值至少为空字符串

if not des:当des为空时,应该足以满足你的if语句

如果您真正想要检查的是否为空,则可以通过将blank设置为False来在模型中执行此操作

description = models.CharField(max_length = 100, blank=False, verbose_name =' Descripcion')

如果字段为空= True,则表单验证将允许输入空值。 如果字段为空= False,则将需要该字段。


是的,但是在用户可以继续保存之前,是不是通过验证错误来显示表单内的警报?

是的,但是在您向用户显示之前覆盖了表单,这可以通过在方法顶部定义表单然后进一步向下覆盖来轻松解决

   def post(self, request, *args, **kwargs):
        form_group = GroupsForm()
        form_subgroup= SubGroupsForm()
        form_cost_item = CostItemsForm()
        if request.user.has_perm('cost_control_app.add_costitems'):
            form_cost_item = CostItemsForm(request.POST)
            if form_cost_item.is_valid():
                form_save = form_cost_item.save(commit = False)
                form_save.save(force_insert = True) 
                messages.success(request, "Record created")
            else:
                messages.error(request, "Could not create record, please check your form")
        else:
            messages.error(request, "Permission denied")
        return render(request, self.template_name,{
                                    "form_subgroup":form_subgroup,
                                    "form_cost_item":form_cost_item,
                                    "form_group":form_group,
                                })  

如果您尝试在模板中显示表单错误,则应将错误传递给模板。 在您的情况下,视图应该类似于以下内容。

def post(self, request, *args, **kwargs):
    if request.user.has_perm('cost_control_app.add_costitems'):
        form_insert = CostItemsForm(request.POST)
        if form_insert.is_valid():
            form_save = form_insert.save(commit = False)
            form_save.save(force_insert = True) 
            messages.success(request, "Record created")
        else:
            messages.error(request, "Could not create record, please check your form")
            form_group = GroupsForm()
            form_subgroup= SubGroupsForm()
            return render(request, self.template_name,{
                            "form_subgroup":form_subgroup,
                            "form_cost_item":form_insert,
                            "form_group":form_group,
                        })   

    else:
        messages.error(request, "Permission denied")
    form_group = GroupsForm()
    form_subgroup= SubGroupsForm()
    form_cost_item = CostItemsForm()
    return render(request, self.template_name,{
                                "form_subgroup":form_subgroup,
                                "form_cost_item":form_cost_item,
                                "form_group":form_group,
                            })  

我可以看到默认情况下模型中的字段是必填字段。 所以无论如何它会引发验证错误。 如果表单无效,您需要做的就是将错误表单传递给模板。

暂无
暂无

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

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