0

I have a form where a user can update their profile. I want the user to choose from a drop down list of all the available profile pictures (a gallery of profile pictures from the ProfilePictures Model) which they want to be their profile picture. At the moment the form returns the string of the image URL. How can i make the actual image be in the drop down so that a user can see all the images before choosing the one they want?

Models.py

class ProfilePicture(models.Model):
image = models.ImageField(upload_to='profile_pics', blank=True)

def __str__(self):
    return f'{self.image.url}'


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(default=' Your Bio   ', max_length=200)
    pic = models.ForeignKey(ProfilePicture, on_delete=models.SET_DEFAULT, default='1')

    def __str__(self):
        return f'{self.user.username} Profile'

Forms.py

class ProfileUpdateForm(forms.ModelForm):
class Meta:
    model = Profile
    fields = ['bio','image','pic']
    # widgets = {
    #     'pic': ImageField(),
    # }

Image of the current dropdown list

Community
  • 1
  • 1
bruzza42
  • 393
  • 2
  • 13

1 Answers1

0

You can render choices manually.

If your ModelForm look like this:

class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['bio','pic']

then you can render this pic field in template as:

<form method="post" action="" >
    {% csrf_token %}>

    <select name="{{ form.pic.name }}">
        {% for q in form.pic.field.queryset %}
            <option value="{{ q.pk }}"><img src={{ q.url }}></img></option>
        {% endfor %}
    </select>

    # ..
    # add other fields
</form>
narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58
  • I am rendering the form using crispy forms and functions in my views.py. Like '{{ p_form|crispy }}'. In my models i have a def__str__(self): function. Is there no way to return the object, rather than a string? – bruzza42 May 04 '20 at 12:09