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))
精彩评论