T
T
TheTrace2019-01-26 14:26:03
Django
TheTrace, 2019-01-26 14:26:03

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")),
]

5c4c43c44d133359155951.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Shatalov, 2019-01-26
@netpastor

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'

O
Oksana ..., 2019-01-26
@deniz1983

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 question

Ask a Question

731 491 924 answers to any question