Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : submitting Foriegn key field with or without form object to models
we can submit foriegnkey data to models through ModelForm class BooksForm(forms.ModelForm): class Meta: model = Books fields = "__all__" where in templates we can add {{form.author}} (author is foriegnkey field in books model) Im aware that we can submit foriegnkey data using forms like this but my question is.is there any way where we can submit a foriegnkey object which we have fetched using some other method (with or without form ) to a model(in my case its book) Let me explain it in detail lets say for instance there is a Search bar when users search for author, then the function fetches list of authors (choice field) to the user where user can select and submit which should get populated in the books model there isnt any proper info related to this on web all i could see is information on how to save data with Foriegnnkey using model form any kind of insights is appreciated -
Why is CSS not working even I use 'runserver' command in Docker?
I am trying to develop a web application using Django in Docker. I made a DockerFile and a docker-compose.yml file as below to check the code in the development environment. Even though I'm using the runserver command in the file, when I start the container and access the localhost, the CSS for the admin page isn't working. How should I change the codes to make it work? Here are the codes: Dockerfile FROM python:3.8.3-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml version: '3.7' services: web: build: ./django_project command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django_project/:/usr/src/app/ ports: - 8000:8000 docker desktop: 4.1.1 Python: 3.8 Django: 3.0 -
Django Custom User Model - admin customization
So, I was making a custom user model, and to be able to change the password using the admin page I did this on the UserAdminChangeForm, is it wrong? I mean dealing with the security. password = ReadOnlyPasswordHashField( label=_("Password"), help_text=_( "Raw passwords are not stored, so there is no way to see this " "user’s password, but you can change the password using " '<a href="../password">this form</a>.' ), ) -
Pass variable in to template in django
Can anyone help me to solve my Problem, I'm trying to pass a variable from my view to my Template. But the variable does not show up when I load my the site. Model: class Artikl(models.Model): name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=60) price = models.PositiveIntegerField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Views: from django.shortcuts import render from .models import Artikl def home(request): context = { 'artikl': Artikl.objects.all() } return render(request, 'base/home2.html', context) Template: {% for artikl in Artikl %} <div class="row g-4"> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="https://picsum.photos/300/200" class="mb-3 img-fluid" alt=""> <h3 class="card-title mb-3">{{ artikl.name }}</h3> <p class="card-text">{{ artikl.description }}</p> <button type="button" class="btn btn-primary">Kupi</button> </div> </div> </div> {%endfor%} -
Django - run flows
assist please with questions for beginner. Haven't managed to find someth simillar. I have some specific flow with 3 steps (scripts) are being performed on remote server via ssh. How to organize a view that will call the Flow and update its template accordingly to completting each step of the flow like: Step 1: Done Step 2: in process How can I screen ssh connection's output? Like i enter ip, command and by "Run" pressing receive realtime updated data (script's output) in template. -
Concurrent operations on django and database
I am developing on Django 3 system. I am using mysql at backend. I have a design question. I have a system of doctors and patients. The patient is registered in the system. Doctors see the patient on their page and push a button and take patient. When 3 doctors open their pages at the same time, all of them will see the patient named Jennifer. Well, if they press the get jenifer patient button at the same time, wouldn't there be a conflict? How do I prevent this? What can i do for this concurrent operation to prevent exceptions. -
Display form error in respective field form
Is possible to display form error in their respective field error form? And if not how can custom a field name on raise field error? E.g. i have a signup/login system where i use email field as a ìdentifier. This becouse i use a custom signup/login system, with BaseUserManager and AbstractBaseUser, like: models.py class User(AbstractBaseUser): username = models.CharField( verbose_name = u'Nome', max_length=33 ) #identifier email = models.EmailField( verbose_name = u'Email', max_length=255, unique=True, ) #.... forms.py class LoginForm(AuthenticationForm): username = forms.EmailField( label="Email", required=True, widget=forms.TextInput( attrs={'placeholder': 'Email'} )) password = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Senha'} )) class Meta: model = User fields = ['email', 'password'] The problem is, when usernamefield form have an error, the message display : username...error, but i need show Email...error, preferably inside respective field. Even with verbose_name = u'Email' in model.field, the error message display username...errror... So: 1- How can i display error inside respective form.field as placeholder or value and 2 - How customize the form.field.name.error when reise error? -
How to convert list to multiple Q objects?
Taking an example from Django 3.2 documentation, I need to use an argument like this for .filter: Q(question__startswith='Who') | Q(question__startswith='What') In my case need to convert each of the user's selections, which I'm getting in views.py via request.META['QUERY_STRING'], into it's own Q() object. If I tried to create Q objects from that list of parameters, it would not work, because the | would be evaluated. This seems like it must be a solved a problem, but I haven't had luck yet finding the answer. Thanks for any advice. -
How to match any url contains a certain string (such as .jsp) in Django?
I'd like to soft reject any path that contains a string, such as .jsp in the Django 3. Here is my url.py: from django.urls import re_path from django.views.generic import TemplateView re_path( r"^.*\.jsp\??.*$", TemplateView.as_view(template_name="404.txt", content_type="text/plain"), ), The above path pattern can match an ordinary string like /whatever.jsp, but cannot match the following probing string. How to improve my re_path pattern to match this? Thanks! /content/..%3B/crx/packmgr/list.jsp%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0A%3B%0Aa.css?_dc=1615863080856&_charset_=utf-8&includeVersions=true -
React i18next fails to load translation.json as json
React i18next fails to load translation.json as json. everything is functioning well before I use the build folder I'm using React / Django. i18n.js : import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default }, nsSeperator: false, keySeperator: false, backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, }); export default i18n; index.js : import React, {Suspense} from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'bootstrap/dist/css/bootstrap.min.css'; import './index.css'; import './i18n'; ReactDOM.render( <React.StrictMode> <Suspense fallback={(<div className='index__loading'><h2>Loading...</h2></div>)}> <App /> </Suspense>, </React.StrictMode>, document.getElementById('root') ); here's where I switch … -
Django: unknown database name
I am trying to change the database in django from sqlite3 to mysql DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER':'myusername', 'PASSWORD':'mypassword', 'HOST':'127.0.0.1', 'PORT':'3306', } } and after trying to run my server i get this error System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 244, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect return Connection(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb.OperationalError: (1049, "Unknown database 'django'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 576, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\ыв\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() … -
How can I protect some endpoints from user accessing it directly in django?
There is a URL with an endpoint named as 'otp/', I don't want the user to access this endpoint directly, I want to have them as directed by my code (whenever needed) How can I do it? here is my code class OTPView(View): def get(self, request, *args, **kwargs): otp_form = OTP_Form() return render(request, 'otp.html', {'otp_form': otp_form}) def post(self, request, *args, **kwargs): try: otp = request.session.get('otp') first_name = request.session.get('first_name') last_name = request.session.get('last_name') password = request.session.get('password') phone = request.session.get('phone') otp_form = OTP_Form(request.POST) if otp_form.is_valid(): get_otp = otp_form.cleaned_data['otp'] if get_otp == otp: user = MyUser.objects.create_user( phone=phone, password=password, first_name=first_name, last_name=last_name) user.save() otp_entry = OTP.objects.create(user_id=user, otp=otp) otp_entry.save() delete_session(request) messages.success( request, 'Your account has been created') return redirect('login') else: messages.error(request, 'Incorrect OTP') return redirect('otp') else: messages.error(request, 'Please enter the OTP again') return redirect('otp') except: messages.error(request, 'Please try signing up again') return redirect('signup') urls.py path('otp/', OTPView.as_view(), name='otp'), I want this endpoint to be accessed by the user right after the user signup Please suggest me something -
Django Using ManyToMany instead of ForeignKey
In a specific Django app, I have a DB Model class A that is considered as the main class and many other models are connected to it weather through one to one relationship (like B) or one to many relationship (like C). So, the direct approach to implement such is: class A(Model): b = OneToOneField('B', on_delete=CASCADE) # other fields class B(Model): # some fields class C(Model): a = ForeignKey(A, on_delete=CASCADE) # other fields Now, when I want to create a new object of A, the sequence will be: create B object create A object and link the created B object to it create C object and link the created A object to it. This happens on a larger scale with a lot of models linked with model A. But I want to have all the relations seen in the A class so that when I want to create an object of A, I go to create all the related objects first after validating them regardless the relationship, then create new A object and link all those related objects to it. So, I did so: class A(Model): b = OneToOneField('B', on_delete=CASCADE) c = ManyToManyField('C') # as there is no OneToManyField class … -
Getting an error with app label 'admin' not installed
I am building a movie project with django, it is my first project so I am still new at this. When I run python manage.py makemigrations I get the following error: LookupError: No installed app with label 'admin'. I have included a few things to my settings.py, here's the additional stuff (not including the things already installed by requirement) #additional import django django.setup() from pathlib import Path #additional import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-b(tax)t-t&6uy$2=64s8=00^oj#&7o*oj7#x0eg10dsbf-=sqa' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] #additional MEDIA_URL = '/media/' #additional MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #additional from django.contrib import admin from django.urls import re_path # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #additional 'movie', ] ... Admin.py from django.contrib import admin from .models import Movie class MovieAdmin(admin.ModelAdmin): pass admin.site.register(Movie, MovieAdmin) Models.py: from django.db import models class Movie(models.Model): title = models.CharField('Title',max_length=255, unique=True) critics_consensus = models.TextField('Critics consensus', blank=True, null=True) average_grade = models.DecimalField('Average grade', max_digits=3, decimal_places=2, blank=True, null=True) poster = models.ImageField('Poster', blank=True, null=True) amount_reviews = models.PositiveIntegerField('Amount Reviews', blank=True, null=True) approval_percentage … -
How to create a Circular Counter Custom Field in Django?
I'm trying to solve this question as a hackerrank challenge but I'm stuck. Django: Circular Counter Custom Field In this challenge, your task is to implement a custom model field called CircularCounterField as a field to hold the provided CircularCounter class. A circular counter is an object that stores a value that is initially set to the given start value and can be incremented. After a given number of increments from the starting value (let's call this number cycle_len), the value is reset to the starting value. For example, if start=1 and cycle_len=2, then the initial value is 1. After the first increment, the value becomes 2. After the second increment, the value is reset to the start value, i.e. 1. Then, after the third increment, the value becomes 2, and after the fourth increment, it again becomes 1, and so on. CircularCounter class is a very simple class to store the state of a circular counter: class Circular Counter: def init(self, start, cycle_len, value=None): if not isinstance (start, int): raise ValueError("start must be int") if not isinstance (cycle_len, int) or cycle_len <= @: raise ValueError("cycle_len must be a positive integer") if value is not None: if not isinstance (value, … -
I am getting this error "HomeView.get() got multiple values for argument 'id'"
Hello I am creating an app, when I logged in, I want to open up the particular profile of that user (by using user.id), but I am getting this error, And I don't know the reason why? here is my code: class HomeView(LoginRequiredMixin, View): def get(request, id): login_url = 'login/' redirect_field_name = 'home/<int:id>' user = MyUser.objects.filter(id=id).first() return render(request, "home.html", {"first_name": user.first_name, "last_name": user.last_name}) class LoginView(View): def get(self, request, *args, **kwargs): loginform = UserLoginForm() return render(request, 'signin.html', {'loginform': loginform}) def post(self, request, *args, **kwargs): try: loginform = UserLoginForm(request.POST) if loginform.is_valid(): phone = loginform.cleaned_data['phone'] password = loginform.cleaned_data['password'] user = authenticate(phone=phone, password=password) if user is not None: login(request, user) return redirect('home', id=user.id) else: messages.error(request, "Invalid phone or password.") return redirect('login') else: messages.error(request, "Invalid phone or password.") return redirect('login') except: messages.error(request, "Please try again") return redirect('login') I am getting this error TypeError: HomeView.get() got multiple values for argument 'id' What is the problem with it -
Django, i18n, problems with translation after changing LANGUAGE_CODE
I have created a multilingual website, using Django i18n. But then I needed to change the default language (LANGUAGE_CODE) to one of those that were in the LANGUAGES. After that, when setting the language that was originally the default, the translation does not work correctly. The models are translated correctly, but the templates remain in the new default language. At the same time, one more language, which was originally in the LANGUAGES, but neither at the beginning nor now is the default language, there are no problems. -
Cannot connect to "@localhost". Access denied for user 'root'@'localhost' (using password: YES)
I try to connect mysql to django project Here my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': 3306, } } enter image description here -
No installed app with label scrapy-django
I have been following the documentation for scrapy-django, and have implemented all the steps required for the first part. I have got up to the django migrations for the file, and when I use: python manage.py makemigrations open_news I get the following error: No installed app with label 'open_news'. Here's my tree: . ├── example_project │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── settings.cpython-310.pyc │ │ └── urls.cpython-310.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── open_news │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── scraper │ │ ├── __init__.py │ │ ├── checkers.py │ │ ├── pipelines.py │ │ ├── settings.py │ │ └── spiders.py │ ├── tasks.py │ ├── tests.py │ └── views.py └── scrapy.cfg -
Is there any way to build a React App and leave env variables that can be dynamically populated?
I have a react app that is served via Django. I have multiple environments: staging and prod. These environments have different URLs that the API is exposed from. On building the React app I'm passing variable that tells the build which URL to use, but this gets to be a mess with the multiple environments and git. I end up having a git history filled with builds from other environemnts. These builds get passed to other branches when PRs are merged, then they create conflicts, etc. I want to have a single React build that will be able to tell which environment it is and update the API url accordingly: after being built! Is that possible? -
tempfile.tif: Cannot read TIFF header?
Here I am trying to convert a tiff image into jpg but I am getting this error tempfile.tif: Cannot read TIFF header. rgb_img = img.convert('RGB') File "..../PIL/Image.py", line 915, in convert self.load() File ".../PIL/TiffImagePlugin.py", line 1079, in load return self._load_libtiff() File ".../PIL/TiffImagePlugin.py", line 1171, in _load_libtiff raise IOError(err) IOError: -2 this is the function from PIL import Image def convert_to_jpg(tiff_image): img = Image.open(tiff_img) rgb_img = img.convert('RGB') rgb_img.save('jpg_file.jpg') return rgb_img -
Why Django doesn't see my json file at base dir?
My structure of files here I'm beginner at Django. And I read in "2 Scoops of Django", that store database password etc. at settings.py it's bad. So I decided, store password etc. at json file, then I expanded settings.py by this code: import json import os from django.core.exceptions import ImproperlyConfigured with open(os.path.join(BASE_DIR, 'secrets.json')) as secrets_file: secrets = json.load(secrets_file) def get_secret(setting, secrets=secrets): """Get secret setting or fail with ImproperlyConfigured""" try: return secrets[setting] except KeyError: raise ImproperlyConfigured("Set the {} setting".format(setting)) And I got the following code: from pathlib import Path import json import os from django.core.exceptions import ImproperlyConfigured BASE_DIR = Path(__file__).resolve().parent.parent with open(os.path.join(BASE_DIR, 'settings_for_db.json')) as secrets_file: secrets = json.load(secrets_file) def get_secret(setting, secrets=secrets): """Get secret setting or fail with ImproperlyConfigured""" try: return secrets[setting] except KeyError: raise ImproperlyConfigured("Set the {} setting".format(setting)) SECRET_KEY = get_secret("SECRET_KEY") ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', "NAME": get_secret("NAME"), "USER": get_secret("USER"), "PASSWORD": get_secret("PASSWORD"), "HOST": get_secret("HOST"), "PORT": get_secret("PORT") } } WHEN I entered the command from Django documentation: py manage.py check --database default I've got this error: Traceback (most recent call last): File "C:\Projects\Django-project\my_first_site\manage.py", line 22, in <module> main() File "C:\Projects\Django-project\my_first_site\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Projects\Django-project\venv\lib\site- packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Projects\Django-project\venv\lib\site- packages\django\core\management\__init__.py", line 386, in … -
How can I display both active and inactive investments on my dashboard using django?
My template only shows active investments, despite the fact that I wish to show both active and inactive investments. It does not appear on the template when I set is_active to false. Anyone know what I'm doing wrong? Attached is the screenshot of my dashboard where I intend to show both active and inactive investment. This image displays active investment when created. This no investment when I change is_active = False which is what I don't want. I want in_active=False investments to also display on the dashboard. Views def create_investment_view(request): if request.method == 'POST': basic_investment_form = BasicInvestmentForm(request.POST) if basic_investment_form.is_valid(): investment = basic_investment_form.save() investment.basic_interest = investment.basic_deposit_amount * 365 * 0.02/2 investment.basic_investment_return = investment.basic_deposit_amount + investment.basic_interest investment.basic_investment_return += investment.basic_deposit_amount investment.plan = "Basic - Daily 2% for 180 Days" investment.due_date = datetime.now() + timedelta(seconds=5) investment.is_active = True investment.save() print(investment.basic_interest) print(investment.basic_investment_return) print(investment.basic_deposit_amount) messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount)) else: messages.success(request, 'your investment is not successfull! Try again.') else: basic_investment_form = BasicInvestmentForm() context = {'basic_investment_form': basic_investment_form} return render(request, 'create-basic-investment.html', context) def list_investments(request): investments = Investment.objects.all() atleast_one_active=False atleast_one_inactive=False for investment in investments: if investment.is_active: atleast_one_active=True else: atleast_one_inactive=True context = { 'investments': investments, } return render(request, 'list-investments.html', context) Model class Investment(models.Model): PLAN_CHOICES = ( … -
Django cannot render model attributes by slug to the template
I have set a model including some attributes and can get the model by a slug in views.py. However, I can't render its attributes into the template. Did I miss something? Model.py class article(models.Model): title = models.CharField(max_length=200) content = RichTextUploadingField() slug = models.SlugField(unique=True, max_length=200) def __str__(self): return self.title Views.py def post_details(request, slug): details = get_object_or_404(article, slug=slug) context = { details: 'details' } return render(request, 'post_details.html', context) Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_details, name='post_details') ] I have set a URL to get the article model's data by slug in index.html <h4 class="title"><a href="{% url 'post_details' article.slug %}">{{ article.title }}</a></h4> post_details.html <h2>{{ details.slug }}</h2> I can access this template by slug but can't get any attributes by using the 'details' tag -
Using Django-tables2 with class-based view and non-default database throws "NameError: name 'TypeError' is not defined"
I am trying to set up django-tables2 and followed the recommendations in their docs. However, if I call the view, it throws the error File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/asgiref/local.py", line 94, in __del__ NameError: name 'TypeError' is not defined Note: From what I could gather, this error message unfortunately also occurs in other contexts as the most upvoted thread deals with an Apache config problem. I would be glad to adjust the title for clarity once the issue has been grasped concisely. Django-tables2 should access (read-only) a legacy MySQL database which I added behind the default SQLite database in settings.py (see further down). My polls/models.py: from django.db import models import datetime from django.db import models from django.utils import timezone ... class Dashboard(models.Model): host = models.CharField(db_column='Host', max_length=255, blank=True, null=True) title = models.TextField(db_column='Title', blank=True, null=True) operation = models.CharField(db_column='Operation', max_length=255, blank=True, null=True) performedat = models.DateTimeField(db_column='PerformedAt', blank=True, null=True) class Meta: managed = False db_table = 'dashboard' In case it's necessary, the underlying table in MySQL looks like this: c.execute('''CREATE TABLE dashboard( id INT PRIMARY KEY AUTO_INCREMENT, Host VARCHAR(255), Title TEXT, Operation VARCHAR(255), PerformedAt DATETIME);''') My polls/views.py: from django.shortcuts import render from django.views.generic.list import ListView from .models import Dashboard from django.http import HttpResponse class DashboardListView(ListView): model = Dashboard …