title: Populating Field in Form with Images in Django
body: <p>I'm trying to populate a field with images from a model in Django. The idea is that the user will enter the name of their product, then ultimately an API with google images will look that up and populate a field on the next page with a couple images to select.</p>
  <p>At this stage, I'm just trying to get a field on the form to show multiple images for the user to select and I'm having a hard time. Here's some of my code, any input is helpful. I know there is a lot out there around this topic and I've looked through a lot but I'm still stuck. My most recent attempt was to create a custom Widget, I'm really open to any solution that will work.</p>
  <p>I'm really not a Django/Python wizard so bear with me :) Thank you!</p>
  <p>Models.py</p>
  <pre><code>class ProductImage(models.Model):
  imageId = models.AutoField(auto_created=True, primary_key=True)
  image = models.ImageField(upload_to='images',null=True,blank=True)
  
  def __str__(self):
      return str(self.image)
  
  
  class Item(models.Model):
  itemId = models.AutoField(auto_created=True, primary_key=True)
  itemName = models.CharField(
      &quot;Name&quot;,
      max_length=1024,
  )
  category = models.ForeignKey(Category,
                               on_delete=models.CASCADE,
                               related_name='category'
                               )
  itemImage = models.ForeignKey(ProductImage,
                                on_delete=models.CASCADE,
                                related_name='photo',
                                default=&quot;&quot;,
                                )
  itemOwner = models.ForeignKey(Customer,
                                on_delete=models.CASCADE,
                                related_name='my_items'
                                )
  itemAvaialable = models.BooleanField()
  costPerItem = models.IntegerField(verbose_name='Cost per Item (USD)')
  itemDescription = models.TextField(null=True, blank=True)
  itemAddedDate = models.DateField(auto_now_add=True)
  asin = models.CharField(null=True, blank=True, max_length=10)
  </code></pre>
  <p>forms.py</p>
  <pre><code>class ImageCreationForm(forms.ModelForm):
  class Meta:
      model = ProductImage
      fields = ('image',)
  
  def clean_itemImage(self):
      itemImage = self.cleaned_data['itemImage']
      valid_extensions = ['jpg', 'jpeg']
      extension = itemImage.rsplit('.', 1)[1].lower()
      if extension not in valid_extensions:
          raise forms.ValidationError('The given product Image file does not ' \
                                      'match valid image extensions.')
      return itemImage
  
  class ItemCreationForm(forms.ModelForm):
  class Meta:
      model = Item
      fields = '__all__'
      widgets = {
          'itemAddedDate': forms.HiddenInput,
      }
  </code></pre>
  <p>Views.py</p>
  <pre><code>class AddImageView(LoginRequiredMixin,CreateView):
  model = ProductImage
  template_name = 'addImage.html'
  fields = ('image',)
  
  def form_valid(self, form):
      form.is_valid()
      form.instance.itemOwner = self.request.user
      return super().form_valid(form)
  
  def get_success_url(self):
      return reverse('RentalApp:my_products')
  
  
  class AddProductView(LoginRequiredMixin, CreateView):
  model = Item
  template_name = 'addProduct.html'
  image = forms.FileField(required=False)
  fields = ('itemName',
            'category',
            'itemImage',
            'itemAvaialable',
            'costPerItem',
            'itemDescription')
  login_url = '/users/login/'
  
  def form_valid(self, form):
      form.fields[&quot;itemImage&quot;].queryset = ProductImage.objects.all()
      form.is_valid()
      form.instance.itemOwner = self.request.user
      return super().form_valid(form)
  
  def get_success_url(self):
      return reverse('RentalApp:my_products')
  </code></pre>
  <p>Widgets.py</p>
  <pre><code>class ImageWidget(forms.widgets.Widget):
      def render(self, name, value, attrs=None, **kwargs):
          html = Template(&quot;&quot;&quot;&lt;img src=&quot;$link&quot;/&gt;&quot;&quot;&quot;)
          return mark_safe(html.substitute(link=value))
  </code></pre>
  <p>Serializers.py</p>
  <pre><code>class ProductImageSerializer(serializers.ModelSerializer):
  
      product_image = serializers.SerializerMethodField()
  
      class Meta:
          model = ProductImage
          fields = ('image')
  
  
  class ProductImageRequirementSerializer(serializers.ModelSerializer):
      class Meta:
          model = ProductImage
          fields = ('image')
  
  
  class ProductSerializer(serializers.ModelSerializer):
      Product_requirement = serializers.SlugRelatedField(many=True,read_only=True,slug_field='text')
      club_image = ProductImageSerializer(many=True)
  
      class Meta:
          model = ProductImage
          fields = ('image')
  </code></pre>
  <p>Template for adding a product:</p>
  <pre><code>{% extends 'base.html' %}
  {% load crispy_forms_tags %}
  {% block content %}
   &lt;div id=&quot;login&quot;&gt;
      &lt;h5 class=&quot;text-center pt-5&quot;&gt;Add Product&lt;/h5&gt;
      &lt;div id=&quot;login-row&quot; class=&quot;row justify-content-center align-items-center&quot;&gt;
          &lt;div id=&quot;login-column&quot; class=&quot;col-md-6&quot;&gt;
              &lt;div id=&quot;login-box&quot; class=&quot;col-md-12&quot;&gt;
                  &lt;form action=&quot;&quot; method=&quot;post&quot; id=&quot;login-form&quot; enctype=&quot;multipart/form-data&quot; class=&quot;form&quot;&gt;{% csrf_token %}
                    {{ form|crispy }}
                      &lt;br&gt;
                    &lt;button class=&quot;btn btn-success ml-2&quot; type=&quot;submit&quot;&gt;Save&lt;/button&gt;
                      &lt;a href=&quot;{% url 'RentalApp:my_products' %}&quot; class=&quot;btn btn-secondary ml-2&quot;&gt;
                      Cancel&lt;/a&gt;
                  &lt;/form&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
   &lt;/div&gt;
  {% endblock content %}
  </code></pre>