Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looking for guidance on creating a search engine using a django web framework [closed]
Hi i would like to look for guidance on creating a search engine using a django web framework. I am not to sure how to proceed as I do not really have an experience on this. I would like to create a search engine on the website that I am building, whereby it will search from a shortlisted list of websites. -
Django - when user submits a form, tables are created, but the connection between the tables is not
i am working on a small project where a customer can go to my website and register phone numbers associated to their name. it is a connection-wise registration (where number1 <--> number2 is one connection), so only two phone numbers are ever registered per session. when viewing a particular phone number (in admins panel, for instance), i want to see the id of the user it belongs to and the id of the connection it is part of. When i view a connection the same way, i want to see who registered that particular connection, and the two phone numbers that were registered in the same session. my problem: all of the foreign keys give a "django.db.utils.IntegrityError: NOT NULL constraint failed" error. I had to set null=True for all of the foreign keys for the customer's data to be submitted at all. the ManyToManyField doesn't give any bugs - but it doesn't limit each Connection to only the two phone numbers registered in the session like it should. and so, this kind of structured connection outlined above isn't made when the data is added. it's like each phone number and each connection and each user becomes its own little island, … -
Add Task doesnot working in django in ToDo List
this is task_list.html <!--if we didnt create this tasklis.html we get error becoz as said in views .py it looks for tempate we diidnt cdreated any list on template et--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List By Manasi</title> </head> <body> {% if request.user.is_authenticated %} <p>{{ request.user }}</p> <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login' %}">Login</a> {% endif %} <hr> <h2>WELCOME To My To List! </h2> <a href="{% url 'create-task' %}">Add task</a> <table bgcolor="yellow" align="center" border="2px"> <tr> <th>Task Name</th><th> Task Details</th><th>Edit Task</th><th align="center">Delete Task</th> </tr> {% for task in tasks %} <!--for task in object_list %}this is when we havent created objet context list yet in view.pywhen view.py only contains model=Task--> <tr><td align="center">{{task.title}}</td><td align="center"><a href=" {% url 'task' task.id %}">View</a></td><td align="center"><a href=" {% url 'update-task' task.id %}">Edit</a></td> <td align="center"><a href=" {% url 'delete-task' task.id %}">Delete Task</a></td></tr> <!--i think this 'task' in url is context_objct_name in views.py but its false--> {% empty %} <!--this is django template format for empty condition likewise ele etc.--> <tr><td>No item</td></tr> {% endfor %} </table> </body> </html> **this is task_form.html for add task ie.create task** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create task Form</title> </head> <body> <h1>Create … -
Django style.css is not found
Error :Not Found: /{ % static 'css/style.css' % } "GET /%7B%20%%20static%20'css/style.css'%20%%20%7D HTTP/1.1" 404 2378 When i want to link my style.css to django project it throws an error. html : <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Have a Good Day</title> <link rel="stylesheet" href="{ % static 'css/style.css' % }" > </head> <body> <h1 class="ok">Great it works</h1> </body> </html> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Note : DEBUG=True Folder structure : newproject : app1: migrations static css style.css templates init.py admin.py apps.py models.py tests.py urls.py views.py It is only for development . not deployment. -
How to import python code like a interface or service like in Laravel
I have this code in python for generating statistics, how can I optimize and make as many classes as possible to import this code https://gyazo.com/6aaca72d6c27595f619f026a40ece496 My code https://gyazo.com/440f5f25f8643245479ab29ab8e079c3 My structure -
Nested query in Django ORM
i'm try to remove duplicated row with distinct or annotate then measure count of something.(mysql:8 ,django:2.2) sql select t1.cp_id, count(*) from ( SELECT user_id, product_id, cp_id, count(*) as cnt FROM A where created_at between '2021-07-12' and '2021-07-13' group by user_id, product_id, cp_id ) as t1 group by t1.cp_id my queryset A.objects.filter( created_at__gte='2021-07-12', created_at__lt='2021-07-13' ).values('cp_id', 'user_id', 'product_id').annotate(cnt=Count('cp_id')).values('cp_id').annotate(count=Count('cp_id')) this queryset sql SELECT A.cp_id, COUNT(cp_id`) AS count FROM A WHERE ( created_at >= 2021-07-11 19:30:00 AND created_at < 2021-07-12 19:30:00 AND ) GROUP BY cp_id, created_at ORDER BY created_at ASC I'm confused why Django ignores the order of my commands and executes the last query commands on the original table (not the table where the duplicate data is deleted) Thanks if you have a solution or idea to remove the rows that have the same 'cp_id', 'user_id', 'product_id' (not from the database), then count the number of cp_ids -
URL automatically changes & it gives me the error of Page not found
"127.0.0.1:8000/adminpanel/edit_gallary/29" So this is the main problem when I first edit it works properly. But when I want to edit the second time URL automatically changes & it changes this way. "127.0.0.1:8000/adminpanel/edit_gallary/edit_gallary/29" This is my views.py file: def edit_gallary(request,gallaryid): table = gallary.objects.get(id=gallaryid) gallary_form = gallaryform(instance=table) if request.method=='POST': form = gallaryform(data=request.POST, files=request.FILES, instance=table) if form.is_valid(): form.save() table=gallary.objects.all() return render(request,"gallary1.html",{'table':table}) context = {'gallary_form':gallary_form} return render(request,'edit_gallary.html',context) This is my URLS.py file: path('edit_gallary/<int:gallaryid>',views.edit_gallary,name="edit gallery"), This is my edit_gallary.html file: {% extends 'index.html' %} {% block content %} <body> <div class="main-wrapper"> <div class="app" id="app"> <header class="header"> <div class="header-block header-block-collapse d-lg-none d-xl-none"> <button class="collapse-btn" id="sidebar-collapse-btn"> <i class="fa fa-bars"></i> </button> </div> <div class="header-block header-block-nav"> <ul class="nav-profile"> <li class="profile dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> <div class="img" style="background-image: url('https://avatars3.githubusercontent.com/u/3959008?v=3&amp;s=40')"> </div> <span class="name">Admin</span> </a> <div class="dropdown-menu profile-dropdown-menu" aria-labelledby="dropdownMenu1"> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#"> <i class="fa fa-power-off icon"></i> Logout </a> </div> </li> </ul> </div> </header> <aside class="sidebar"> <div class="sidebar-container"> <div class="sidebar-header"> <div class="brand"> <div class="logo"> <span class="l l1"></span> <span class="l l2"></span> <span class="l l3"></span> <span class="l l4"></span> <span class="l l5"></span> </div> Compare school </div> </div> <nav class="menu"> <ul class="sidebar-menu metismenu" id="sidebar-menu"> <li> <a href="insert_school"> <i class="fa fa-home"></i>Back</a> </li> </ul> </nav> </div> </aside> <div class="sidebar-overlay" id="sidebar-overlay"></div> <div class="sidebar-mobile-menu-handle" … -
How to sync a large CSV file with Django model
I want to process item report every hour for multiple accounts in my system. There are around 150k+ records in each csv. I want to sync report with database in the following way. Create record if it does not exists Update if it is present I want to do this in bulk (in one database query) Currently I am doing get or create for each record. I am using Postgres=13.2, Django=3.2.5 and python=3.9 -
Passing a URL into render_as_string
Is there a way to pass a URL instead of a template name in render_as_string. If not what can we use? # something like this def my_view_(request): if request.POST.get == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: return JsonResponse(data={ 'string_template': render_as_string('a url here'), # or we have something other than render_as_string which takes URLS }) -
If a queryset value is in a list
I'm new to python but am surprised I can't find another post with a similar question to mine. I'm trying to find a way to compare whether a queryset value is inside a list. Take this as an example: account_roles = <QuerySet [<Group: admin>, <Group: customer>]> allowed_roles = ['admin', 'customer', 'supplier', 'observer'] if account_roles in allowed_roles: print('Authorised') Essentially a user has account_roles and I only want to print 'authorised' if a user with an admin or customer role is present. I can only get a comparison working for a single value, but an the entire list of values. Example working for a single value only: if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_fn(request, *args, **kwargs) Can someone show me how this is done? -
Activation of virtual environment for python in PowerShell the parenthesis not showing does it matter when shell confirms env is on?
My PowerShell virtual environment activates the virtual environment for my Django project but does not show the parenthesis does it really matter. C:\Users\xxx\.virtualenvs\mb-g7VMb0x7 already activated. I cannot use Scripts\activate as I installed my virtualenv using pipenv not virtualenv -p python . which normal carry the scripts folder. On my Vscode the parenthesis shows that I am in a virtual environment (mb) PS E:\Dev\mb. -
How to make redirecting to services in Django / Vue / Nuxt / nginx docker-compose app work?
I'm building Django / Vue / Nuxt (not yet included) app; I would like Django to run after calling localhost/backend/, and Vue after calling localhost/panel/. So far I've managed to create docker-compose.yml shown below: version: "3" services: web: build: context: ./web restart: always volumes: - static_volume:/usr/local/src/app/static - media_volume:/usr/local/src/app/media ports: - 1300:80 depends_on: - backend - panel backend: build: context: ./izba-backend dockerfile: Dockerfile.prod args: GIT_USER_NAME: ${GIT_USER_NAME} GIT_USER_EMAIL: ${GIT_USER_EMAIL} command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 environment: DB_HOST: db DB_PORT: 3306 SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} ALLOWED_HOSTS: ${ALLOWED_HOSTS} ports: - 8000:8000 depends_on: - db volumes: - static_volume:/usr/local/src/app/static - media_volume:/usr/local/src/app/media db: image: mariadb restart: always environment: MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} MYSQL_DATABASE: ${MYSQL_DATABASE} panel: build: context: ./izba-panel ports: - 8080:8080 volumes: static_volume: media_volume: and set of nginx's .conf files for backend and panel services: backend.conf upstream backendapp { server backend:8000; } server { listen 80; location /backend/ { proxy_pass http://backendapp/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /static/ { alias /usr/local/src/app/static/; } location /media/ { alias /usr/local/src/app/static/; } } panel.conf upstream panelapp { server panel:8080; } server { listen 80; location /panel/ { proxy_pass http://panelapp/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } } Unfortunately, the presented configuration does not work - it works only … -
Django Allauth and Salesforce: No_Oauth_State: State was not valid
I am having trouble setting up Salesforce as an auth provider for my Django application using Django Allauth, getting "No_Oauth_State: State was not valid" whenever I try to log in. What I've done: I made a connected app in Salesforce as documented here: https://trailhead.salesforce.com/en/content/learn/projects/build-a-connected-app-for-api-integration/create-a-connected-app I followed the steps outlined in the Salesforce documentation (https://help.salesforce.com/articleView?id=sf.sso_provider_sfdc.htm&type=5) to setup Salesforce as an auth provider. I pasted the consumer key and secret from my connected app into the auth provider settings and copied the callback uri (https://{my_sf_domain}/services/authcallback/salesforce) from my auth provider into the callback uri field of the connected app, as stated in the docs. I configured Salesforce as a provider in my django application as stated in the Allauth docs (https://django-allauth.readthedocs.io/en/latest/providers.html#salesforce) What happens when I try to log in: My application returns a 302 with the Location header set to: https://my.sf.domain/services/authcallback/salesforce/services/oauth2/authorize?client_id={super_secret}&redirect_uri=http://my.django.app.domain/accounts/salesforce/login/callback/&scope=id+openid&response_type=code&state={a_random_string_of_length_12} Salesforce returns a 302 at the uri the above Location header refers to, now with the Location header set to: https://my.sf.domain/_nc_external/identity/sso/ui/AuthorizationError?ErrorCode=No_Oauth_State&ErrorDescription=State+was+not+valid&ProviderId={auth_provider_id} I am unsure how to debug this. Why is the state not valid? Does Salesforce expect the state parameter to be of a certain format? -
Django overriding a formfield with a queryset gives KEY ERROR
I am creating a chained dropdown list, Where selection-options of dropdown field B is based on value of field A. It works fine on Create, But when updating, it gives me a key error even though I am overriding the field to display the Selections based on the current instance of the form. I am able to print out the query set in console but when passed into the form gives a Key error. Searched for a very long time. Any help would be appreciated. Thanks!! Models.py class ReadingArea(models.Model): ReadingAreaNo = models.IntegerField() ReadingAreaNM = models.CharField(max_length=20) def __str__(self): return self.ReadingAreaNM class StoreMaster(models.Model): StoreNO = models.IntegerField() ReadingAreaNo = models.ForeignKey(ReadingArea, on_delete=models.CASCADE) class Meta: unique_together = ['StoreNO','ReadingAreaNo'] def __str__(self): return str(self.StoreNo) class MeterMaster(models.Model): MeterID = models.IntegerField(unique=True) ReadingAreaNo = models.ForeignKey(ReadingArea, on_delete=models.CASCADE) StoreNO = models.ForeignKey(StoreMaster,on_delete=models.CASCADE) def __str__(self): return str(self.MeterID) Forms.py from structure.models import MeterMaster,ReadingArea, StoreMaster class MeterMasterForm(ModelForm): class Meta: model = MeterMaster fields = ['MeterID','ReadingAreaNo','StoreNO'] def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['StoreNO'].queryset = ReadingArea.objects.none() if 'ReadingAreaNo' in self.data: try: ReadingAreaNo_id = int(self.data.get('ReadingAreaNo')) self.fields['StoreNO'].queryset = StoreMaster.objects.filter(ReadingAreaNo_id=ReadingAreaNo_id).order_by('StoreNo') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: print('The queryset in console' , StoreMaster.objects.filter(ReadingAreaNo__ReadingAreaNo = self.instance.ReadingAreaNo.ReadingAreaNo)) self.fields['StoreNo'].queryset = StoreMaster.objects.filter(ReadingAreaNo__ReadingAreaNo = self.instance.ReadingAreaNo.ReadingAreaNo) … -
Django Field 'id' expected a number but got 'test'
I try to make login. When user enter its username and password inputs. Django should match the datas from database if it exists or not but when I write HosLocUser = Hospital_Local_User.objects.filter(email=username, password=passwo) It gives this error Field 'id' expected a number but got 'test'. My codes here def login(request): if request.method == 'POST': username = request.POST.get("email") passwo = request.POST.get("password") try: HosLocUser = Hospital_Local_User.objects.filter(email=username, password=passwo) except ValidationError as e: return HttpResponse(e) if not HosLocUser: return HttpResponse("User is not found") else: output = {"jwt": generateJWT.jwt_creator(60, username, passwo)} return JsonResponse(output) return render(request, 'Login.html') Related model class Hospital_Local_User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(max_length=45) password = models.CharField(max_length=45) phone = models.CharField(max_length=45) def __str__(self): return f'Id = {self.id}, name = {self.email}' -
I am unable to import views in my app's urls.py file
I added the necessary stuffs for the work. Edited settings.py and added my app in the INSTALLED APPS, included the include function in urls.py of the base, typed a def in views.py file even. All that is bugging is the app urls.py. I did worked on django multiple time, but still can't figure out. Help me out, please! Grateful Settings.py INSTALLED_APPS = [ 'first', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] view.py from django.shortcuts import render, redirect, HttpResponse def home(request): return HttpResponse("YES") Base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('first.urls')), ] App url.py from django.urls import path from first import views #problem here urlpatterns = [ path('', views.home), #and problem here ] File-tree ├───banner │ │ db.sqlite3 │ │ manage.py │ │ │ ├───banner │ │ │ asgi.py │ │ │ procfile │ │ │ requirements.txt │ │ │ settings.py │ │ │ urls.py │ │ │ wsgi.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ settings.cpython-39.pyc │ │ urls.cpython-39.pyc │ │ wsgi.cpython-39.pyc │ │ __init__.cpython-39.pyc │ │ │ └───first │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ … -
Systemd: Messages are logged at the end of script execution
I have Django site that have custom management command that sync data from one system to database every 5 min. In the script for the command there is serveral log messages. When I manually execute the command, everything is working fine and each log message is outputed to stdout/stderr at the time as it should be. No problem here. For running the command every 5min, I setup systemd service and timer and it is working as it should be with one minor thing. All messsages from the script are logged in systemd at the time when the script execution ended, not at the time when they happened. The script is usually running about one minute and log message is outputed sporadically as each subtask in the script has ended. In my case, systemd logged all messages as if they happend at the same time, more precisely at the end of execution. So, log is looking something like this and pay attention on timestamp of messages. Jul 16 09:20:01 SmallServer systemd[1]: Started DjngoSite Sync daemon. Jul 16 09:20:40 SmallServer python[21265]: Task 1 completed Jul 16 09:20:40 SmallServer python[21265]: Task 2 completed Jul 16 09:20:40 SmallServer python[21265]: Task 3 completed Jul 16 … -
the procution rq schedule job exmple
you should use django command to run schedule job https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/ enter image description here then run python manage.py rq_crontab_job then run python manage.py rqscheduler --queue crontab_job them run python manage.py rqworker crontab_job i think the first answer is greate,but in multi-Progress enviroment may have some probelm,you should only run once to pub job in queue! -
How to connect django with cosmos db using SQL API?
I want to connect Django with Azure Cosmos DB. Either with Core SQL. Do we have any existing libraries we can use to achieve it? -
How to save a file using django's File object
I am using Celery to strip the audio from an uploaded video file. I want to save the audio file into my model where the video file is. So this is what I am trying: # model class Video(models.Model): file = models.FileField( validators=[ FileExtensionValidator( allowed_extensions=["mp4", "mov", "flv", "mkv", "avi"] ) ] ) processed_file = models.FileField( validators=[FileExtensionValidator(allowed_extensions=["flac"])], null=True, blank=True, ) # celery task output_audio_file = str(settings.MEDIA_ROOT) + "/" + str(video_obj.pk) + ".flac" ffmpeg.input(video_obj.file.path).output( output_audio_file, **{ "ac": 1, "ar": 16000, "format": "flac", }, ).run() dj_file = File(open(output_audio_file)) video_obj.processed_file = dj_file video_obj.save() This raises the Detected path traversal attempt in '/app/proj/media/49.flac' exception. I also tried with the context manager, with the video_obj.processed_file.save() method. All of which raise TypeError, AttributeError, UnicodeDecodeError and so on. I feel like the answer could be so simple but I just couldn't find it. -
Module 'rest_framework.request' has no attribute 'method' Django error
I'm having a strange error and I didn't find answers nowhere and that's mean that I need your help(again). So, I'm having two views in my views.py file and I'm trying to adding GET and POST methods for one view, I've tried to check the method with request. Method but rest frame work module tells me that has no that attribute, can you help me, please, with a fix for this issue? Thank you! In models.py I have: class ChatViewSet(ConversationViewSet): @api_view(['GET', 'POST']) def get_chat(self, **kwargs): if request.method == 'GET': information = Chat.objects.all() tutorials_serializer = ChatSerializer(information, many=True).data return JsonResponse(tutorials_serializer, safe=False) elif request.method == 'POST': tutorial_data = JSONParser().parse(request) tutorial_serializer = ChatSerializer(data=tutorial_data) tutorial_data['status'] = 'new' tutorial_data['chat_id'] += 1 if tutorial_serializer.is_valid(): tutorial_serializer.save() return JsonResponse(tutorial_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(tutorial_serializer.errors, status=status.HTTP_400_BAD_REQUEST) In urls.py: urlpatterns = [ url(r'^conversation/', ConversationViewSet.get_all), url(r'^conversation/(?P<pk>[0-9]+)$', ConversationViewSet.get_by_id), url(r'chat', ChatViewSet.get_chat), ] And error: if request.method == 'GET': AttributeError: module 'rest_framework.request' has no attribute 'method' -
How to disable password requirement for the Django admin app?
I'd like to disable the password requirement for the Django admin app. Is that possible and if so how? -
How can I filter the field so that when I select a category, only those products that belong to this category are displayed?
My models, category and product. Each product has a category field, which is linked through ForeignKey. class Category(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() image = models.ImageField(upload_to='category', blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return self.name And views, a product category can be selected and when I click on a category, I want the product to appear only in that category class CategoriesList(LoginRequiredMixin, ListView): login_url = 'login/' template_name = 'index.html' model = Category class ProductsList(ListView): template_name = 'products.html' model = Product def get_queryset(self): return super().get_queryset().filter(category=category_id) -
How to serve Images with Heroku and Django
After deoploying to heroku it was initially working fine, but would disappear (I'm assuming because of the unmounting thing) So some googling and I changed DEBUG = False and also added ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'HEROKU LINK'] but that didn't fix the problems and now my images are not even being shown after upload I've looked at a few solutions but nothing that really explains (or particularly works), it shows my image location as HEROKU-LINK/media/photos/2021/07/16/dev.jpeg Using Heroku for Django Media Files My static files are fine, they don't disappear only my images. I have the heroku postgres addon as a database, do I need to add something like CLoudinary or AWS S3? Or is there a way to get it working normally with Heroku (and not adding more cost to my side project blog) my settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my model class BlogPost(models.Model): title = models.CharField(max_length=100, default='Title') slug = models.SlugField() category = models.CharField(max_length=55, choices=Categories.choices, default=Categories.RANDOM) thumbnail = models.ImageField(upload_to='photos/%Y/%m/%d/') excerpt = models.CharField(max_length=150) month = models.CharField(max_length=9) day = models.CharField(max_length=2) year =models.CharField(max_length=4, default='2021') content = models.TextField() featured = models.BooleanField(default=False) hide = models.BooleanField(default=False) date_created = models.DateTimeField(default=datetime.now, blank=True) -
Adding a maximum limit to the number of post using python
I need to limit the number of post in Django queries. I have tried to add a min and max but nothing seemed to have worked. view.py: class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id']