Prepopulate a Form Field using URL Parameters - Django

Documented by kbruder tech✞ᵀᵀᴹ on Apr 11, 2021
Last updated on Apr 21, 2021



Filling out forms online sucks balls. ANYTHING that will reduce the soul sucking task of filling out an online form is welcome. Many times a page with a link to a form will exist with some semblance of context. In many cases, the context is enough to make an educated guess about what the end user will choose for a given form field.

What are URL Parameters?

In case you do not already know, URL stands for Uniform Resource Locator. As the name suggests, its a standard syntax that any application using HTTP (HyperText Transfer Protocol, the protocol that sends web page data across the Internet) uses to eventually find the IP address of the server or proxy from where the resources can be downloaded. To restate that, the URL is used to request web pages from a web server or proxy.

A URL parameter, also referred to as querystring, is a string of variable assignments. You most likely have seen a long URL with a bunch of crazy nonsense. Everything after the "?" character are the parameters. These variables are interpreted by dynamic web applications to show different data on a web page or a different web page entirely depending on the values assigned to the variables. Each assignment is demarcated by the "&" character.

This is an example URL with multiple parameters.
Source: kbruder Tech

Django HTML Template URL Syntax

In your view template, use Django's URL syntax to add a link to the form that contains the parameters. Make sure you have your URLs configured in

<a href="{% url 'foo:bar_section_create' %}?bar={{ }}"><button type="button" class="btn btn-sm btn-primary float-right">+Section</button></a>

In this example, a button links to a form that will create a "bar_section" from the "foo" app where we know that the section will belong to a "bar" model instance.
Source: kbruder Tech

Add the Parameter in the Create or Update View

class BarSectionCreateView(LoginRequiredMixin, PermissionRequiredMixin, MemberCreateMixin, CreateView):

    permission_required = 'documentation.add_barsection'
    model = BarSection
    form_class = BarSectionForm

    def get_form_kwargs(self):
        kwargs = super(StorySectionCreateView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        kwargs['baz'] = self.request.GET.get('baz')
        return kwargs

Override the get_from_kwargs() method so you can access your parameter (baz) in the __init__() method of the form class.
Source: kbruder Tech

Override models.ModelForm init Method

In your app's add a custom __init__ method to your form. If you already have an __init__ method in your ModelForm class, add the conditional statement along with everything else. You can access the URL parameters by using the "kwargs.pop()" method.

Caution: Make sure you add the super() line AFTER updating the kwargs or you will get an error.

class FooSectionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # Populate Bar field
        if 'bar' in kwargs:
            bar = kwargs.pop('bar')
                'bar': bar
        super(FooSectionForm, self).__init__(*args, **kwargs)

In this example, if the request URL contains a parameter called 'bar' then update the keyword argument 'initial'. This argument is set in __init__ because we want the new data before the form is rendered.
Source: kbruder Tech


This approach will populate the field before the user posts the form for validation. This is useful when you want to suggest a value but allow the user to change the value in a widget if they choose.

Bitcoin Accepted Here


Please donate some Bitcoin to our site. We can use it to keep improving the site and open up to more members. Any amount will help. Thank you.

Litecoin Accepted Here


Please donate some Lite to our site. We can use it to keep improving the site and open it up to more members. Any amount will help. Thank you.