ijj
ijj

Reputation: 321

Django 1.6 No Category matches the given query

I am newbie in django .. and i dont understand what is reason this 404 error

I have Page not found (404) when i try go to link No Category matches the given query.

code:

models.py:

   ....
    def get_absolute_url(self):
        return ('article_url', None, { 'slug': self.slug })

   ....
      def get_absolute_url(self):
        return ('category_url', None, { 'slug': self.slug })

views.py:

def main(request):
    return render_to_response('main.html',
    {'categories': Category.objects.all(),
    'articles': Article.objects.all()[:4]})

def article_view(request, slug):
    return render_to_response('article_view.html',
    {'article': get_object_or_404(Article, slug=slug)})


def category_view(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response ('category_view.html',
    {'category': category, 'articles': Article.objects.filter(category=category)
    [:4]})

urls.py

urlpatterns = patterns('',
url(r'^$', 'main.views.main'),
url(r'^(?P<slug>[^\.]+)/$', 'main.views.category_view', name='category_url'),
url(r'^(?P<slug>[^\.]+)/$', 'main.views.article_view', name='article_url'),
)

Upvotes: 0

Views: 3442

Answers (2)

AnonymousUser
AnonymousUser

Reputation: 786

I was following a YouTube tutorial, but I did some different style with my code

I got this error because I included my cart.urls in the projects url at the bottom

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    
    path('', include('app.urls')),
    path('', include('store.urls')), 
    path('', include('cart.urls')),
    
]

When I changed it to the top or the middle

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    
    path('', include('app.urls')),

    # changed cart url to middle
    path('', include('cart.urls')), 
    
    path('', include('store.urls')),
    
]

It worked.

I found this solution by reading https://www.reddit.com/r/django/comments/avg0zi/no_post_matches_the_given_query/

Upvotes: 0

Rohan
Rohan

Reputation: 53336

Most likely, you don't have category object with slug that you are specifying in the url. Due to this, the line

category = get_object_or_404(Category, slug=slug)

in your category_view() gives you 404 page.

Upvotes: 2

Related Questions