Почему моя страница Django не находится, хотя я создал экземпляр модели для этой страницы?

Подробности:

У меня есть приложение Django, в котором я пытаюсь создать динамическое представление, отображающее страницу с деталями для экземпляра модели на основе параметра URL. Я настроил следующее:

Код модели:

class Card(models.Model):
    background_image_id = models.CharField(max_length=100)
    border_id = models.CharField(max_length=100)
    image = models.ImageField(upload_to='cards/')
    number = models.IntegerField()
    name = models.CharField(max_length=30)
    subtitle = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    card_paragraph1 = models.TextField()
    card_paragraph2 = models.TextField()
    card_paragraph3 = models.TextField()
    card_paragraph4 = models.TextField()
    card_button_class = models.CharField(max_length=100)
    card_detail_url = models.CharField(max_length=100, blank=True, null=True)
    card_modal_class = models.CharField(max_length=100)
    card_temple_url = models.CharField(max_length=100, blank=True, null=True)
    quote = models.CharField(max_length=255)
    background_modal_image_id = models.CharField(max_length=100)
    modal_title = models.CharField(max_length=100)

View Code:

from django.shortcuts import render
from .models import Card

def card(request, name):
    try:
        # Attempt to retrieve the card with the given name
        card = Card.objects.get(name=name)
    except Card.DoesNotExist:
        # If no card is found, render the placeholder template
        return render(request, 'cards2/temples_placeholder.html')
    else:
        # If the card is found, render the card detail template

        return render(request, 'cards2/card.html', {'card': card})

URL Code:

from django.urls import path
from . import views

urlpatterns = [
    path('card/<str:name>/', views.card, name='card_detail'),
]

Выпуск:

Когда я пытаюсь получить доступ к URL-адресу типа http://127.0.0.1:8000/card/arepage/, я получаю ошибку 404, указывающую на то, что страница не может быть найдена. ("arepage" - это имя экземпляра моей модели)

Я подтвердил, что:

Экземпляр модели Card с name='arepage' существует в базе данных. Шаблон URL правильно определен, чтобы соответствовать card/str:name/. Вопросы:

Почему URL-адрес может не соответствовать представлению, хотя экземпляр модели существует? Как я могу отладить или исправить эту проблему, чтобы убедиться, что страница найдена правильно?

I checked your project and understood that you didn't provide your main urls.py in the question. Because if you didn't register your urls.py from app.py in main urls.py, in this case your url card/whatever/ is not registered and you should get 404.

I believe the name of the app folder is cards. To improve the situation, you should manually register your cards/urls.py in main urls.py:

# project_settings_folder/urls.py
# whole text, with admin etc.
...
# end of your file:

from django.urls import include

urlpatterns += [
    path('', include('cards.urls')),
]

BTW, try to read about GCBV, it is much simplier and clear than FBV. More here: https://docs.djangoproject.com/en/5.1/topics/class-based-views/

Вернуться на верх