Prepopulate a Form Field Using Slugs and Integers - Django

Written by Kyle Bruder, published on April 11, 2021, 1:29 a.m., last updated on April 11, 2021, 1:34 a.m.


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. If the context is enough to know exactly what a field's value is then you can set it behind the scenes without any user action.

What is Meant by "Slug" and "Integer"?

The way the Django framework handles URLs is very handy and friendly to search engine optimization. In case you are unfamiliar, you can insert dynamically created URLS into HTML pages and pass keyword arguments to the "path()" items in an app's "" file. For our purposes, we will focus on two argument types; "slug" and "integer".


A slug is a word, phrase, title or combination of alpha-numeric characters without spaces, that is compatible with the URL syntax. Only word characters are allowed. A word character in character encoding is any uppercase or lowercase letter, the integers 0 through 9, "_" (underscore) and "-" (hyphen). Slugs are used after the fully qualified domain name and demarcated by "/" (forward slash).

class Text:
    def slugify_unique(model, title):
        Given a DB model and a title, return a unique slug that is unique \
        to all other slug fields of the given DB model.
        model - Must be a Django database model that has \
                   a slug field called "slug".
        title - The string used to create the slug.

        Returns - A slug that is unique across all instances of the model.
        from django.utils.text import slugify
        slug = slugify(title)
        existing_slugs = []
            [existing_slugs.append(str(i.slug)) for i in model.objects.all()]
            print("There was no slug field found for {}".format(model))
            return slug
        if slug in existing_slugs:
            date_slug = slug + "-" +"%Y%m%d")
            if date_slug in existing_slugs:
                long_slug = date_slug +"%m%s")
                return long_slug
                return date_slug
            return slug

Source: kbruder Tech


The integer keyword argument is exactly what is sounds like. It's simply a positive whole number or zero.

Source: kbruder Tech

Assign the Form Field in form_valid() in a CreateView

class BarCreateView(LoginRequiredMixin, CreateView):
    model = Bar
    form_class = BarForm
    def form_valid(self, form):
        member = self.request.user
        if self.kwargs['model'] == 'baz':
            form.instance.baz = Baz.objects.get(pk=self.kwargs['pk'])
        if self.kwargs['quz']:
            form.instance.quz = self.kwargs['quz']
        form.instance.creation_date =
        form.instance.owner = member
        form.instance.slug = Text.slugify_unique(self.model, form.instance.title)
        return super().form_valid(form)

Source: kbruder Tech

Add the URL Path to ""

app_name= "foo"

urlpatterns = [

Source: kbruder Tech

Add the Link to a Template

<a href="{% url 'foo:bar_create' model='baz' quz=baz.quz %}"><button type="button" class="btn btn-sm btn-primary float-right">+Bar</button></a>

Source: kbruder Tech

The Resulting URL

This URL will open a form. If the form post is valid, then the resulting Bar instance will have a 'baz' field that points to a Baz instance with a PK of 420 and a 'quz' field set to True.

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.

Example Django Python HTML: 5

Contributed by Kyle Bruder on April 11, 2021, 1:29 a.m.
Last updated on April 11, 2021, 1:34 a.m.