Answer the question
In order to leave comments, you need to log in
How to connect class to urls in Django?
I created a news category on Django and created the Articles class in models.py, when importing Articles into urls.py everything is fine. But when I start to customize the output of the article, Articles.objects writes an error that Articles is not in the object. How to write the objects function correctly and set it up correctly. Thanks in advance!
MODELS.PY:
from django.db import models
class Articles(models.Model):
title = models.CharField(max_lenght = 120)
post = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
from django.urls import path, include
from django.views.generic import ListView, DetailView
from news.models import Articles
urlpatterns = [
path('', ListView.as_view(queryset=Articles.objects.all().order_by("-date")[:20], template_name="news/posts.html")),
]
Answer the question
In order to leave comments, you need to log in
That's right - when the flies are separate and the cutlets are separate
from django.urls import path
from news.views import NewsListView
urlpatterns = [
path('', NewsListView.as_view()),
]
from django.views.generic import ListView
from news.models import Articles
class NewsListView(ListView):
model = Articles
paginate_by = 20
ordering = 'created_date'
template_name = 'news/posts.html'
path('', ListView.as_vew(), name='post'), #this is your path, which indicates what name to look for the view under.
Then in the views.py file, import your class: from .models import Articles and write the code for the view : def post(request):
articles = Articles.objects.filter(created_date__lte=timezone.now()).order_by('created_date')# here of course your queryset, not mine ))
return TemplateResponse(request, 'news/post .html', {'articles': articles })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question