SlugField is most important part of generating a valid URL, slug url containing only letters, numbers, underscores or hyphens.
For example, my website is bestseller.in and I have create one post and I using posting title “ how create slug field in django”
Here if I want my url show with by post title like” www.bestsaller.in/how create slug field in django” then without slug fields not possible showing correct, without slug field you have get this is url like “www.bestsaller.in/how%%create%slug%field%in%django%
It means without slug fields not possible url showing correct formate.
So django provide future slug fields option and this option is auto create . here you look how create auto slug field.
1st you have setup your .venv
2nd create your project django-admin startproject project
3rd crate your application under project, here application name is slug
python manage.py startapp slug
Python manage.py makemigrations
Python manage.py migrate
Python manage.py runserver
look like below windows.
4rd slug application add in your setting.py file
INSTALLED_APPS = [ ... "articles", # new]
5th now pip install django-autoslug
Pip install django-autoslug
6th also django-autoslug field add in setting.py
INSTALLED_APPS = [ ... "articles", # new “django-autoslug”, # slug fields]
7th now create models.py
from django.db.models import CharField, Model
from autoslug import AutoSlugField
class Post(models.Model):
title = models.CharField(max_length = 250)
slug = AutoSlugField(populate_from='title')
text = models.TextField()
def __str__(self):
return self.title
8th now models.py fields in ADMIN.PY
from django.contrib import admin from .models import post class postAdmin(admin.ModelAdmin): list_display = ("title", "text",) admin.site.register(post, postAdmin)
9th you now create views.py
from .models import post def postview(request, slug):
allpost=post.objects.all(slug=slug)
return render (request, “yourhtmlfile.html”, {‘post:allpost})
10th now create url.py file
from django.urls import path
from .models import post
from .views import postview
urlpatterns = [
path("home", views. postview name="home"),
path("home/<slug>", views. postview name="postdetails"),
]
Again do
Python manage.py makemigrations
Python manage.py migrate
Python manage.py runserver
After creating all function you can able to fetching data in your templates file.
Views.py you can create accounting to your requirement here I have giving you tips for slug fields adding only.
--Posted By : santosh
All Comments...
No comments yet !!!!