ImageField() 不在 ModelForm 中保存图像 - Django/Python
Posted
技术标签:
【中文标题】ImageField() 不在 ModelForm 中保存图像 - Django/Python【英文标题】:ImageField() not saving images in ModelForm - Django/Python 【发布时间】:2015-05-24 03:08:21 【问题描述】:当我尝试从我的表单上传图片时,一切都在处理,但没有保存图片。
有人知道为什么会这样吗?
提前谢谢!
models.py:
class Photo(models.Model):
user = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.user)
views.py:
def photo_upload_view(request, username):
u = MyUser.objects.get(username=username)
if request.method == 'POST':
form = PhotoUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, "Thank you! You have successfully posted your picture!")
return HttpResponseRedirect('/')
else:
form = PhotoUploadForm()
submit_btn = "Upload Post"
context =
"form": form,
"submit_btn": submit_btn
return render(request, "photos/photo_upload.html", context)
forms.py:
class PhotoUploadForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('user', 'category', 'title', 'description', 'image')
.html:
<form method='POST' action=' action_url '>% csrf_token %
form|crispy
<input class='btn btn-default submit_btn_class ' type='submit' value=' submit_btn '/>
</form>
【问题讨论】:
【参考方案1】:您应该将enctype=multipart/form-data
属性添加到<form>
标签:
<form method='POST' action=' action_url ' enctype='multipart/form-data'>
【讨论】:
以上是关于ImageField() 不在 ModelForm 中保存图像 - Django/Python的主要内容,如果未能解决你的问题,请参考以下文章
imageField 中的 upload_to 属性无法将图像保存在磁盘上
在 Drupal 6 下的 CCK 中未显示 ImageField
在 Django Rest Framework 中接收 Base64 编码的图像并保存到 ImageField