I can't see any slug field generated in admin page

i can’t generate slug to my post model


class Post(models.Model):
    id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True, editable=False) # add unique=True in slug (never repeat)
    title = models.CharField(max_length=200, db_index=True, blank=False, default='')
    snippet = models.OneToOneField(Snippet, on_delete=models.CASCADE, related_name='post_snippets', blank=True, null=True)
    creator = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="post_creator")
    def get_absolute_url(self):
        """Returns the url to access a particular post instance."""
        return reverse('details', kwargs={ "id": str(self.id), "slug": self.slug})
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        img = Image.open(self.post_img.path)
        return super(Post, self).save(*args, **kwargs)

my form

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ('creator', 'snippet')

class SnippetForm(forms.ModelForm):
    class Meta:
        model = Snippet
        fields = '__all__'

my view

def add_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST, request.FILES)
        snippet_form = SnippetForm(request.POST)
        if post_form.is_valid() and snippet_form.is_valid():
            post = post_form.save(commit=False)
            snpt = snippet_form.save()
            post.creator = request.user
            post.snippet = snpt
            return redirect('blog:index')
        post_form = PostForm()
        snippet_form = SnippetForm()
    return render(request, 'blog/add_post.html', {'post': post_form, 'snpt': snippet_form})

what’s wrong in this logic that cause slug to not be generated
i have tried in admin.py
prepopulated_fields = {'slug': ('title',)}
but it gives
"KeyError at /admin/post/add/ "Key ‘slug’ not found in ‘PostForm’. Choices are: other fields

i really confused on what to do for it to be exist in admin page
I removed the save method from my model and let only the perpetuated line or vice versa but same thing. Do and add some logic in views functions???

You’ve defined editable=False in the field definition.

i don’t know what to say and also don’t know how to thank you for continuing to help me
but stay with me in this journey please to make this site real bro
i got this error now

Reverse for ‘details’ not found. ‘details’ is not a valid view function or pattern name

because of my get_absolute_url method above
here is the line in index.html template that causing this

<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>

here is he view

def post_details(request, slug, uuid): 
    template_name = 'post_details.html'
    post = get_object_or_404(Post, slug=slug, id=uuid) 
    comments = post.comments.filter(active=True) 
    post.views += 1
    if request.method == 'POST':
        comments= Comment.objects.filter(post=post, parent=None) 
        replies= Comment.objects.filter(post=post).exclude(parent=None) 
        for reply in replies:
            if reply.parent.id not in replyDict.keys():
        form = CommentForm(request.POST or None, request.FILES)
        if form.is_valid():
            add = form.save(commit=False)
            add.post = post 
            return HttpResponseRedirect('/posts/')
        form = CommentForm()
    context = {'post': post, 'comments': comments, 'new_comment': add, 'form': form, 'user': request.user, 'replyDict': replyDict}
    return render(request, template_name, context)

and the url

path('posts/<str:slug>/<int:pk>/', post_details, name='details'),

and the get_absolute_url as above

    def get_absolute_url(self):
        return reverse('details', kwargs={ "id": str(self.id), "slug": self.slug})

how can i solve this problem
i don’t know what’s next too but please brother @KenWhitesell help me

Any Help please? Bro @KenWhitesell are you here?

Start with looking at the error message - what is this telling you?

this is the pattern name i have named in my url so it’s valid as i think, i think there is something else is causing this, if you don’t have an idea what is it, i will try to rethink and look again on this return reverse

i thought that you will find it just by naked eye as you are an expert without having to search on stack or take some time but i have to do some search and think again, anyway thanks bro

What is your complete urls.py file containing this entry?

i just provide the url that is responsible for this view but here is the urls file

    path('', index, name='index'), 
    path('posts/', post_list, name='posts'),
    path('posts/<str:slug>/<int:pk>/', post_details, name='details'),     # this is the one that cause error
    path('posts/<int:pk>/<str:slug>/', PostDetailView.as_view(), name='post_details'),

That is not the complete file.

from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import path, include, re_path
from rest_framework.routers import DefaultRouter
from .import api
from .views import (index, likePost, post_list, post_details, PostDetailView, add_post, PostCreateView, PostUpdateView, PostDeleteView,
PostedByUserListView, renew_post_admin, RenewedAllListView, MaintainerListView, MaintainerDetailView, MaintainerCreate,
MaintainerUpdate, MaintainerDelete )
<a href="{% url 'url_name_in_urlpatterns' argument_needed %}"> {{ context_var_name.field_name }}</a>
<li><a href="{% url 'posts:details' post.id %}">{{ post.title }}</a></li>  
# application namespace to use in {% url blog:details post.id %} because there are so many apps in the site that has same name details
app_name='blog' # To let Django knows which app view to create for a url when using the {% url %} template tag
# Create a router and register our API viewsets with it.
router = DefaultRouter()
# Registering the viewsets with the router is similar to providing a urlpattern
# We include two arguments - the URL prefix for the views, and the viewset itself
# The DefaultRouter class we're using also automatically creates the API root view for us,
# so we can now delete the api_root method from our views module, don't forget to do so.
# The API URLs are now determined automatically by the router.
router.register(r'posts', api.PostViewSet) # api views blog/api/posts
router.register(r'snippets', api.SnippetViewSet) # api views
#router.register(r'users', api.UserViewSet) # will conflict with the same users of job urls.py
# The Normal views routing.
urlpatterns = [ # you can use the URL name to map the link in template <a href="{% url 'name' %}">URLText</a>
    path('api', include(router.urls)), # OR re_path(r'^', include(router.urls)) => this only for api routing using default router
    #path('', views.IndexView.as_view(), name='home'),
    path('', index, name='index'), # <a href="/blog/">Home</a>  blog/
    path('posts/', post_list, name='posts'), # for normal function based views
    #path('posts/', views.PostListView.as_view(), name='post_list'), # <a href="/blog/posts/">Home</a>  use name better blog/posts
    path('posts/<str:slug>/<int:pk>/', post_details, name='details'),     #
    path('posts/<int:pk>/<str:slug>/', PostDetailView.as_view(), name='post_details'),
    #path('posts/<int:pk>', PostDetailView.as_view(), name='post-detail'), # <a href="{% url 'post-detail' %}">URLText</a> or
    #re_path(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post-details'), # re_path == regular exp path
    #path('posts/<int:pk>/highlight/', api.PostHighlight.as_view()),
    path('posts/add/', add_post, name='add'),  #
    path('posts/create/', PostCreateView.as_view(), name='create'),
    path('posts/like/', likePost, name='likepost'),
    #path('posts/<int:pk>/update/', views.PostUpdate.as_view(), name='post-update'),
    path('posts/<int:pk>/update/', PostUpdateView.as_view(), name='post_update'),
    #path('posts/<int:pk>/delete/', views.PostDelete.as_view(), name='post-delete'),
    path('posts/<int:pk>/delete/', PostDeleteView.as_view(), name='post_delete'),
    path('posts/myposts/', PostedByUserListView.as_view(), name='my-posts'),    
    # Add URLConf for admin to renew a post. /blog/post/<postinstance_id>/renew/1
    path('posts/<uuid:pk>/renew/', renew_post_admin, name='renew-post-admin'),
    path(r'renewed/', RenewedAllListView.as_view(), name='all-renewed'),
    #path('posts/snippets/', SnippetListView.as_view(), name='snippet-list'),
    #path('posts/snippets/create', SnippetAdd, name='snippet-create'),
    #path('posts/snippets/<int:pk>', SnippetDetailView.as_view(), name='snippet-details'),
    # The pattern only matches if pk is a correctly formatted uuid
    path('maintainers/', MaintainerListView.as_view(), name='maintainers'), # <a href="{% url 'maintainers' %}">URLText</a>
    path('maintainer/<int:pk>', MaintainerDetailView.as_view(), name='maintainer-detail'),# <a href="{% url 'auth-det' %}">URLText</a>
    path('maintainer/create/', MaintainerCreate.as_view(), name='maintainer-create'),
    path('maintainer/<int:pk>/update/', MaintainerUpdate.as_view(), name='maintainer-update'),
    path('maintainer/<int:pk>/delete/', MaintainerDelete.as_view(), name='maintainer-delete'),

This is what’s missing in your call to reverse:

This app_name creates a “namespace” for your urls. You need to prefix the url name references with this app_name, similar to what you have here:

(But with blog instead of posts)

i don’t know why i am always doing complicated work and when it comes to simple steps i miss them always this is so so logic, but this is when i have an expert like you, always you save me i don’t know really what to say i feel like i awe a special gratful thanks and greetings for you

It’s what I refer to as the “eye for details” - it’s something you work on, develop, and enhance as you gain experience.

1 Like

right bro and a lot of thanks and greetings for you