ImageField()没有在ModelForm中保存图像 - Django / Python

时间:2015-03-20 16:11:04

标签: python django django-models django-forms django-views

当我尝试从表单上传图片时,所有内容都会处理,但图片未保存。

有谁知道为什么会这样?

提前致谢!

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 个答案:

答案 0 :(得分:15)

您应该将enctype=multipart/form-data属性添加到<form>标记:

<form method='POST' action='{{ action_url }}' enctype='multipart/form-data'>