Django and Python "Questions and answers"

17.04.2024
ModuleNotFoundError: No module named 'captcha.fields'

By Executing command python manage.py runserver in vscode terminal occured this error : Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner self.run() File "C:\Users\<user>\AppData\Local\Programs\Python\Python312\Lib\threading.py", …

17.04.2024
How to properly use javascript within oTree / django?

I have a problem regarding implementing my non-oTree HTML, CSS, JS files into oTree format. I have this puzzle game (see screenshot 1) . Implemented in oTree it is buggy - …

17.04.2024
Setting Timezone for django connection

The Problem: Postgresql timezone is set to 'UTC' /etc/postgresql/15/main/conf.d/local.conf: log_timezone = Europe/Warsaw timezone = UTC database has been altered: ALTER DATABASE example_database SET TIMEZONE TO 'Europe/Warsaw'; Postgresql user has set own time_zone SELECT rolconfig FROM pg_roles WHERE rolname …

17.04.2024
Trying to connect oracle db to the django application using wallet.zip file

I'm configuring my Oracle database to the django application using wallet.zip file in the following way. Note: This wallet.zip file contains tnsnames.ora file. In settings.py file: DATABASES = { "oracledb": { "ENGINE": "django.db.backends.oracle", "NAME": "dummyemployee", "USER": "dummyuser123", "PASSWORD": "dummypass123", "OPTIONS": …

17.04.2024
Persist list inside a object Django Rest Framework

I'm trying to persiste list of a python object (dico) like this but it's difficult { "leader": { "nameLastname": "AAAAA" }, "employeeRemun": { "grossSalaryBase": 111, "bonuses": 222, "travellingExpenses": 333, "noRemuneration": false }, "abandonmentCurrentAccount": { "abandonDate": "2023-10-20", "partner": "BBB", "amount": 444, …

17.04.2024
Fetching Data from a .sql file in a Django Project

I have a django project. I have a dump of the data from a Mysql database in a .sql file and want to query some data from this file into my django project and display it. I am fairly new …

17.04.2024
DLL load failed while importing _rust: The specified procedure could not be found

I am trying to hit an API that is of POST type, it generates access and refresh tokens which can be used to access other APIs. It takes the username and password in the body, which we generate while creating …

17.04.2024
How can I fix my blacklist token at Django rest framework simple JWT? Error: Given token not valid for any token type"

Im using rest framework simple_jwt authentication. After login, I have access and refresh token. I checked on the website JWT Web tokens to confirm if the type is correct and the token has type "refresh", the same that I should …

17.04.2024
`I am trying to build a registration form in Django, using Django form [duplicate]

I put {{form.username}} {{ form.email }} {{ form.password }} in my html code instead of text boxes and i can't see them, i also made a forms.py file and views.py this is register.html `{% load static %} <!DOCTYPE html> <html …

17.04.2024
Django guest user cart functionality? Is it safe?

Creating an e-commerce website project to try and learn Django and more about Javascript, so I have been going over a tutorial for the past week. In the tutorial, there is a guest user cart feature. It works by storing …

17.04.2024
TokenObtainPairSerializer override

I'am using django-otp and Django-rest-jwt my goal is I want to check if user has enable 2fa if yes I will give him the refresh and access token i would like to change my top file to not required . …

17.04.2024
Deployed Django Application on PythonAnywhere: Connection Refused Error When Controlling Raspberry Pi Robot Remotely

I am trying to deploy a Django web application on PythonAnywhere that controls a Raspberry Pi robot remotely. The application worked flawlessly locally using ngrok to establish a connection, but after deploying it to PythonAnywhere, I encountered the following error: …

17.04.2024
Foreign Key dropdown in Admin returns __str__, can I change it so some other column? [duplicate]

Here is my setup: # myapp.models class Country(models.Model): alpha2 = models.CharField(primary_key=True, max_length=2), name = models.CharField(max_length=64, def __str__(self): return "%(alpha2)s %(name)s" % {"alpha2": self.alpha2, "name", self.name} class Address(models.Model): id = models.BigAutoField(primary_key=True) province = models.CharField(max_length=64) country = models.ForeignKey(Country, on_delete=models.PROTECT) …

17.04.2024
Django project not fetching static files

I am developing a small app for my course in Django. Now, I am trying to bring my project to a cloud system, in this case using Heroku, however it seems that I have an issue with fetching my static …

17.04.2024
Python Django ASGI - saving image to a model with django-storages to S3 bucket results in memory leak

First of all I've been looking for a solution for a couple of days and tried various code snippets found here. The problem: hosted web app consumes more and more memory everytime image is saved to a Django model ImageField …

17.04.2024
Django admin site not loading in localhost

I am running python manage.py runserver on my django project but my django admin site is not loading locally. All the other urls apart from http://127.0.0.1:8000/ are functional. I am using Django==4.2.11 and Python 3.9 This is my urls.py from …

17.04.2024
Как сделать проверку на наличие у пользователя прав?

Как сделать проверку на наличие прав у пользователя в html? В представлении (views.py) как сделать такую проверку понятно, но как сделать непосредственно на странице, как, например, с user.is_superuser? Или в Django нет встроенного шаблонизатора для проверки на права?

17.04.2024
How to show embeded video on home page from blog page in wagtail?

As shown i can embed the video via URL. but it save videos as url and text as whole body. i an unable to extract videos only and show in home page. https://docs.wagtail.org/en/v4.0.3/editor_manual/new_pages/inserting_videos.html# i tried using <pre …

17.04.2024
Django filter objects using two fields [duplicate]

I have a Django model looks like this class Product(models.Model): product_type_id = models.IntegerField() product_sub_id = models.IntegerField() ... Where a product can be defined as name product_type_id product_sub_id toy …

17.04.2024
Why Django Admin static doesn't work in nginx and docker?

The problem is when I make docker-compose up and enter my website at localhost/admin in ngnix I don't see the default django admin styles. nginx.conf location /static/ { autoindex on; alias movies_admin/staticfiles/; } components/static.py from pathlib import Path import …

17.04.2024
Django merge two m2m_change signals

I have a post model which has category m2m field and tag m2m field, on post post_save i want to retrieve the category ids and tag ids from that post model instance, but after some research i found out, m2m …

17.04.2024
How can celery use Django ORM?

How can celery use Django ORM? Celery and django are diffent processes. But, Celery worker can use Django Application code.(ORM, Model..) I think celery process have django application code. Is it right? What should I do setting when django and …

17.04.2024
How to make href point to a django template and pass context to it? [duplicate]

I have a django template listing mails/messages from a sql database. I am trying to make those messages clickable by using an &lt;a&gt; tag, as to open a page displaying the content of the message. Part of my template listing …

17.04.2024
Drf allauth google signup sign in

Im using django allauth for google signup sign in after successfully sign in, all the functions which need authentication will be performed after user is authenticated but i dont know how to authenticate the user in backend after sign in …

17.04.2024
Problem with Django template inheritance, i had tried referring Django docs and everything with the code is correct but the expected out is wrong [duplicate]

Trying to extend base.html so that my home.html will be visible in base.html body I think i have missed something, can anyone take a look and suggest me. once check this code https://github.com/Pav125/portfolio/tree/main/portfo/skills/templates/skills or see parts of …

17.04.2024
How do I start a django project with uvicorn in pycharm and debug

I want to debug a django project using pycharm, but this django project uses uvicorn blogs.asgi: application --host 0.0.0.0 --port 8000 starts. How do I configure pycharm so that it starts a normal django project by clicking the Debug …

17.04.2024
Error when using cms.api.create_page "UserWarning: No user has been supplied when creating a new PageContent object."

When I use the Django CMS API &quot;create_page&quot; function I get the following error: UserWarning: No user has been supplied when creating a new PageContent object. No version could be created. Make sure that the creating code also creates a …

17.04.2024
Django puts AND clause to lookup "in"

Django 4.2 together with graphene-django filters is making my query use AND operation class ExampleFilterSet(FilterSet): label__name__in = StringInFilter(method=&quot;filter_labels&quot;) class Meta: model = Example fields = {&quot;users__email&quot;: [&quot;in&quot;]} Ideally, here it should have been OR query - where users__email in …

17.04.2024
Nginx[emerg] "map" directive is not allowed here in /etc/nginx/sites-enabled/default:1

This is my /etc/nginx/sites-enabled/default file map $sent_http_content_type $expires { default off; text/html epoch; text/css 30d; application/javascript 30d; ~image/ max; } server { listen 80 default_server; listen [::]:80 default_server; expires $expires; # SSL configuration # # listen 443 ssl default_server; # …

17.04.2024
How do I access all files, such as environment variables

Import logging logger = logging.getLogger(__name__) How do I make this part accessible from all files? Is there a way to use it on all files without importing it similar to the environment variable?

17.04.2024
Deleting Django migrations in the auth app [duplicate]

I have a migration that was created for the built in django auth app and we realized it was a bad idea and want to completely remove it because its buggy. however since this migration was for the pre built …

17.04.2024
Is it better to use http requests or websocket connection for uploading and retrieving static content [closed]

Is it better in terms of server load, resources, cost, ..etc to use standard post and get http requests or a web socket to initially upload and/or retrieve static content such as profile pics of a user and other users. …

17.04.2024
Django oauth toolkit, setting the scopes for separate authorization server

I am trying to separate my resource server with the authorization server https://django-oauth-toolkit.readthedocs.io/en/latest/resource_server.html, and now confused on the setting of the SCOPES available in the authorization server. From my understanding, the authorization server would need to know …

17.04.2024
Am I missing something with Django's makemigrations?

I am working on a Django project and am struggling with adding a new field to a models class. I am still pretty new, but this is what my Manager model class look like: class Manager(models.Model): ''' Create Manager model …

16.04.2024
I use mac, starting django using visual code studio. I fail to start a new app “startapp” I get syntax error “ File ‘Manage.py’, line 17 ) from exc”

I am starting django with visual code studio. I fail to start a new app “startapp” I get syntax error “ File ‘Manage.py’, line 17 ) from exc” I tried changing in manage.py putting “except Exception as exc” but no …

16.04.2024
Nginx, gunicorn & django on amazon lightsail, what is the hostname of the ip address?

I deployed a Django application to Amazon Lightsail VPS, and it works as expected when I access it by the domain name xxxxx.com, However, if I tried to access it by the IP address, it gave an error: Invalid HTTP_HOST …

16.04.2024
Does wagtail tag {% slugurl 'page' %} work with Wagtail-localize?

I'm building a website with Django, Wagtail and Wagtail Localize. But when I'm load my website on &quot;https://exemple.com/fr/&quot; the slugurl tags generates links like href=&quot;/en/about/&quot; I followed settings for urls.py : urlpatterns = urlpatterns + i18n_patterns( path(&quot;search/&quot;, search_views.search, name=&quot;search&quot;), path(&quot;&quot;, …

16.04.2024
Django: psychopg2 unique violation error anyway to fix this

I was updating my django projects version from 2.1 to 2.2 and it looks like some errors occurred with my staging database (I am assuming from all the answers that look similar to my problem). I however am unsure on …

16.04.2024
Django IntegrityError: Check constraint failed: new__blog_blogpage

I'm trying to build a blog using Django(wagtail cms) and have this error now that I'm not quite sure I understand. I'm assuming it has to do with my blog model. I've been googling for a day and half with …

16.04.2024
Django with datatables bootstrap 5 pagination is not working properly

I am learning Django with a sample web page. And I am trying to integrate Jquery DataTable with Bootstrap 5. The issue is, I have a total of 12 records in the DB. When I do the code and return …