Issue
I have a model called Listing
that has a field called categories
that stores all the different categories. There is also a form with a field called categories
that should show a choice field to the user, where the choices should be the values stored in the Listing.categories
model field. So I tried to loop through it but that is not possible as the choice field values are stored in a dict format.
So how do I get the values from the model field into the choice field?
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
class Listing(models.Model):
...
category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True)
forms.py:
from .models import Listing
for i in Listing.category:
category_choices = (
(i, Listing.category)
)
class NewListing(forms.Form):
...
category = forms.ChoiceField(choices=category_choices)
Solution
You can use a ModelChoiceField in order to pass a queryset and allow the user to choose between all models in this queryset. You would then get something like :
category = forms.ModelChoiceField(queryset=Category.objects.all())
Answered By - Balizok
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.