开发者

Uploading images from Django view

Models:

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

Forms:

from models import Advertisement
from django.forms import *

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

Q: How should I form an upload view?


Something like this should work. Make sure you inlcude enctype="multipart/form-data" in your form tag so the files get uploaded.

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜