提交具有自定义日期格式的表单时的ValidationError

时间:2017-08-06 13:03:35

标签: django django-forms django-views

提交django表单时,我收到ValidationError。

在我的表格中,这是我的意见:01/01/2017 但是django告诉我格式必须是'AAAA-MM-GG' 使用此异常位置:/usr/local/lib/python3.5/dist-packages/django/db/models/fields/init.py in to_python,第1271行

这是我项目中的代码:

# models.py
class Archivio(models.Model):  
    sys_codice = models.AutoField(primary_key=True)
    some_other_field ...

class QuoteIscrizione(models.Model):  
    sys_chiave = models.AutoField(primary_key=True)
    sys_cod = models.ForeignKey(Archivio, on_delete=models.CASCADE)
    data_quota = models.DateField(blank=True, null=True)  


# forms.py
class ArchivioSearchForm(forms.Form):  
    data_quota = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y'), input_formats=('%d/%m/%Y',), required=False)  

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self:
            field.field.widget.attrs['class'] = 'form-control '
                if type(field.field.widget) is DateInput:
                    field.field.widget.attrs['class'] += 'datepicker'  
    def clean(self):
        data_quota = self.cleaned_data['data_quota']  
        return self.cleaned_data

# views.py  
def ArchivioSearchView(request):  
    model = Archivio
    form = ArchivioSearchForm()   

    if request.GET.get('data_quota'):  
        selection = Archivio.objects.filter(Q(quoteiscrizione__data_quota__gte=request.GET.get('data_quota'))  
        return render(request, 'search_template.html', {'selection':selection, 'form':form})  

# search_template.html  
<form action="" method="get" class="form-horizontal">
    <div class="form-group form-group-md">            
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
        {% for field in form %}
            <div class="form-group row">
                <label class="col-md-3 col-form-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
                <div class="col-md-6">
                    {{ field.as_widget() }}
                </div>
            </div>
        {% endfor %}
    <input type="submit" value="Confermo" />  
    </div>
</form>
{% for select in selection %}
    <h4><li><a href="{{ url('archivio_detail', args=[select.pk]) }}">{{ select.nominativo }}</a></li></h4>
{% endfor %}

我的settings.py

也有
LANGUAGE_CODE = 'it-IT'  
TIME_ZONE = 'Europe/Rome'  
USE_I18N = True
USE_L10N = True  
USE_TZ = True

我在尝试使用我的settings.py当然在转换USE_L10N = False之后     DATE_INPUT_FORMATS = ['%d /%m /%Y']

我还尝试在for循环上的 init 函数的forms.py上使用:

if type(field.field.widget) is DateInput:  
    field.field.widget.input_formats = ['d%/%m/%Y']  

我不仅尝试过列表,还尝试使用像'%d /%m /%Y'这样的字符串。

我也看到即使我的输入是2017/01/01也会发生此错误!

我无法弄清楚我做错了什么。 Django继续期待“YYYY-MM-DD”格式的日期,即使我覆盖了DateField小部件的每个可能的方法或参数。

感谢大家,您需要花一些时间来帮助我!

1 个答案:

答案 0 :(得分:0)

当您在表单上声明变量时,需要在DateInput小部件上设置格式,加上input_formats,如:

data_quota = forms.DateField(widget=forms.DateInput(format ='%d/%m/%Y'), input_formats=('%d/%m/%Y',), required=False)