Search code examples
djangohttp-status-code-404url-routing

URL configuration and 404 error


I'm working on a personal Django project and I have 404 error, but I can't figure out why.

I tried the following configuration: Urls.py

url(r'composer/(?P<slug>.+)$', views.articles_plats_composer, name='articles_plats_composer'),

My views:

def articles_plats_composer(request, slug):
sous_categories_articles = get_object_or_404(Sous_Categories_Article, slug=slug)
articles = sous_categories_articles.article_set.all()
return render(request, "commander-suite-composer.html",{'sous_categories_articles':sous_categories_articles, 'articles':articles})

And my templates:

<a href="{% url 'articles_plats_composer' article.slug %}"></a>

With this configuration it works. When i tried with only an id, it works (same kind of code).

But when, I try to have a slug and id url with the following code, I get 404 error.

My URLs file

url(r'composer/(?P<slug>.+)-(?P<id>\d+)$', views.articles_plats_composer, name='articles_plats_composer'),

My views:

def articles_plats_composer(request, slug, id):
sous_categories_articles = get_object_or_404(Sous_Categories_Article, slug=slug, id=id)
articles = sous_categories_articles.article_set.all()
return render(request, "commander-suite-composer.html",{'sous_categories_articles':sous_categories_articles, 'articles':articles})

And my templates:

<a href="{% url 'articles_plats_composer' article.slug article.id %}"></a>

I don't understand why, separately, it works, but when i combine them, it doesn't work...

Thank you in advance for your help

Singertwist


Solution

  • So, I found the answer.

    def articles_plats_composer(request, id, slug):
    sous_categories_articles = get_object_or_404(Sous_Categories_Article, id=id, slug=slug)
    articles = sous_categories_articles.article_set.all()
    return render(request, "commander-suite-composer.html",{'sous_categories_articles':sous_categories_articles, 'articles':articles})
    

    Thanks for your help.