简体   繁体   中英

Django: 404 Error Appears While Trying to Use Slug in URLs

I am a beginner in Django. Right now, I am learning the framework by building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.

Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html . However, I am facing issues with the third template, which is details.html .

When I go to http://127.0.0.1:8000/index , I see this page: 在此处输入图像描述

When I click on Samsung , I see this page:

在此处输入图像描述

Up to this is fine. But when I click on any phone model, like Galaxy S10 , I get 404 error. It looks like this:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/details/galaxy-s10
Raised by:  PhoneReview.views.ReviewView
No review found matching the query

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error.

Here are my codes of models.py located inside PhoneReview folder:

from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Brand(models.Model):
    brand_name = models.CharField(max_length=100)
    origin = models.CharField(max_length=100)
    manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
    slug = models.SlugField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.brand_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.brand_name)
        super().save(*args, **kwargs)

class PhoneModel(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    model_name = models.CharField(max_length=100)
    launch_date = models.CharField(max_length=100)
    platform = models.CharField(max_length=100)
    slug = models.SlugField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.model_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.model_name)
        super().save(*args, **kwargs)

class Review(models.Model):
    phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
    review_article = models.TextField()
    date_published = models.DateField(auto_now=True)
    slug = models.SlugField(max_length=150, null=True, blank=True)
    link = models.TextField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.review_article

Here are my codes of urls.py located inside PhoneReview folder:

from . import views
from django.urls import path

app_name = 'PhoneReview'

urlpatterns = [
    path('index', views.BrandListView.as_view(), name='brandlist'),
    path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
    path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]

Here are my codes of views.py located inside PhoneReview folder:

from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review


class BrandListView(generic.ListView):
    template_name = 'PhoneReview/index.html'
    context_object_name = 'all_brands'

    def get_queryset(self):
        return Brand.objects.all()


class ModelView(generic.ListView):
    template_name = 'PhoneReview/phonemodel.html'
    context_object_name = 'all_model_name'

    def get_queryset(self):
        self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
        return PhoneModel.objects.filter(brand=self.brand)

class ReviewView(generic.DetailView):
    model = Review
    template_name = 'PhoneReview/details.html'

Here are my codes of apps.py located inside PhoneReview folder:

from django.apps import AppConfig


class PhonereviewConfig(AppConfig):
    name = 'PhoneReview'

Here are my codes of index.html located inside templates folder:

{% extends 'PhoneReview/base.html' %}

{% load static %}

{% block title%}
Brand List
{% endblock %}

{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
    <ul>
        {% for brand in all_brands %}
<!--            <li>{{ brand.brand_name }}</li>-->
            <li><a href = "{% url 'PhoneReview:modellist' brand.slug %}">{{ brand.brand_name }}</a></li>
        {% endfor %}
    </ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}

Here are my codes of phonemodel.html located inside templates folder:

{% extends 'PhoneReview/base.html' %}

{% load static %}

{% block title%}
Phone Model Page
{% endblock %}

{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
    <ul>
        {% for phonemodel in all_model_name %}
            <li><a href = "{% url 'PhoneReview:details' phonemodel.slug %}">{{ phonemodel.model_name }}</a></li>
        {% endfor %}
    </ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}

Here are my codes of details.html located inside templates folder:

{% extends 'PhoneReview/base.html' %}
{% load static %}

<html>

<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">


<html lang="en">

{% block title%}Details{% endblock %}

{% block content %}

<h1>This is the Details Page</h1>

<h2>Review:</h2>
<p>{{ review.review_article }}</p>

<h2>News Link:</h2>
<a href={{ review.link }}>{{ review.link }}</a>
{% endblock %}
</html>

Have I made any mistake in models.py or details.html ?

I don't think there is an error in the code here. open Django shell by python3 manage.py shell then run the following query

I guess this will probably give NotFound error because there is no model with slug galaxy-s10

from your_app.models import Review

samsung_s10 = Review.objects.get(slug='galaxy-s10')
print(smasung_s10.slug)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM