forms with foreign keys
Date: March 20th 2016
Last updated: March 20th 2016
Adding foreign keys to a form was easier than I originally thought. In this example I only update forms.py used in the example basic form.
forms.py
from django import forms
from surferprofile.models import Surfer, Board, Wave, Trick, Fin, Beach
class SurferForm(forms.ModelForm):
boards = forms.ModelMultipleChoiceField(
queryset=Board.objects.all())
homebeach = forms.ModelMultipleChoiceField(
queryset=Beach.objects.all())
fins = forms.ModelMultipleChoiceField(
queryset=Fin.objects.all())
tricks = forms.ModelMultipleChoiceField(
queryset=Trick.objects.all())
favwave = forms.ModelMultipleChoiceField(
queryset=Wave.objects.all())
class Meta:
model = Surfer
fields = ['firstname','lastname',
'height', 'weight',
'DOB','hometown',
'homebeach','favwave',
'boards','fins','tricks']
127.0.0.1:8080/1/update/
Note the order set by fields.