click here
click here

Reputation: 836

Populate form field with data from model without using foreign key

My problem is simple to explain but I can only think of hacky ways to solve. I have a list of 800 items that I want the user to be able to pick. They then enter stuff into a text box and hit go. And then I take it from there and process it and spit a response back.

How do I get the items I have saved in Taxonomy to populate in a dropdown in my form?

model:

class Taxonomy(models.Model):
    code = models.CharField(max_length=10, blank=False)
    specialty = models.CharField(max_length=60, blank=False)

    def __str__(self): #python 3.3. is __str__
        return self.specialty

view:

def NPI(request):
    form = NPIQueryForm(request.POST or None)
    ...other stuff...

forms.py:

class NPIQueryForm(forms.ModelForm):
    class Meta:
        model = Taxonomy
        fields = ['specialty']

The hacky ways I've considered is to just create an input field and manually paste the options. But I want them to be easily modified in admin so i'm avoiding that. Also, I considered creating two models with one being a foreign key of the other but this just seems to be very unnecessary. I must be missing something.

Upvotes: 0

Views: 104

Answers (1)

stschindler
stschindler

Reputation: 937

Django has ModelChoiceField for selecting an option from a list of model objects.

It can be used like this:

class MyForm(forms.Form):
  speciality = forms.ModelChoiceField(queryset=Speciality.objects.all())

Upvotes: 1

Related Questions