我試圖處理與下面的代碼的圖像上傳驗證錯誤:當我試圖上傳我得到驗證錯誤,該位置是必填字段保存(提交= FALSE)投擲
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.
你能後的堆棧跟蹤? – Rohan
追溯你的意思?我是新手,所以這就是我剛發佈的內容。 – bcoop713
是的,但你是什麼意思:_if我擺脫了「if,else」聲明:_ – Rohan