title: django upload to image model with foreign key to user
body: <p>I'm using Django's Extended User Profile and instead of having many image fields I want to make a new Images class in my models that I can upload many images which automatically get assigned to the right user. Then the user can view and edit all their images. I'm basically stuck on the last part (view and edit).</p>
  
  <p>My app is called ve</p>
  
  <p>models.py</p>
  
  <pre><code>class Profile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      bio = models.TextField(max_length=500, blank=True)
      ... etc   
  
  class Images(models.Model):
      image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
      user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
  </code></pre>
  
  <p>forms.py</p>
  
  <pre><code>class ImagesForm(forms.ModelForm):
      image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
      class Meta:
          model = Images
          fields = (
              'image',
          )
  </code></pre>
  
  <p><strong>1. Edit Image(s)</strong></p>
  
  <p>This setup, uploads image (in admin) but doesn't assign the user. Another problem is I can only upload/edit 1 image.</p>
  
  <p>views.py </p>
  
  <pre><code>@login_required
  @transaction.atomic
  def edit_images(request):
      if request.method == 'POST':
          images_form = ImagesForm(request.POST, request.FILES)
          if images_form.is_valid():
              images_form.save()
              return redirect('ve:index_account')
          else:
              pass
  
      else:
          images_form = ImagesForm(request.POST, request.FILES)
  
      return render(request, 've/cp/edit_images_account.html', {
          'images_form': images_form,
      })
  </code></pre>
  
  <p>edit_images_account.html</p>
  
  <pre><code>    &lt;form method="post" enctype="multipart/form-data"&gt;
      {% csrf_token %}
      {{ images_form.as_p }}
      &lt;button type="submit"&gt;Upload&lt;/button&gt;
      &lt;/form&gt;
  </code></pre>
  
  <p><strong>2. View Image(s)</strong></p>
  
  <p>views.py</p>
  
  <pre><code>@login_required
  def index_account(request):
      args = {'user': request.user}
      return render(request, 've/cp/index_account.html', args)
  </code></pre>
  
  <p>index_account.html</p>
  
  <pre><code>&lt;p&gt;&lt;a href="{% url 've:edit_images' %}"&gt;Edit your images&lt;/a&gt;&lt;/p&gt;
              {% if user.images.images %}
                  {% for img in user.images %}
                  &lt;img src="{{ user.images.image.url }}"&gt;&lt;br&gt;
                  {% endfor %}
              {% else %}
              &lt;p&gt;No images&lt;/p&gt;
  
              {% endif %}
  </code></pre>