从Django视图上传图像

时间:2011-06-15 14:08:30

标签: django django-forms django-views django-uploads

型号:

from django.db import models
class Image(models.Model):
    advertisement = models.ForeignKey('Advertisement')
    image = ImageWithThumbsField(upload_to=store_path, blank=True)

class Advertisement(models.Model):
    #some code here

class AdvertOne(Advertisement):
    #some code again

class AdvertTwo(Advertisement):
    #and again

形式:

from models import Advertisement
from django.forms import *

class AdvertisementForm(ModelForm):
    message = CharField(max_length=400, widget=Textarea)
    image = ImageField(required=False)

问:我应该如何形成上传视图?

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效。确保在表单标记中包含enctype="multipart/form-data",以便上传文件。

def upload_advertisement(request):
    if request.method == "POST":
        form =  AdvertisementForm(request.POST,request.FILES, prefix='advertisement')
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/")
    else:    
        form =  AdvertisementForm(prefix='advertisement')

    return render_to_response('advertisementform.html', {
        'form':form,
    }, context_instance=RequestContext(request))