Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill Django Form Field Data with Db Data

I am trying pre-fill a form field with data from a Db object. How do you set up the form,view, and model to fill a field with this data?

The goal is to let the user only select data that is queried from the object. Ex. An event has bands playing, the user selects their favorite band from those at the event.

I tried looking through the docs for form.data - but can't seem to find what I'm looking for.

Thanks!

like image 687
Emile Avatar asked Jan 20 '11 05:01

Emile


People also ask

How does Django get data from database?

The database view is created by following the SQL and it can be injected into a customized data migration with the raw SQL execution command. The next step is to create a Django model which maps to this view so we can use Django ORM to retrieve the data from the view.


2 Answers

Supposing your Events model has bands as Many-2-Many key, the layout of the forms and views would be as follows:

forms.py:

class EditEventForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditEventForm, self).__init__(*args, **kwargs)
        self.fields['bands'].queryset= \
                      Bands.objects.filter(Q(name='band1')|Q(name='band2'))
    class Meta:
        model = Event

NOTE: You would need to adjust the queryset fetching in the forms for your requirement.

views.py:

form = EditEventForm(instance=event)

Moreover, in line with the suggestion given by dcrodjer, go ahead and read some text on implementing ModelMultipleChoiceField

like image 120
sidhshar Avatar answered Oct 14 '22 13:10

sidhshar


You can get a little more custom by passing arguments to the Form

class SelectBandForm(forms.Form):
def __init__(self, event, *args, **kwargs):
    super(EditEventForm, self).__init__(*args, **kwargs)
    self.fields['bands'] = forms.ModelChoiceField(label="Whats your favorite band?",
               empty_label="Select a Band" , querset=Bands.objects.filter(event=event))

Then in your views

if request.method =="POST":
   form = SelectBandForm(event, request.POST)
   if form.is_valid():
        #do stuff
else:
   form = SelectBandForm(event)
   #show it
like image 35
Cyrus Cold Avatar answered Oct 14 '22 12:10

Cyrus Cold