简体   繁体   中英

How do I use a pre-set list of choices from a foreign key as the options to select from in a ModelForm in Django?

I have 2 models, one is a profile user model and the other for categories of that profile. (see below). The category model has one 'name' attribute which consists of a set of choices that users must choose as their profile type.

class DkUser(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    category=models.ForeignKey(Category, blank=True, null=True)


CATEGORIES = (
             ('cat1', 'Category1'),
             ('cat2', 'Category2'),
             ('cat3', 'Category3'),
             )

class Category(models.Model):
    name=models.CharField(max_length=100, choices=CATEGORIES)

My form thus far:

class ProfileForm(forms.ModelForm):
  category = forms.ChoiceField()
  class Meta:
        model = DkUser
        fields = ('category')

What I'm trying to do is to include a drop-down choice-field on the form that allows users to select one of 'category 1', 'category 2' or 'category3'.

I've looked at ModelChoiceField, but that appears to be for choosing from the Model Instances.

How might I achieve this? All help greatly appreciated.

I believe you don't need to have a ProfileForm defined, and what you need is to have a str method for your Category model, and django will do everything for you. As far as i know following should work as you want:

class DkUser(models.Model):
   user = models.OneToOneField(settings.AUTH_USER_MODEL)
   category=models.ForeignKey(Category, blank=True, null=True)

CATEGORIES = (
         ('cat1', 'Category1'),
         ('cat2', 'Category2'),
         ('cat3', 'Category3'),
  )

class Category(models.Model):
   name=models.CharField(max_length=100, choices=CATEGORIES)

def __str__(self):
    return self.name

And on Admin page you should see a combo-box for category field for DKUser model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM