从模板保存日期字段:错误"值具有无效的日期格式。它必须是YYYY-MM-DD格式。"

时间:2016-01-11 14:56:42

标签: django date datetime input format

现在我必须以AAAA-MM-DD格式插入数据,如果我想要插入%m/%d/%Y%m/%d/%y格式,我能做什么? 谢谢我在Django上的新作。

我有模板,我插入数据:

TEMPLATE

<tr>
    <td>N_Prova</td>
    <td><input type="text" name="nprova"/></td>
</tr>
<tr>
    <td>Date Analysis</td>
    <td><input type="text" name="date_analysis" /></td>
</tr>

MODEL

class Analysis(models.Model):
    nprova = models.CharField(unique=True, max_length=20, null=False, blank=False)
    date_analysis = models.DateField(null=True)

查看

    def addanalisi(request):

        if 'save' in request.POST:
            print("save is in request post")

            newanal = analysis(nprova=nprova,data_analysis=date_analysis)
            newanal.save()

            print(nprova,data_analysis)
            return redirect('/listanalysis/')

        analysis = Analysis.objects.all()
        template = 'italgraniti/addanalysis.html'
        context_instance = RequestContext(request)

return render_to_response(template, {'form': form, 'analysis' : analysis}, context_instance)

2 个答案:

答案 0 :(得分:2)

您应该根据ModelForm创建Model。表单将automatically convert日期转换为Python datetime.date对象。

forms.py:

from .models import Analysis


class AnalysisForm(forms.ModelForm):
    date_analysis = form.DateField(input_formats=['%m/%d/%Y',
                                                '%m/%d/%y',])
    class Meta:
        model = Analysis

views.py:

from .forms import AnalysisForm


def addanalisi(request):  
    form = AnalysisForm(request.POST or None)
    if form.is_valid:
        form.save()
    return render(request, template, {'form':form})

docs_about_modelforminput_formats

答案 1 :(得分:0)

您正在寻找的是this功能。

因此,在您看来,您希望:

date = time.strptime(request.POST['date_analysis'], "%m/%d/%Y")   
newanal = analysis(nprova=request.POST['nprova'],data_analysis=date)
newanal.save()