Fill Django Form Field Data with Db Data
I am trying pre-fill a form field with data from a Db object. 开发者_StackOverflow社区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!
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
精彩评论