save(commit = False)抛出验证错误

时间:2013-10-24 04:44:59

标签: python django django-crispy-forms

我正在尝试使用以下代码处理图片上传:

    location = get_object_or_404(Location, slug=slug)
    if 'submit_photo' in request.POST:
    photo = PhotoForm(request.POST, request.FILES)
    if photo.is_valid():
        new_photo = photo.save(commit=False)
        new_photo.location = location
        new_photo.user = request.user
        new_photo.save()
        photo.save_m2m() 
    else:
        print(photo.errors)

当我尝试上传时,我得到验证错误,该位置是必填字段(它是)。但是我认为commit = False的意思是我可以在保存任何内容之前添加信息,例如必填字段......

我确定我错过了一些非常愚蠢的东西,因为我几乎完全从其他工作表单提交中复制了这些内容。我还添加了一些其他可能有用的代码。

以下是模型:

class Photo(models.Model):
    user = models.ForeignKey(User)
    location = models.ForeignKey(Location)
    title = models.CharField(max_length=30, blank=True, null=True)
    desc = models.CharField(max_length=150, blank=True, null=True, verbose_name='Description')
    created_on = models.DateTimeField(auto_now_add=True)
    photo = models.ImageField(upload_to='photos/%Y/%m/%d')
    tags = TaggableManager(blank=True)


    def __unicode__(self):
        return unicode(self.photo)

这是表格(使用脆纸):

class PhotoForm(ModelForm):
class Meta:
    model = Photo
    #fields = ['title', 'desc', 'photo', 'tags']

def __init__(self, *args, **kwargs):
    super(PhotoForm, self).__init__(*args, **kwargs)
    self.helper = FormHelper()
    self.helper.form_method = 'post'
    self.helper.layout = Layout(
        Field('title', placeholder="Name it"),
        Field('desc', placeholder="A brief description"),
        Field('photo'),
        Field('tags', placeholder="Optional = Add tags like this Hiking, Reservations, Sight-seeing"),
    )

    self.helper.add_input(Submit('submit_photo', 'Add Photo'))

如果我将视图重写为:

    if 'submit_photo' in request.POST:
    photo = PhotoForm(request.POST, request.FILES)
    new_photo = photo.save(commit=False)
    new_photo.campground = campground
    new_photo.user = request.user
    new_photo.save()
    photo.save_m2m()  # REQUIRED TO SAVE TAGS

我尝试上传时收到以下回溯:

Traceback:
File "/home/bobby/.virtualenvs/campthat3/lib/python2.7/site-            packages/django/core/handlers/base.py" in get_response
115.                         response = callback(request, *callback_args,    **callback_kwargs)
File "/home/bobby/django/campthat3/cg_profiles/views.py" in cg_profile
17.         new_photo = photo.save(commit=False)
File "/home/bobby/.virtualenvs/campthat3/lib/python2.7/site-   packages/django/forms/models.py" in save
370.                              fail_message, commit, construct=False)
File "/home/bobby/.virtualenvs/campthat3/lib/python2.7/site-  packages/django/forms/models.py" in save_instance
75.                          " validate." % (opts.object_name, fail_message))

Exception Type: ValueError at /michigan/bay-view/
Exception Value: The Photo could not be created because the data didn't validate.

1 个答案:

答案 0 :(得分:2)

来自你的评论:

  

当我在视图中有“if,else”时,我没有得到错误页面,因为它只是转到“else”并在控制台中输出“location required”错误而不是整个回溯< / p>

表单无效,因此即使使用commit=False也无法保存。 表单中的错误可能是由于模型中的排除字段,在这种情况下,您不应将这些字段放在表单中。

您可以在元类中使用excludefields属性:

class PhotoForm(ModelForm):
    class Meta:
        model = Photo
        exclude = ['location', 'user']