title: Django image file uploads
body: <p>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.</p>
  
  <p>Here is what I have so far. This is my model:</p>
  
  <pre><code> 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()
  </code></pre>
  
  <p>Here is the form that I use:</p>
  
  <pre><code> class PostForm(forms.Form):
     text = forms.CharField(
        widget = forms.Textarea(attrs = {'cols': 40, 'rows': 10}), required=True)
     screenshot = forms.ImageField(required=False)
  </code></pre>
  
  <p>And here is how I currently process the form:</p>
  
  <pre><code>  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()
  </code></pre>
  
  <p>But this doesn't work, the file is not uploaded to the server. According to the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField" rel="nofollow noreferrer">documentation on file uploads</a>, I have to write my own handle_uploaded_file function, but that page doesn't explain:</p>
  
  <ul>
  <li>How do I figure out where to save the uploaded file?</li>
  <li>How do I spread files over multiple directories?</li>
  <li>How do I prevent two files with the same name to overwrite each other?</li>
  <li>What value do I assign to the ImageField of my model?</li>
  </ul>
  
  <p>That seems like those problems have already been solved a thousand times...</p>