当我尝试从表单上载图片时,一切都进行了,但图像没有保存。
有人知道为什么会这样吗?
提前感谢!
型号.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)
视图.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)
表格.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>
3条答案
按热度按时间crcmnpdw1#
您应该将
enctype=multipart/form-data
属性添加到<form>
标记:ndh0cuux2#
除了添加
enctype=multipart/form-data
之外,您的映像未保存在modelform
中的另一个可能原因是在POST
条件中添加了request.FILES
:应为:
ijnw1ujt3#
数据.profile_pic =请求.文件[“配置文件_pic”]
使用请求文件