Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React + DRF API not working when using other device
I have two applications: React frontend (via create-react-app) on localhost:3000 Django backend (mainly django-rest-framework) on localhost:8000 I use JWT for authentication but I don't think that matters in this case. Those two apps interact like this: React app has only two routes available to everyone: login page and register page After logging in, login page sends a request to generate JWT which is saved in localStorage From now on each request has a header with JWT in it - done with axios.interceptors So this is how I log in: async function loginUser(email: string, password: string) { try { const response = await axios.post("/api/token/", { email, password, }); setToken(response.data); return true; } catch (error) { return false; } } It works because I have a following setting specified in my package.json: "proxy": "http://localhost:8000" This is my authRequest function which returns axios object to communicate with the API in an authenticated mannner: const baseURL = "http://localhost:8000/api"; export const authRequest = () => { const axiosInstance = axios.create({ baseURL, timeout: 5000, headers: { Authorization: getAccessToken() ? `JWT ${getAccessToken()}` : null, "Content-Type": "application/json", accept: "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", }, }); return applyInterceptors(axiosInstance); }; The applyInterceptors function add some interceptors which … -
I want to load images faster without directly changing resolution of the image but with a script or some other css stuff
Size of the image is changed in the css but it loads in full hd which makes the process very long. Website is made in django. #resize { width: 213px; height: 120px; border-radius: 5%; } <img id="resize" src="https://cdn.discordapp.com/attachments/649975215685632060/838073807218016286/latest.png"> -
Python Django Email
Good day, I have a Django app that sends emails. I used a google app password for my EMAIL_HOST_PASSWORD, it works perfectly fine, but the from_email always set to my email which I used to create the app password instead of the email it gets from the form. How can I fix this, please? -
I get error 405 after submitting the django form
i try to combine DetailView and form, but when i try to submit the form i get a 405 error views.py class ReplyToVacancy(DetailView): model = Vacancy template_name = 'vacancies/vacancy.html' pk_url_kwarg = 'vacancy_id' context_object_name = 'vacancy' # form_class = 'CreateApplication' # success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CreateApplication return context html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> -
How can I dynamically create multi-level hierarchical forms in Django?
I'm building an advanced search page for a scientific database using Django. The goal is to be able to allow some dynamically created sophisticated searches, joining groups of search terms with and & or. I got part-way there by following this example, which allows multiple terms anded together. It's basically a single group of search terms, dynamically created, that I can either and-together or or-together. E.g. <field1|field2> <is|is not|contains|doesn't contain> <search term> <-> <+> ...where <-> will remove a search term row and <+> will add a new row. But I would like the user to be able to either add another search term row, or add an and-group and an or-group, so that I'd have something like: <and-group|or-group> <-> <field1|field2> <is|is not|contains|doesn't contain> <search term> <-> <+term|+and-group|_or-group> A user could then add terms or groups. The result search might end up like: and-group compound is lysine or-group tissue is brain tissue is spleen feeding status is not fasted Thus the resulting filter would be like the following. Data.objects.filter(Q(compound="lysine") & (Q(tissue=brain) | Q(tissue="spleen")) & ~Q(feeding_status="fasted")) Note - I'm not necessarily asking how to get the filter expression below correct - it's just the dynamic hierarchical construction component that I'm trying … -
Adding values_list produces AttributeError
When I do something like: def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['sdnClearedDates'] = serializers.serialize('json', Profile.objects.filter(pk=object_id)) return super(ProfileAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) it returns a valid list of json data. But when I add a values_list('sdn_cleared_dates', flat=True) inside the Profile query like this: Profile.objects.values_list('sdn_cleared_dates', flat=True).filter(pk=object_id) It returns an AttributeError. Exception Value: 'list' object has no attribute '_meta' What am I doing wrong? -
Сhecking for groups in html django
I need to check if there is a user in the author group, if there is, then these buttons will: appear <a href="{% url 'news_update' el.id %}" class="btn btn-primary">Редактировать пост</a> <a href="{% url 'news_delete' el.id %}" class="btn btn-primary">Удалить пост</a> If not in this group they do not appear -
Enable my Kivy mobile app to use sockets (for real time messaging text and images) to/from a Django backend
I am just learning about sockets and am confused about what would best suit my needs. I am not worried about scaling - this is just a learning project for me. I have a working kivy - Django RESTful API going for user authentication. Now, I am trying to add real time exchange of text and images. What options should I consider for Django ? Thanks in advance. Dave -
Can migrate with models.DateTimeField() but SQL Error with models.TimeField()
I have a Django model that is not working properly. When I migrate the following, I don't get any errors and I get an id, question_text, and time column in my database: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) time = models.DateTimeField() def __str__(self): return self.question_text But if I change the models.DateTimeField() to models.TimeField(), I can successfuly run python3 manage.py makemigrations: Migrations for 'app': app/migrations/0001_initial.py - Create model Question But when I then try to run python3 manage.py migrate, I get the following error: Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0002_question_time...Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/Cellar/python/3.7.6/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) DEFAULT '22:12:07.640513' NOT NULL' at line 1") The above exception was the direct cause of the following … -
'TypeError at /api/chunked_upload/ Unicode-objects must be encoded before hashing' errorwhen using botocore in Django project
I have hit a dead end with this problem. My code works perfectly in development but when I deploy my project and configure DigitalOcean Spaces & S3 bucket I get the following error when uploading media: TypeError at /api/chunked_upload/ Unicode-objects must be encoded before hashing I'm using django-chucked-uploads and it doesn't play well with Botocore I'm using Python 3.7 My code is taken from this demo: https://github.com/juliomalegria/django-chunked-upload-demo Any help will be massively helpful -
Aiottp + Aiohttp Swagger dosen't works
my application is Django + Aiohttp + Gunicorn (localhost) I started use aiohttp-swagger to documentation, but the files doesn't load (html, css and javascript). Can someone help me? The route /api/doc generate by aiohttp-swagger - net::ERR_ABORTED 500 (Internal Server Error) -
How to create a Parent/Child relationship with Django REST models?
I am new to Django REST and want to basically create a join table like this. One Page (txt doc) can have a parent and child Page. Each and every Page can be a parent and child of multiple other pages. Both the Page Entity and PageToPage Entity have an implemented model & serializer in the backend, where the serializer looks like this: class PageToPageSerializer(serializers.ModelSerializer): parent_page = PageSerializer(many=True, read_only=True) child_page = PageSerializer(many=True, read_only=True) class Meta: model = PageToPage fields = ['pkid', 'parent_page', 'child_page'] When entering the manage.py shell and create a PageToPage object, it just yields empty results: # Create Pages p1 = Page(title="Parent Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p1.save() p3 = Page(title="Child Page 1", text="Once upon a time, there was a young man...", page_of_user=u2) p3.save() # Create Page Relationships ptp = PageToPage(parent_page=p1, child_page=p3) ptp.save() # Select all Pages print("Created Pages:") ser2 = PageSerializer(Page.objects.all(), many=True) print(ser2.data) # Select all Page to Page relationships ser_ptp = PageToPageSerializer(PageToPage.objects.all()) print("Created Page relationships:") print(ser_ptp.data) Output: >>> Created Pages: >>> [OrderedDict([('pkid', 1), ('title', 'Test Page number 1'), ('text', 'Just some sample text'), ('creation_date', '17.06.2021'), ('page_of_user', UUID('eeec0437-75f2-44ba-935d-96fcb78e38c6'))]), ...] >>> Created Page relationships: >>> {} What am I doing wrong? … -
Django Admin 403 in Autocomplete as Superuser
Django==3.2.4 I'm getting error 403 when entering a query in a django admin autocomplete field. This only happens in production and in every model with autocomplete fields. Please tell me if more info is required in order to answer this question. Thanks! Example screenshot in Django Admin autocomplete field RESPONSE HEADERS alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: *** cf-request-id: *** content-encoding: br content-language: es-ar content-type: text/html; charset=utf-8 date: Thu, 17 Jun 2021 21:29:22 GMT expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" nel: {"report_to":"cf-nel","max_age":604800} referrer-policy: same-origin report-to: *** server: cloudflare strict-transport-security: max-age=31449600; includeSubDomains; preload vary: Accept-Language, Cookie x-content-type-options: nosniff X-DNS-Prefetch-Control: off x-frame-options: DENY x-xss-protection: 1; mode=block REQUEST HEADERS :authority: *** :method: GET :path: /***/autocomplete/ :scheme: https accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 accept-encoding: gzip, deflate, br accept-language: es,es-US;q=0.9 cache-control: max-age=0 cookie: csrftoken=***; sessionid=*** dnt: 1 sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91" sec-ch-ua-mobile: ?0 sec-fetch-dest: document sec-fetch-mode: navigate sec-fetch-site: none sec-fetch-user: ?1 upgrade-insecure-requests: 1 user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36 -
Django Return JSON POST Response Header & Body
I created a webhook for my Django project and I am trying to do a verification with another API from SmartSheet SDK Python. Basically in order for me to enable a webhook for one of my sheets, I have to echo back the verification data from header and body back for the webhook to be enabled. Here is my python code. Basically up to this point, if you send a POST request through postman to my Django project, it will record it in the database with the changes, however I haven't created a process yet on what to do with the data. @csrf_exempt def SmartSheet_WebHook(request): if request.method == "GET": return HttpResponse("This is a GET Request.", content_type="text/plain") if request.method == "POST": record = APIInformation.objects.get(api_name = "SmartSheet") key = record.key given_token = request.headers.get("key", "") if compare_digest(given_token, key): print("Deleting stale records") WebHookSmartSheet.objects.filter(received_at__lte=timezone.now() - dt.timedelta(days=7) ).delete() payload = json.loads(request.body) WebHookSmartSheet.objects.create(received_at=timezone.now(),payload=payload,) print(payload) # Process Payload New Student Creation return JsonResponse(payload, safe=False) else: return HttpResponse("Verification Error.", content_type="text/plain") How do I return the data I am getting from the post request they are sending to my webhook? Here is their documentation on what they are looking for. "When an API client attempts to enable a webhook, Smartsheet … -
Django rest framework with client-side validation
I have so many questions, so I gonna contextualize what I am trying to do. I'm creating a Django chat app with rest_api in the backend and eventually will work with websocket to be a real-time website. The first feature that i am implementing is: I want to do some client-side validation that verify if the room that i want to connect already exists. in my api/models.py: class Room(models.Model): name = models.CharField(max_length=64, blank=False) host = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return self.name I created a serializer for that model and the follow APIView: class RoomView(ListCreateAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer pointing to the follow URL: app_name = 'api' urlpatterns = [ path('room/', views.RoomView.as_view(), name='index'), ] I have that function that check if the typed room already exist, if exist will redirect to that room, if don't, should send a POST request to my api, return and redirect. function roomExist() { let name = document.getElementById('name'); if (!isEmpty(name)) return; let room = document.getElementById('room'); if(!isEmpty(room)) return; fetch('../api/room') .then(res => res.json()) .then(data => { data.forEach((e) => { if (e.name === room.value) { submitForm() }}) createRoom(room.value) }) } wheel, my problem is with that last part, how i can send a POST request to … -
How to pass qs.query to a custom plpgsql function with Django ORM?
I have some queryset qs = MyModel.objects.filter(fieldname='fieldname') and a custom plpgsql function my_function(), that I can use in pg_shell like: SELECT my_function('SELECT * FROM my_model'); How to do this with Django ORM? I tried to: with connection.cursor() as cursor: query, params = qs.query.sql_with_params() query = f"SELECT my_function('{query}')" cursor.execute(query, params) But qs.query.sql_with_params() does not return valid SQL. Is something like this even possible with Django ORM? -
Hi, I am having a problem related a django postgreSQL
I have two tables and I need to calculate something similar to a smoothie Table fruit: fruit_Id, fruit_name, fruit_cost fruit_name(pk) Table smoothie: id juice_name fruit1_name References fruit.fruit_name, fruit1_% , fruit2_name References fruit.fruit_name, fruit2_% , smoothie_cost In order to calculate smoothie cost I need access price from Table fruit. Can you suggest best way to do this. I have tried to use Joins and triggers but no use. Is calculating in models.py is best approach or in PostgreSQL -
How I can create a textfield in dajngo admin that not create a field in database?
In django, I need a textfield and a button in django admin, but I don't want to save that textfield in database. For example I have a textfield named age. I need to a textfield to enter birthday.By clicking on button I will calculate age and assign to age field. This is only a example! -
Django MPTT selects all categories data while rendering to template?
I am using the django MPTT library for building my category model. Everything works fine but I noticed the following issue which is quite annoying. For every category that is rendered in my template, MPTT does a select * and gets all categories. I used the django debug toolbar to profile the query. I found this behaviour quite strange. Wanted to know if anyone else experienced such an error. This is the sample code from categories.base import CategoryBase class SampleCategory(CategoryBase): class Meta: verbose_name_plural = 'Sample Categories' class Product(models.Model): category = models.ForeignKey( SampleCategory, on_delete=models.SET_NULL, null=True, blank=True, ) In template <span class="dropdown"> <a href="#" class="dropdown-chevron" data-toggle="dropdown" data-display="static" aria-haspopup="true" aria-expanded="false"> </a> <span class="dropdown-menu dropdown-menu-lg-right filtersDropdown"> {% bootstrap_field filter.form.category bound_css_class='' show_label='sr-only' size='sm' %} {% bootstrap_button 'Filter' button_type='submit' size='sm' button_class='btn-primary mb-3 mr-md-2' %} </span> </span> filters.py category = django_filters.ModelMultipleChoiceFilter(field_name='category', queryset=SampleCategory.objects.all(), ) -
Images not displaying in a rendered pdf
I'm tryin to render a particular html file to pdf and it work. But the issue is the rendered pdf file does not contain an image which i linked in the html file. below is the code Below is my Views def get(request): template = get_template('success.html') context = { 'path': f"{surname}.png" } html = template.render(context) pdf = render_to_pdf('success.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Paymentslip%s.pdf" content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Any solutions will be appreciated. Thanks. -
Django one to many query
I have a one-to-many model relationship an trying to query both the main and the referenced model in views. The model.py looks like this(simplified): class Project(models.Model): project_number = models.CharField(max_length=5, unique=True) .... class Phase(models.Model): time_input_id = models.AutoField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, default=None) phase_name = models.CharField(max_length=50, null=True) Views.py: How can I structure the views in order to pass all the fields to a template that shows info about the project and all its phases? I've tried so many things with no success, my brain just stopped functioning now. -
I want to make a User to User Private Live Chat App with React & Django
I'm really confused about that. I want to make a user to user chat app on my project with Django and React. I've tried create a model and fetch messages with Rest Framework API. But that's not what i need. I need to live chat between just two users. When a user send a message to me i want to display that instantly (without click anywhere) like Whatsapp. When i try this with DRF i can get messages and save them inside to useState. But i must to refresh page for display new messages. I don't want to this. I don't want to refresh to page. How can i do that? I saw Django Channel but i don't know can i use this for just between two user's private messaging. Also i don't know how to set this on React JS. Can anyone help me? I just need your opinions. I can try your opinion. You don't have to write code for me. -
Cross-Origin Request Blocked - REACT and webserver issue
My application consist of three major parts. Firstly, it consist of a Django application that functions as my REST-API. The second part consist of a nginx web-server that is linked with the Django application through a reverse-proxy. These two components, the web-server and Django application is containerized using docker. The last component, and the one which is creating problems is my React application which is responsible for the GUI. When requests are sent between React application, and the server though Axios, I'm getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS request did not succeed). Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. As I understand from the error, the problem is most likely connected to Cross-Origin Resource Sharing. Consequently I've tried the following modifications. In aspect to the Nginx, I've change the conf folder by adding: add_header Access-Control-Allow-Origin *; upstream API { server web:8000; } server { listen 80; location / { proxy_set_header Host $host; add_header Access-Control-Allow-Origin *; proxy_pass http://API; } location /staticfiles/ { alias /home/app/web/staticfiles/; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } In terms of the Django application, I've added the CorsMiddleware middleware and … -
pipenv Locking failed: No closing quotation
I am trying to use django in a virtual environment. I am using windows 10 and python 3.9. I write in my cmd pipenv install django but it constantly gives me a locking error: Installing django... Adding django to Pipfile's [packages]... Installation Succeeded Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Resolving dependencies... Locking Failed! Traceback (most recent call last): File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 764, in <module> main() File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 758, in main _main(parsed.pre, parsed.clear, parsed.verbose, parsed.system, parsed.write, File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 741, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 702, in resolve_packages results, resolver = resolve( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\resolver.py", line 684, in resolve return resolve_deps( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1397, in resolve_deps results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 1110, in actually_resolve_deps resolver.resolve() File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 825, in resolve results = self.resolver.resolve(max_rounds=environments.PIPENV_MAX_ROUNDS) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 813, in resolver self.get_resolver(clear=self.clear, pre=self.pre) File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 804, in get_resolver constraints=self.parsed_constraints, repository=self.repository, File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 797, in parsed_constraints self._parsed_constraints = [c for c in self.constraints] File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\utils.py", line 797, in <listcomp> self._parsed_constraints = [c for c in self.constraints] File "c:\users\someone's pc\appdata\local\programs\python\python39\lib\site-packages\pipenv\patched\notpip\_internal\req\req_file.py", line 137, … -
database connection isn't set to UTC - Django getting timestamp
Set-up I'm trying to run unit tests in Django. pipenv run python manage.py test test_module.tests.test_application.ExampleTest I'm getting the following error: Traceback (most recent call last): File "C:\Users\Dom_W\Documents\Development\Projects\project_test\data_load_api_functions\tests\test_deepcrawl_api.py", line 210, in setUp print(list(User.objects.all())) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1130, in execute_sql return list(result) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1509, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\models\sql\compiler.py", line 1509, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\utils.py", line 96, in inner return func(*args, **kwargs) File "C:\Users\Dom_W\.virtualenvs\example-project-n37Jnk2\lib\site-packages\django\db\backends\postgresql\utils.py", line 9, in utc_tzinfo_factory raise AssertionError("database connection isn't set to UTC") AssertionError: database connection isn't set to UTC I think it might've started because of the switch to BST, but now despite forcing timezone I can't get Django to recognise it. What I've tried I set the default Postgres timezone to UTC in postgresql.conf That did nothing so I inspected the function which is responsible: def utc_tzinfo_factory(offset): if offset != 0: raise AssertionError("database connection isn't set to UTC") return utc And discovered it's being given a datetime.timedelta with a value of 0:00:00 which then causes this line to fail: …