Skip to content Skip to sidebar Skip to footer

How To Set Foreign Key During Form Completion (python/django)

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: #models.py class AA

Solution 1:

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.

classBBBForm(forms.ModelForm):
    classMeta:
        model = BBB
        exclude = ("key_field",)

defcreate_view(request, **kwargs):
    if request.method == "POST":
        aaa = # get aaa from url, session or somewhere else
        form = BBBForm(request.POST)
        if form.is_valid():
            bbb = form.save(commit=False)
            bbb.key_field = aaa
            bbb.save()
            return HttpResponseRedirect("/success-url/")
        ...

Solution 2:

As the user creates a BBB via an instance of AAA, this should be reflected in the URL, i.e., your "create_object style view" will get a parameter identifying an AAA object. You can use it to get the object from the database and create your BBB object accordingly:

from django.shortcuts import get_object_or_404

defcreate_bbb_view(request, aaa_id):
    a = get_object_or_404(AAA, id=aaa_id)
    form = MyBBBCreationForm(request.POST) # or similar codeif form.is_valid():
         b = BBB.objects.create(key_field=a) # plus other data from form# ...

(You could also set key_field to aaa_id directly, but it's probably a good idea to check if the object exists.)

Post a Comment for "How To Set Foreign Key During Form Completion (python/django)"