我有表格字段,我想有时保持空白。 问题是视图中的save()方法期望归档和抛出错误。
我的表单:
from django import forms
from cProfile import label
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file'
)
time_from = forms.DateTimeField(
label = 'select range of time, from'
)
time_to = forms.DateTimeField(
label = 'to:', required = False
)
我的模特:
from django.db import models
import uuid
from django.utils import timezone
from celery.worker.strategy import default
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
time_from = models.DateTimeField(default=None, null=True, blank=True)
time_to = models.DateTimeField(default=None, null=True, blank=True)
我的观点:
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'], time_from=request.POST['time_from'], time_to=request.POST['time_to'])
newdoc.save()
我在提交时尝试将 time_to 字段保留为空,但它给了我这个错误:
例外价值:[u"'' value的格式无效。它必须在 YYYY-MM-DD HH:MM [:ss [.uuuuuu]] [TZ]格式。"]
我认为原因是 newdoc.save()期望 time_to 格式的DateTimeField格式为 u' 2017-05-05 12: 02:02' 并获得一个空字符串或类似的东西:你'
答案 0 :(得分:0)
你应该创建一个ModelForm而不是Form,只需调用form.save(),这样做django将帮助你管理你的属性和值。
Django会为你的模型创建一个id,所以你不需要创建这个id
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
您的表格
class DocumentForm(forms.ModelForm):
class Meta:
model = Document #This will link your form to your model, and django can do his job
fields = '__all__'
docfile = forms.FileField(
label='Select a file'
)
time_from = forms.DateTimeField(
label = 'select range of time, from'
)
time_to = forms.DateTimeField(
label = 'to:', required = False
)
您的观点
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
如果你这样做,你的DocumentForm(request.POST,request.FILES)将创建一个Document实例,它将验证并存储正确的值。