0

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

    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.
4

1 回答 1

2

根据您的评论:

当我在视图中有“if,else”时,我没有收到错误页面,因为它只是转到“else”并在控制台中打印“需要位置”错误而不是整个回溯

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

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

class PhotoForm(ModelForm):
    class Meta:
        model = Photo
        exclude = ['location', 'user']
于 2013-10-24T05:08:16.400 回答