How do I create a Slug automatically from the title of an item created with a Django form

Asked

Viewed 76 times

-1

Like the line prepopulated_fields = {'slug': ('name',)} you can generate the Slug of an object automatically just by typing its name in the admin panel. I wanted to do this also when the object is created from a form. How do I do this?

my model.py

from django.db import models
from django.urls import reverse


class Team(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    slug = models.SlugField(max_length=255)
    archived = models.BooleanField(default=False)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("core:team", kwargs={'pk': self.pk})

My form.py

from django import forms
from .models import Team


class TeamForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ['name', 'description']

My view.py

from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Team
from .forms import TeamForm


def homePage(request):
    """
    View all teams.
    """
    context = {
        'teams': Team.objects.all().filter(archived=False),
    }
    template = 'index.html'
    return render(request, template, context)


def teamDetail(request, pk):
    """
    View team details
    """
    context = {
        'team': get_object_or_404(Team, pk=pk),
    }
    template = 'team.html'
    return render(request, template, context)


def createTeam(request):
    """
    Create a team
    """
    form = TeamForm(request.POST or None)

    if request.method == 'POST':

        if form.is_valid():
            teams_instance = form.save(commit=False)
            teams_instance.save()
            return HttpResponseRedirect(reverse(
                'core:team',
                kwargs={'pk': teams_instance.pk}))

    context = {
        'form': form
    }
    template = 'create_team.html'
    return render(request, template, context)


def updateTeam(request, pk):
    """
    Update a team
    """
    get_team = get_object_or_404(Team, pk=pk)
    form = TeamForm(request.POST or None, instance=get_team)

    if request.method == 'POST':

        if form.is_valid():
            teams_instance = form.save(commit=False)
            teams_instance.save()
            return HttpResponseRedirect(reverse(
                'core:team',
                kwargs={'pk': teams_instance.pk}))

    context = {
        'form': form
    }
    template = 'update_team.html'
    return render(request, template, context)


def deleteTeam(request, pk):
    """
    Detele team
    """
    get_team = get_object_or_404(Team, pk=pk)

    if request.method == 'POST':
        get_team.delete()
        return redirect('core:home')

    context = {
        'delete': get_team,
    }
    template = 'delete_team.html'
    return render(request, template, context)
  • If it is while the person type, you will have to use javascript or similar. If it is after that the person submits (createTeam) just put between the teams_instance = and the teams_instance.save().

1 answer

0

If it is while the person type, you will have to use javascript or similar and then it is better to post in another forum.

If it is after the person submits (createTeam) just put between the lines

teams_instance = form.save(commit=False)

and

teams_instance.save()

something like

teams_instance.meu_slug = slug(campo_que_vc_quer_slug)

Don’t forget to install the module slug

pip install slug

and carry it

from slug import slug

Example

>>> from slug import slug

>>> slug("Isso é uma slug")
'isso-e-uma-slug'

I hope it helps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.