views:

119

answers:

2

I just can't figure out how to upload images in django. I've read dozens of blog posts and questions here, but most of them just confuse me more.

Here is what I have so far. This is my model:

 class Post(models.Model):
  user = models.ForeignKey(User)
  screenshot = models.ImageField(null=True, upload_to="images")
  date = models.DateTimeField("date posted", auto_now=True)
  text = models.TextField()

Here is the form that I use:

 class PostForm(forms.Form):
   text = forms.CharField(
      widget = forms.Textarea(attrs = {'cols': 40, 'rows': 10}), required=True)
   screenshot = forms.ImageField(required=False)

And here is how I currently process the form:

  if request.method == 'POST':
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
      post = Post(
        user = request.user, 
    text=form.cleaned_data['text'], 
    screenshot=form.cleaned_data['screenshot']
      )
      post.save()

But this doesn't work, the file is not uploaded to the server. According to the documentation on file uploads, I have to write my own handle_uploaded_file function, but that page doesn't explain:

  • How do I figure out where to save the uploaded file?
  • How do I spread files over multiple directories?
  • How do I prevent two files with the same name to overwrite each other?
  • What value do I assign to the ImageField of my model?

That seems like those problems have already been solved a thousand times...

+1  A: 

1) Your ImageField needs an upload_to path:

forms.ImageField(required=False, upload_to="/relative/path/to/foo/bar")

Note that, IIRC, this is relative to your MEDIA_ROOT

2) For spreading them over directories, just set upload_to=my_path_naming_method and do

def my_path_naming_method(instance, filename):
  #something here that returns a new/bespoke string path for each file or similar

3) If two files have the same name, Django gives the newer one a _ suffix. eg foo.jpg and 'foo_.jpg' so there is never a name collision

4) I don't get what you mean by that, but hopefully 1-3 have got you rolling.

stevejalim
No, that is not right. When I set an upload_to on forms.ImageField, I get the following error:"__init__() got an unexpected keyword argument 'upload_to'"
amarillion
Whoops - my typo: should be models.ImageField
stevejalim
A: 

In the end, it turns out my code was right but my Django version was wrong. After I upgraded to Django 1.2.1 (from 1.0.2), my code worked unchanged.

To answer my own questions

  • The images get uploaded to the upload_to dir I specified, relative to the MEDIA_ROOT specified in settings.py
  • Still not sure about this one
  • Django automatically adds underscores to the file name to prevent duplicates
  • assigning screenshot=form.cleaned_data['screenshot'] like in the code above works as expected.
amarillion