Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name
I am trying to create a url-shohrtener and it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('shorturl.urls')), ] here is my apps urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:id>/', views.redirect_url, name='redirect'), ] these are the views.py: from django.shortcuts import render, redirect from .models import Url import random import string def redirect_url(request, id): urls = Url.objects.filter(short=id) link = "" for i in urls: link = i.url return redirect(link) def index(request): if request.method == "POST": link = request.POST.get("link") short = "" if Url.objects.filter(url=link).exists(): urls = Url.objects.all() for i in urls: if i.url == link: short = i.short break else: short = get_short_code() url = Url(url=link, short=short) url.save() new_url = request.get_host() + "/" + short return render(request, 'shorturl/index.html', {"new_url":new_url}) return render(request, 'shorturl/index.html') def get_short_code(): length = 6 char = string.ascii_uppercase + string.digits + string.ascii_lowercase while True: short_id = ''.join(random.choice(char) for x in range(length)) if Url.objects.filter(short=short_id).exists(): continue else: return short_id just in case it is important this is the template: <!doctype html> <html lang="en"> <head> <!-- Required … -
Filter Django queryset using dropdown box and ajax
I have the following view and template. I would like to filter (current_state is the variable I'm using) the query set using the dropdown list and jquery or ajax to reload the data on the page. Views.py def dashboard(request): records = Employee.objects.filter(owner_id__profile__state=current_state) #my queryset return render(request, "dashboard.html", {"records" : records}) Template.html <form method="POST"> <select name="stateddl" id="stateddl"> <option value="AL" selected>Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> ... </select> </form> ... <table> <thead> <tr> <th>Name</th> <th>State</th> <th>Phone</th> </tr> </thead> <tbody> {% for r in records %} <tr> <td>{{ r.name }}</td> <td>{{ r.state }}</td> <td>{{ r.phone }}</td> </tr> {% endfor %} </tbody> </table> -
ImportError: cannot import name 'employees' from 'rest_framework'
from rest_framework import employees ImportError: cannot import name 'employees' from 'rest_framework' (C:\Users\SONY\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework_init_.py) how to solve this error? -
Can I put custom settings in Django's settings.py
I have several custom settings I'd like to define in my Django app. Up to this point, I've put them in a constants.py file in each individual app. myapp/constants.py HOURS_PER_EVENT = 4 MAX_MEMBERS_PER_EVENTS = 150 MAX_EVENTS_PER_YEAR = 10 ... It just occurred to me I may be able to put these in settings.py and after a quick test everything seems to work fine. Is this allowed or is settings.py reserved for core django settings defined here? If it's not allowed, is there a better place to put these. -
Is there a way to create an endpoint (and subsequently view) for a choice field in a Django backend?
In my Django models.py file, I have a variable ColourChoices = ((0, "GREEN"), (1, "YELLOW"), (2, "RED"), (3, "GREY")) where in the same file, ColourChoices is used in class class Rainbow(models.Model): colour = models.IntegerField(choices=ColourChoices) I was wondering if there is a viable way to create a view for ColourChoices (i.e. some JSON endpoint), such that you can get all the existing values for it (GREEN, YELLOW, RED, GREY) without creating a new table in the underlying database and adding those values to it? That is, in such a way that if I were to add a new colour (e.g. BLUE), or remove one colour from the choices, that doing it once in the code would do the trick (i.e. change what you see in the view). -
what is the most optimal way of using location in django
If I am trying to create a location based recommender system in Django and where to start, Thanks in advance for answering this silly question -
django: prefetch with only() is causing many queries
If i am using only() in prefetch then its causing lot of sql queries queryset = SymbolList.objects.prefetch_related( Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in= [1,....,200]).only('close','volume').order_by('datetime') ) for symbolObject in querset: querysetDaily = symbolObject.stock_dailypricehistory_symbol.all() for daily in querysetDaily: print(daily.volume,daily.close) this is causing sql query which is accpeted SELECT `daily_price_history`.`id`, `daily_price_history`.`volume`, `daily_price_history`.`close` FROM `daily_price_history` WHERE (`daily_price_history`.`id` IN (SELECT U0.`id` FROM `daily_price_history` U0 WHERE (U0.`datetime` >= 1604718922708 AND U0.`symbolId_id` = `daily_price_history`.`symbolId_id`)) AND `daily_price_history`.`symbolId_id` IN (1, 2, .. .. 200)) ORDER BY `daily_price_history`.`datetime` ASC but also many queries like which is not supposed to SELECT `daily_price_history`.`id`, `daily_price_history`.`symbolId_id` FROM `daily_price_history` WHERE `daily_price_history`.`id` = 11346597 LIMIT 21 I found the traceback causing the above sql to: File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1710, in prefetch_related_objects obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1823, in prefetch_one_level prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level))) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 637, in get_prefetch_queryset instance = instances_dict[rel_obj_attr(rel_obj)] File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 647, in get_local_related_value return self.get_instance_value_for_fields(instance, self.local_related_fields) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 667, in get_instance_value_for_fields ret.append(getattr(instance, field.attname)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\base.py", line 635, in refresh_from_db db_instance = db_instance_qs.get() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 53, in __iter__ … -
How to make a Python html implementation of Battleship(Flask or Django)?
Would it be easier for the program to get inputs from the terminal or from somewhere else? Why do you need flask/django and which one would be better? -
Exception Value: No module named 'PIL' - in Django
Django Version: 3.1.6 Python Version: 3.6.9 I'm trying to use the ImageField in my django admin page to upload an image. When I try to upload it from my NGinx/Gunicorn server I get this error. However when I run it from port 8000 using manage.py runserver 0:8000 from the SAME server, it works. I don't understand this error. I have Pillow installed. Environment: Request Method: POST Request URL: http://54.188.59.209/admin/core/employee/add/ Django Version: 3.1.6 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, … -
Scrapyd + Django in Docker: HTTPConnectionPool (host = '0.0.0.0', port = 6800) error
I am a young Italian boy looking for help.I'm building a web interface for my web scraper using django and scrapyd. It's my first experience with scrapy but i'm learning fast thanks to the good amount of documentation on the net. However, I find myself in quite a bit of difficulty starting my spider via scrapyd_api.ScrapydAPI. Despite starting the server at the correct port (curl and browser requests both work), django returns a requests.exceptions.ConnectionError: HTTPConnectionPool (host = '0.0.0.0', port = 6800) error. First of all, here is my folder structure: scraper ├── admin.py ├── apps.py ├── dbs │ └── default.db ├── __init__.py ├── items.py ├── logs │ └── default │ └── autoscout │ ├── 0b2585dc6f2011eba4d30242ac140002.log │ ├── 1fd803a66f2011eba4d30242ac140002.log │ └── 6fac4d646f2111eba4d30242ac140002.log ├── middlewares.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20210214_2019.py │ ├── 0003_auto_search_token.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ ├── [...] │ └── __init__.cpython-38.pyc ├── models.py ├── pipelines.py ├── __pycache__ │ ├── admin.cpython-38.pyc │ ├── [...] │ └── views.cpython-38.pyc ├── serializers.py ├── settings.py ├── spiders │ ├── AutoScout.py │ ├── __init__.py │ └── __pycache__ │ ├── AutoScout.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── urls.py └── views.py and my docker compose: version: "3.9" services: django: build: . command: … -
Django video uploader is not playing videos?
I have this video uploader in django, but it is not working. Here is my model: #blog/models.py class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') And my views: #blog/views.py def display(request): videos = Videos.objects.all() context = { 'videos': videos, } return render(request, 'blog/videos.html', {'videos': videos}) My settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And my urls: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my template: <h2>{{ video.title }}</h2> <div class="embed-responsive embed-responsive-16by9"> <video class="embed-responsive-item" src="{{ video.video.url }}" controls></video><br> </div> But it is not working, it is a play button with a cross on it. So what am I doing wrong? -
Gunicorn/Nginx/Django - 500 Error is not producing error logs
I have a django site in production running NGINX/Gunicorn/Supervisor. I have an imageupload Field which fails and returns a 500 error page from Gunicorn. Although my error logs don't tell me anything. How am I supposed to debug this problem? logs: ubuntu@ip-172-31-29-176:/logs$ cat gunicorn.err.log [2021-02-15 02:12:20 +0000] [11369] [INFO] Starting gunicorn 20.0.4 [2021-02-15 02:12:20 +0000] [11369] [INFO] Listening at: unix:/home/ubuntu/gsc/app.sock (11369) [2021-02-15 02:12:20 +0000] [11369] [INFO] Using worker: sync [2021-02-15 02:12:20 +0000] [11372] [INFO] Booting worker with pid: 11372 [2021-02-15 02:12:20 +0000] [11374] [INFO] Booting worker with pid: 11374 [2021-02-15 02:12:20 +0000] [11375] [INFO] Booting worker with pid: 11375 /etc/nginx/sites-enabled/django.conf server{ listen 80; server_name ec2-54-188-59-209.us-west-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/gsc/app.sock; } location /static { alias /home/ubuntu/gsc/assets/; } location /media { alias /home/ubuntu/gsc/media/; } } /etc/supervisor/conf.d/django.conf [program:gunicorn] directory=/home/ubuntu/gsc command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/gsc/app.sock gsc.wsgi:application autostart=true autorestart=true stderr_logfile=/logs/gunicorn.err.log stdout_logfile=/logs/gunicorn.out.log -
How include Recipients to django-postman
in django postmon, when sending a message, an empty recipient field, how to auto-detect the recipient by ID, if the message is sent from the recipient's profile page? thank -
How to make the django-filter issue a request and transform it into a geoJSON?
I want to display my data from the database on a web map, in the form of a geoison. Since I'm new to development, I am lacking in knowledge. The Djnago filter displays my geoDjango coordinates from the database on HTML as: SRID = 4326; POINT (78.407707 44.998262). Is there an option for integration with Django Rest Framework, which gives data in the form of JSON? Help me please. Thank you in advance. #------------------------------------------------------------------------------------------------------ #filters.py import django_filters from .models import SubstationTable, PowerLine10Table, TransformerTable class SubstationFilter(django_filters.FilterSet): class Meta: model = SubstationTable fields = [ 'owner_substation', 'section_substation', 'substation_number', ] class PowerLine10Filter(django_filters.FilterSet): class Meta: model = PowerLine10Table fields = [ 'owner_powerline10', 'section_powerline10', 'substation', 'powerline10_number', ] class TransformerFilter(django_filters.FilterSet): class Meta: model = TransformerTable fields = [ 'owner_transformer', 'section_transformer', 'powerline10', 'transformer_number', ] #------------------------------------------------------------------------------------------------------ #views.py def web_map(request): substation_filter = SubstationFilter(request.GET, queryset=SubstationTable.objects.all()) powerline_filter = PowerLine10Filter(request.GET, queryset=PowerLine10Table.objects.all()) transformer_filter = TransformerFilter(request.GET, queryset=TransformerTable.objects.all()) context = { 'title': 'WEB_MAP', 'substation_filter': substation_filter, 'powerline_filter': powerline_filter, 'transformer_filter': transformer_filter, } return render(request, 'app_webmap/app_webmap_page.html', context)``` #------------------------------------------------------------------------------------------------------ #models.py from django.db import models from django.contrib.gis.db import models class SubstationTable(models.Model): """Substation""" owner_substation = models.ForeignKey( OwnersTable, on_delete=models.CASCADE, verbose_name='Owner:') section_substation = models.ForeignKey( SectionsTable, on_delete=models.CASCADE, verbose_name='Section:') substation_number = models.CharField(max_length=25, unique=True, verbose_name='Substation number:') substation_name = models.CharField( max_length=25, unique=True, blank=True, null=True, verbose_name='Substation name:') visibility_on_map= … -
Django stuck on default splash page in production
I just set up a deployment server with NGINX/GUNICORN. I've uploaded my project and all I see is the "welcome to django" splash page. No matter what I do, I can't get rid of this. When I run: ./manage.py runserver 0:8000 I can access my website through port 8000, and it works! I don't understand why the production server (using the same code) won't do anything. I even changed debug=False, and the splash screen still thinks I'm in debug mode. I have even deleted my pycache folder. No change. -
Django Template: Add Variable Into URL As Parameter
What's the proper way to add {{gamestoday|lookup:i}} into the <a href={%url 'stats'%}>. Do I need to make changes to urls.py? {% load tags %} <center> <div class = "scoreboardbackground"> <div class="row"> {% for i in ngames %} <div class="col"> <a href={%url 'stats'%}> <div class="livegamebox"> {{teamnames|lookup:i|lookup:0}} vs {{teamnames|lookup:i|lookup:1}} - {{gamestoday|lookup:i}} <br> <div style="font-size:12px;"> {{datetimegames|lookup:i}} </div> <br> <div style = "font-size:30px"> <b>{{latestscore|lookup:i}}</b> </div> </div> </a> -
Django: Need help returning 2 sets of data in the same view
I am trying to return 2 different sets of data in the same view. The two tables: Restaurant Foods Models class Restaurant(models.Model): PRICING = ( ("£", "£"), ("££", "££"), ("£££", "£££"), ) name = models.CharField(max_length=50) slug = models.SlugField(unique=True) description = models.TextField(null=True) price = models.CharField(max_length=10, null=True, choices=PRICING) category = models.ManyToManyField(Category) def __str__(self): return str(self.name) class Foods(models.Model): name = models.CharField(max_length=200, null=True) description = models.TextField(null=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) image = models.ImageField(null=True, blank=True, upload_to="food_images/") price = models.FloatField() def __str__(self): return self.name On this view, I'm trying to list the restaurant data as well as the food data. But how do I access the food data for that specific restaurant? Views def restaurantDetailView(request, slug): restaurant = Restaurant.objects.get(slug=slug) context = { "restaurant": restaurant, } return render(request, "restaurants/restaurant_detail.html", context) This is the HTML <div class="container restaurant-container" padding-top="40px"> <div class="card"> <div class="row no-gutters"> <div class="col-sm-5" style="background: #868e96;"> <img src="{{ restaurant.image.url }}" width="500px" class="card-img-top h-100" alt="..."> </div> <div class="col-sm-7"> <div class="card-body"> <h5 class="card-title" style="font-size:28px;">{{restaurant.name}}</h5> <hr> <p class="card-text">{{restaurant.description}}</p> <p class="card-text">{{restaurant.category.all|join:" | " }}</p> <div class="row" style="padding:10px 0px 10px;"> <div class="col">Price: {{restaurant.price}}</div> <div class="col">Location: {{ restaurant.postcode }} | {{ restaurant.city }}</div> </div> <div class="row" style="padding:10px 0px 10px;"> <div class="col">Avg Wait: {{restaurant.min_serve_time}} mins</div> <div class="col">Minimum Order: £{{restaurant.min_order_tk}}0</div> </div> </div> </div> … -
How to have Django raise ValidationError as Popup?
I am using a custom clean() function on one of my forms for a conditional field requirement. I am able to raise the validation error on my template as a part of the DOM using {{ form.non_field_errors }}. I would like to have the validation error come up as a popup like the default errors do, but do not know how. Here is the custom clean() function: class ReportForm(forms.Form): def clean(self): cleaned_data = super().clean() class_type = cleaned_data.get("class_type") class_other = cleaned_data.get("class_other") if class_type == "Other": if not class_other: msg = "Please fill out this field." raise ValidationError(msg) I don't know what to put in views or the template to have it show as a popup - I don't currently have anything special there. Is it possible with Django, or do I need to use javascript? -
Django Model @property duplicates queries
Django model properties is useful to access in run time, however this does not come without cost. Below property cause huge duplicate queries due to database hit with each query (product). @property def total_stock(self): """ SKU total stock """ total = SKU.objects.filter( product=self ).values_list("stock").aggregate(Sum(F("stock"))).get("stock__sum") or 0 return total Any thought how to use django model @property in efficient way? -
Fabric keep asking for user password, although key_filename is set
I am using fabfile for django deployment. I am connecting to my deployment servers through bastin host (using env.gateway option in fabfile, env.gateway=bastin_IP) and then running required commands. Following options are set in fabfile, added for reference. env.gateway = 'user@xx.xx.xx.1' #bastin_IP env.key_filename = ['path/to/pem/file'] env.user = 'user' env.port = 22 Now whenever I run command, it always prompt for password of user, message shown like this. [xx.xx.xx.002] Login password for 'user': Note: here IP shown before message is the IP of my deployment/prod server. What I am assuming (after seeing above message) is that connection is being made with bastin successfully, but it is not connecting with deployment/prod server. Although whenever I try to connect via putty (on windows), I can login to bastin host (using openssh private key) then from bastin to any other deployment/prod server without password. Please let me know, what is the actual issue and how to resolve that. What I am doing wrong? Any help is appreciated. -
Call Microsoft Authentication in a Custom Login Form
So I'm creating a custom login form and really would like to include the option so that users can login in via office365 account. To do this I have used the django_microsoft_auth functionality. When going to admin it is working perfectly, however really would like to know how should I use it in a custom form. I did not find any documentation how this can be done and really would like some feedback on this. So in my login there will be a button then when pressed it will redirect to Microsoft authentication site and when completed it will redirect to the homepage. What do I need to include the the href in my template? and do I need to add something in the views.py or there is no need? Thanks -
autoreload.restart_with_reloader - how to reboot with --noreload key? [django]
how to restart the server with the --noreload key and back? from django.utils import autoreload autoreload.restart_with_reloader(--noreload) #for example #some code autoreload.restart_with_reloader() can i restart the server with the --noreload key? and then back with no key? if manually, but it is necessary in the code dynamically python manage.py runserver ctrl+c python manage.py runserver --noreload ctrl+c python manage.py runserver -
Get a string variable from views to urls in Django
I am a beginner at python and especially Django, I am trying to solve a problem where when a user searches, if that search is valid, i want to get that search = var_X, in my URL like: "www.website.com/search/var_X" or something like, "www.website.com/search/<df.item>" -Views.py- def views_search(request): temp_dict = {} if request.method == 'POST': var_X = request.POST['var_X'] try: df = wsc.Summary(temp_dict, var_X) except Exception as e: df = "ERROR" return render(request,'search.html', {'df' : df}) else: return render(request,'home.html', {'var_X' : "Not Found"}) -- Urls -- from django.urls import path from . import views from requests import * urlpatterns = [ path('search/<var_X>', views.views_search, name="url-search"), ] -- HTML -- <form action="{% url 'url-search' var_X %}"class="d-flex" method="POST"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Enter String" aria-label="Search" name="var_X"> <button class="btn btn-outline-secondary" type="submit">Search</button> </form> -
Convertir lista a formato fecha en Django [closed]
estoy intentando convertir esta lista: `[datetime.date(2021, 1, 19), datetime.date(2021, 1, 20), datetime.date(2021, 1, 22)]` a un formato date() que se mire de la siguiente manera: [2021-01-19,2021-01-20, 2021-01-22...] estoy usando Django y no encuentro la manera de hacerlo convertir la lista a un formato date. -
django not picking up migration where managed = False
I have a simple web-app I'm trying to create to visualise some carbon data (to teach myself Django!) As my data model is a little complex I use the managed=False and import a view from my postgres database where I wrangle my data. When I first ran the migration I noticed I left in a field that I didn't have in my view, so naturally I changed it. Now when I run makemigrations for my app called carbon it says there are no changes. What is the correct way to remedy this? additionally, for some reason when I try to run an orm query to pull in some data it expected me to have an id field in my view, can someone explain this, if possible? models.py class CarbonViewHour(models.Model): daily_hour = models.CharField(max_length=50) reading = models.FloatField() #date = models.DateField() This was removed class Meta: managed = False db_table = 'carbon_v_hourly_meter_readings' def __str__(self) -> str: return f"{self.meter}-{self.reading}-{self.date}-{self.daily_time}" the change I made was to remove a field from CarbonTimeView date = models.DateField() views.py class CarbonTimeView(TemplateView): template_name = 'carbon/chart.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qsm'] = CarbonViewMinute.objects.all().order_by('date') context['qsh'] = CarbonViewHour.objects.all() context['title'] = 'Daily Carbon Data' return context SQL View. DROP VIEW IF EXISTS …