Django: how to use upload_to property of an ImageField
I'm writing a large application with image uploads.
Here is my model:
class GallryImage(models.Model):
# ...
image = models.ImageField(max_length=255, upload_to='gallery', height_field='width', width_field='height')
width = models.IntegerField()
height = models.IntegerField()
# ...
And here is how I handle the upload:
image_name = 'image.png';
destination = open(settings.MEDIA_ROOT + '/gallery/' + image_name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
This code, kind of, violates the DRY principle - the path gallery
is repeated twice.
Question: how do I reuse path tha开发者_如何学Ct I have specified in my model (upload_to='gallery'
), so that I would not have to repeat in upload handler?
I am using python 2.6 and Django 1.3 beta.
Thank you!
Solution based on Paulo's answer
When instance of a model is saved, the file is uploaded automatically, so all I have to do is this:
def add(request):
from forms import ImageAddForm
form = ImageAddForm()
if request.method == 'POST':
form = ImageAddForm(request.POST, request.FILES)
if form.is_valid():
image = GalleryImage(
image = form.cleaned_data['image']
)
image.save() # file is uploaded to upload_to dir!
return HttpResponseRedirect(reverse('image_add') + '?image_added=')
else:
form = ImageAddForm()
return render_to_response('gallery/add.html',
locals(),
context_instance=RequestContext(request))
The forms framework should take care of this for you. No need to save the files by hand unless you want to store them in some container other than your filesystem.
class UploadImageForm(forms.ModelForm):
class Meta:
model = GallryImage
...
# Sample view
def upload_file(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadImageForm()
return render_to_response('upload.html', {'form': form})
精彩评论