Prepopulate a Form Field using URL Parameters - Django

Written by Kyle Bruder, published on April 11, 2021, 1:41 a.m., last updated on April 21, 2021, 5:48 p.m.


Screenshot_from_2021-04-10_18-33-25


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.

https://duckduckgo.com/?q=Lookaway+Information&t=canonical&ia=web

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 urls.py.

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

Source: kbruder Tech


Add the Parameter in the Create or Update View

foo/forms.py
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
        ...

Source: kbruder Tech


Override models.ModelForm init Method

In your app's forms.py 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.

foo/forms.py
class FooSectionForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        # Populate Bar field
        if 'bar' in kwargs:
            bar = kwargs.pop('bar')
            kwargs.update(initial={
                'bar': bar
            })
        super(FooSectionForm, self).__init__(*args, **kwargs)

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:3MnhNRKgrpTFQWstYicjF6GebY7u7dap4u
Bitcoin Accepted Here

3MnhNRKgrpTFQWstYicjF6GebY7u7dap4u

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:MT61gm6pdp9rJoLyMWW5A1hnUpxAERnxqg
Litecoin Accepted Here

MT61gm6pdp9rJoLyMWW5A1hnUpxAERnxqg

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.


Example Django Python HTML: 5

Contributed by Kyle Bruder on April 11, 2021, 1:41 a.m.
Last updated on April 21, 2021, 5:48 p.m.