-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 theteams_instance.save()
.– Paulo Marques