losee losee - 4 years ago 297
Python Question

Django slug throws me an error and url is not matching

I've followed the advice I was given but the slug still does not show in the url. When I try to run it I get the following error:

Page not found (404)
Request Method: GET
Request URL: http://localhost:8080/blog/1/
Raised by: blog.views.detail


I was told if I changed the values in my views from

detail(request, blog_id):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, pk=blog_id),
}


to this

detail(request, slug):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, slug=slug),
}


and changed my url to look like this

url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),


it would work but it does not. Heres my code as it is now below.

My post model in models.py looks like this

from django.db import models

class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
slug = models.SlugField()
img = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
author = models.ForeignKey(Author)
categories = models.ManyToManyField(Category)
tags = models.ManyToManyField(Tag)

def __str__(self):
return self.title

class Meta:
ordering = ["-created"]


my views.py looks like this

from django.shortcuts import render, get_object_or_404
from .models import Post

def detail(request, slug):
page = "blog/detail.html"
title = "Detail"
context = {
"post": get_object_or_404(Post, slug=slug),
"title": title,
}
return render(request, page, context)


my blog/urls.py look like this

from django.conf.urls import url
app_name = 'blog'

from . import views
urlpatterns = [
# ex: /blog/
url(r'^$', views.index, name='index'),

# ex: /blog/5/
url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),

# ex: /blog/contact
url(r'^contact$', views.contact, name='contact'),
]


my site/urls.py looks like this

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^blog/', include('blog.urls')),
url(r'^admin/', admin.site.urls),
url(r'^$', 'blog.views.land'),
]


my admin.py looks like this

from django.contrib import admin

from .models import Post, Author, Category, Tag


class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
search_fields = ['title', 'body']
list_display = ['title', 'body', 'created']
list_filter = ['created']

admin.site.register(Post, PostAdmin)


any and all help guidance advice or tutorial is invited and welcomed. Thanks

Answer Source

the regex is this

(?P<slug>[\w-]+)

when it should be this

(?P<slug>[\w\-]+)

thanks to all that tried to help. I'm glad I didn't give up. This made my new years!!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download