This is a website for a tattoo shop. I have an Artist
and Tattoo
model:
class Artist(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
# etc
class Tattoo(models.Model):
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
name = models.CharField(max_length=150)
image = models.ImageField(upload_to='images/')
and a ModelForm
designed to allow artists to filter tattoos by artist:
class FilterArtForm(ModelForm):
class Meta:
model = Tattoo
fields = ['artist']
widgets = {
'artist': forms.Select(attrs={'id': 'filter_by_artist'}),
}
This form will create the following:
<form>
<label for="filter_by_artist">Artist:</label></th>
<select name="artist" id="filter_by_artist" required>
<option value="" selected>---------</option>
<option value="1">Artist 1</option>
<option value="2">Artist 2</option>
</select>
</form>
I am trying to store each Artist
objects id in their respective <option>
field. I was thinking I would have to add something like data-artist_id
to each one as such: <option value="1" data-artist_id >Artist 1</option>
but I suppose I could just change the value
attribute? Looking at it, if the value
attribute automatically increases by 1 each time it would seem that that should always align with the Artist
's object id value, but it just seems like I should be more explicit to avoid future headaches(for example if an Artist
object gets deleted and another added, I don't think these values will longer align)? Is there a way to build the field in forms.py like the following:
<option value="{{artist.id}}">Artist 1</option>
Thanks for any help.
CodePudding user response:
You do not have to do anything. By default, the value is the artist's id. Those values of the options of your select are the ids of the artists that you have registered. It is not an arbitrary numbering, they are already the id of the artist.