A
A
Alexander Sidnin2021-02-19 01:13:07
Django
Alexander Sidnin, 2021-02-19 01:13:07

How to display one record from the database in Django on the main page?

The manuals for the Django framework describe everywhere how to display a list of records from the database, but nowhere did I find information on how to display one specific record on the main page of the site.

I tried to figure it out myself and, based on the examples available on the network, get the necessary result, but it didn’t work out - I don’t have enough skills. So I will be grateful for advice in what direction to dig.
There is a basicapp application with the main pages of the site, it has a MainPages model:

models.py

class MainPages(models.Model):
    name = models.CharField(verbose_name="Название страницы", max_length=100)
    title = models.CharField(blank=True, max_length=100)
    description = models.CharField(blank=True, max_length=300)
    keywords = models.CharField(blank=True, max_length=300)
    h1 = models.CharField(verbose_name="Заголовок h1", blank=True, max_length=100)
    content = models.TextField(verbose_name="Контент", blank=True, max_length=5000)


views.py
class MainPagesDetailView(generic.DetailView):
    model = MainPages
    template_name = 'basicapp/index.html'
    context_oject_name = 'mainpages'


urls.py
urlpatterns = [
    path('', views.MainPagesDetailView.as_view(), name='index'),
]


When opening the main page, we get an error:
Generic detail view MainPagesDetailView must be called with either an object pk or a slug in the URLconf.

I understand that in order to display a specific record from the database, I have to tell Django which record to get, but I can’t figure out how to do this.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WStanley, 2021-02-19
@asidnin

Shake!
DetailView - displays 1 record on page, yes. But for output, she asks to pass to her the pk of this record (primary key which is usually id) or slug (you don’t have it in the table), which is what your error says - MainPagesDetailView must be called with either an object pk or a slug in the URLcon

urlpatterns = [
    path('<int:id>/', views.MainPagesDetailView.as_view(), name='index'),
    # или
    path('<slug:slug>/', views.MainPagesDetailView.as_view(), name='index'),
]

Accordingly, you will have to access the page by the key
http://my_domain/pk/ 
или
http://my_domain/slug/

Read the doc https :
//docs.djangoproject.com/en/3.1/ref/class-ba... for example TemplateView https://docs.djangoproject.com/en/3.1/ref/class-ba... in get_context_data pass any data you need to the template and refer to it in the template

D
Dr. Bacon, 2021-02-19
@bacon

override MainPagesDetailView get_object method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question