During form processing I’d like to be able to set a foreign key field on a model object without the user having to select the key from a dropdown.
For instance:
JavaScript
x
9
1
#models.py
2
class AAA(models.Model):
3
4
some_field = models.TextField()
5
6
class BBB(models.Model):
7
another_field = models.TextField()
8
key_field = models.ForeignKey('AAA')
9
The user will navigate from a view showing an instance of ‘AAA’ to a create_object style view that will create an instance of ‘BBB’ given a parameter referring to ‘AAA’. The foreign key is set in code to point back to the ‘AAA’ instance.
The django comments framework seems to do this but I can’t figure out how.
Any ideas? I’m sure it should be quite simple.
Advertisement
Answer
You can exclude the key_field
from your model form, save with commit=False
, then set key_field
in your view before saving to the database.
JavaScript
1
16
16
1
class BBBForm(forms.ModelForm):
2
class Meta:
3
model = BBB
4
exclude = ("key_field",)
5
6
def create_view(request, **kwargs):
7
if request.method == "POST":
8
aaa = # get aaa from url, session or somewhere else
9
form = BBBForm(request.POST)
10
if form.is_valid():
11
bbb = form.save(commit=False)
12
bbb.key_field = aaa
13
bbb.save()
14
return HttpResponseRedirect("/success-url/")
15
16