0

I have a use case where in UserProfile model, user details are stored. One of the field is user_company_name.

class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company_name = models.CharField(max_length=254)

Instead of a CharField I want the field to be a ChoiceField, having drop down of the Company (names) currently present in the database. If the current company of the user is not present in the dropdown I plan to give the user an option to add his or her company to the DB. Suppose I have a Company model as such:

class Company(BaseModel):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

What should be my Field Choice in the UserProfile model for user_company_name field.

Piklu Dey
  • 190
  • 1
  • 13

3 Answers3

0

Why don't just add ForeignKey to UserProfile model? Example below.

class UserProfile(BaseModel):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    user_company = models.ForeignKey(Company)
Szymon P.
  • 1,008
  • 7
  • 11
0

You need ForeignKey for this field user_company_name

https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey read this doc

Mubariz Feyziyev
  • 412
  • 4
  • 16
0

You can use foreign key in the models for user_company and in forms use ChoiceField to get a drop down.

Check the code below:-

In models:-

class UserProfile(BaseModel):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
user_company = models.ForeignKey(Company)

In Forms:-

user_company = forms.ModelChoiceField(queryset=Company.objects.all())