help please deal with ForeignKey

I have a model:

class UserProfile(models.Model): CHOICES_status = ( ('0', 'статус отключен'), ('1', 'в поиске'), ('2', 'в космосе'), ('3', 'женат'), ('4', 'член партии'), ) user = models.OneToOneField(User) family = models.CharField(max_length=30, blank=True) name = models.CharField(max_length=30, blank=True) nation = models.CharField(max_length=30) status = models.CharField(max_length=30, blank=True, choices=CHOICES_status, default='0') avatar = models.ImageField(upload_to='userprofile/', blank=True) nation_show = models.BooleanField(default=True, blank=True) 

she works. the problem is that I would like to keep the list of statuses not in the constant CHOICES_status, but in a separate table

for this, I create and fill in the table, which corresponds to the following model:

 class UserStatus(models.Model): status = models.CharField(max_length=30) 

but I do not understand how to connect these two models (tables)

if I do this:

 class UserProfile(models.Model): user = models.OneToOneField(User) family = models.CharField(max_length=30, blank=True) name = models.CharField(max_length=30, blank=True) nation = models.CharField(max_length=30) status = models.ForeignKey() avatar = models.ImageField(upload_to='userprofile/', blank=True) nation_show = models.BooleanField(default=True, blank=True) 

, firstly it does not work, and secondly it is not clear where the instruction to use the drop-down list

please tell me the code example

    1 answer 1

    And it should not work :)

    ForeignKey, to put it simply, should show that such and such a field (in your case, status) can take values ​​from such and such a table (in your case, UserSatatus), for which the first argument takes this class with a table whose values ​​can be accepted by the field.

      status = models.ForeignKey(UserStatus) 

    Then you will have a drop-down list in the admin panel (provided that there are entries in the UserStatus table).

    • now clearer. only I do not go through the admin panel to select the status. I have made a registration system and each registered user has a personal page where they can change their personal data. including choose status - cyklop77
    • one
      Ok, so you have a form class? You can write the status = forms.ModelChoiceField (queryset = UserStatus.objects.all (), label = _ (u'status'), widget = forms.Select ()) - iterq
    • one
      If the form is made from a model, it is better to use a ModelForm, then you do not need to prescribe anything with your hands. - ravli