上传到默认django db的简单图像永远不会完成。该错误似乎表明图像字段出现问题,就像我的views.py打印form.errors,它返回
这是我的代码,我只上传了我认为可能影响它的内容。
models.py
class Image(models.Model):
name = models.CharField(max_length=128, unique=True)
image = models.ImageField(upload_to="user_images")
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Image, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
forms.py
from django import forms
from shareIt.models import Image
class ImageForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter an image name")
image = forms.ImageField()
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Image
fields = ('name', 'image')
views.py
def uploadImage(request):
if request.method== 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=True)
return images(request)
else:
print form.errors
else:
form = ImageForm()
contextdict = {"form": form}
return render(request, 'uploadImage.html', contextdict)
uploadImage.html
<html>
<form id="upload" action="/share/images/upload" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit", value="upload image" />
</form>
答案 0 :(得分:8)
将enctype
属性添加到<form>
代码:
<form id="upload" action="/share/images/upload" enctype="multipart/form-data" method="post">
答案 1 :(得分:0)
使用模型表单时,无需键入:
name = forms.CharField(max_length=128, help_text="Please enter an image name")
image = forms.ImageField()
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
您的模型中已有此功能。你只需要这个:
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ('name', 'image')