HunterBerry
HunterBerry

Reputation: 195

Using Django to Dynamically Create New URLs/Pages

I am working on a program that allows users to create pages to monitor and manage tournaments that may be going on at their high schools and colleges, specifically MUN and Forensics tournaments. Whenever the user logs in, he or she has the option to create a new tournament, which should create a new URL and base web page for them, where they can edit the tournament to their liking. For instance, if a user created a tournament named "Hello World," then I want to be able to make them a page they can visit at example.com/helloworld. Are there any built in Django functions that can help with something like this?

Upvotes: 1

Views: 948

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

You can just have common url pattern with slug here:

models.py

from django.db import models
from django.utils.text import slugify


class Tournament(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)

    def _get_unique_slug(self):
        '''
        In this method a unique slug is created
        '''
        slug = slugify(self.name)
        unique_slug = slug
        num = 1
        while Tournament.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

urls.py

urlpatterns = [
    path('<slug:slug>/', views.tournament_detail_view),
]

views.py

def tournament_detail_view(request, slug):
    tournament = get_object_or_404(Tournament, slug=slug)    
    return render(request, 'tournament/detail.html', {'tournament': tournament})

So what we have: when a user creates a new Tournament with name Hello World it will be available with example.com/hello-world url.

For tournament with name New Tournament it becomes available with example.com/new-tournament url. And etc.

Upvotes: 2

Related Questions