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!
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With