Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Baseserializer remove certain fields from validated_data
I need to validate a payload json based on, say, fields A, B. But I don't want these to show in serializer.validated_data I tried to override validated_data base class method. class MySerializer(serializers.Serializer): fieldA = ... fieldB = ... fieldC = ... def validate_fieldA(self, fieldA): # validate def validate_fieldB(self, fieldB): # validate def validated_data(self): data = super().validated_data() exclude_fields = self.context.get('exclude_fields', []) for field in exclude_fields: # providing a default prevents a KeyError # if the field does not exist data.pop(field, default=None) return data Now when I try to access serializer.validated_data dict, it returns a method instead of deserialized dictionary. <bound method MySerializer.validated_data of .... How do I accomplish this correctly? -
How can I configure my Django application to use separate databases for different superusers?
How can I create multiple databases in my Django project, where each superuser has access to their own separate database . so when I called or login with superuser only their data should be visible in the dashboard or database I have tried to create multiple database in setting.py and models.py but it is not working -
Django running with apache2 cannot find app.settings module
Django works when running with python manage.py. When I run with apache I get a 500 internal server error, the apache error log file states: AH01215: ModuleNotFoundError: /var/www/app/myproject/wsgi.py AH01215: : : /var/www/app/myproject/wsgi.py AH01215: No module named 'myproject': /var/www/app/myproject/wsgi.py AH01215: : /var/www/app/myproject/wsgi.py So I checked to my wsgi.py file to see if sys.path was looking in the correct location (removed the exit statement after the check): #!/usr/bin/env python3 import os import sys exit(sys.path) from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() Note the shebang, I had to add that to fix an earlier error. The apache error log file now shows: AH01215: ['/var/www/app/myproject', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']: /var/www/app/myproject/wsgi.py sys.path is not including /var/www/app so I look in the relevant sites-available file and also check there are no other conf files with the same ServerName: <VirtualHost *:80> ServerName example.com ServerAlias www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/app Alias /static /var/www/app/static <Directory /var/www/app/static> Require all granted </Directory> WSGIDaemonProcess myproject python-path=/var/www/app:/var/www/app/myprojectenv/lib/python3.10/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /var/www/app/myproject/wsgi.py <Directory /var/www/app> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/your-project-name-error.log CustomLog ${APACHE_LOG_DIR}/your-project-name-access.log combined </VirtualHost> I can see that the python-path variable is set to /var/www/app, but this does not appear in sys.path in wsgi.py. So I go … -
Python Django Error: TemplateSyntaxError: Could not parse the remainder
What is the solution for following problem? Error is on line 10! I do not know what is wrong with the code! Error during template rendering In template C:\Users\farib\Desktop\Python\classProject\signup\templates\services.html, error at line 10 Could not parse the remainder: '(airquality' from '(airquality' 1 {% extends "layout.html" %} 2 {% block content %} 3 <h1 style="color:rgb(51, 48, 51)">Services</h1> 4 <form id="contactForm" method="post" action="services" class="needs-validation"> 5 {% csrf_token %} 6 {{ servicesform }} 7 <input id="sendBtn" type="submit" class="btn btn-primary" value="Analyze"> 8 </form> 9 <h3>Address: {{ address }}, City: {{ city }}, Country: {{ country }}, Latitude: {{ latitude }}, Longitude: {{ longitude }}</h3> 10 {% if airquality < 50 %} 11 <h3 style="background-color: green;">Air Quality: {{ airquality }}</h3> 12 {% elif (airquality >= 51) and (airquality < 100) %} 13 <h3 style="background-color: yellow;">Air Quality: {{ airquality }}</h3> 14 {% elif (airquality >= 101) and (airquality < 150) %} 15 <h3 style="background-color: orange;">Air Quality: {{ airquality }}</h3> 16 {% elif (airquality >= 151) and (airquality < 200) %} 17 <h3 style="background-color: red;">Air Quality: {{ airquality }}</h3> 18 {% elif (airquality >= 201) and (airquality < 300) %} 19 <h3 style="background-color: purple;">Air Quality: {{ airquality }}</h3> 20 {% elif airquality >= 301 %} I tried … -
django problem when i start an application
When I start an application like (pages) then I link it with the project in settings => INSTALLED_APPS: INSTALLED_APPS = [ 'pages.app.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Then i made a url for it in urls: `from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('pages',include('pages.urls')) ]` This Error appear after running the server : ModuleNotFoundError: No module named 'pages.app' i searched for the solution and i founed that the problem may be in the installed apps but i made it right -
Operational problem to connect Postgres db
When trying to migrate, I receive the below error message. This means that my project cannot connect to my local PostgreSQL. My project is on django. I work with Windows 11. I googled and nearly all similar errors where linked somehow to Docker and docker-compose. While the current project isn't dockerized. I previously run a similar docker project through docker desktop, with postgres database. While I don't know if that is relevant to my problem, I note in case it's relevant. I also removed all docker container, images, volumes that could conflict with the current file, just in case. I updated PostgreSQL and restart its settings. Any return would be highly appreciated. settings/base.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db_user', 'USER': 'postgres', 'PASSWORD': 'my_db_password', 'HOST': 'localhost', 'PORT': '5432', } } command: python manage.py migrate: error message: File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\anica\AppData\Local\Programs\Python\Python311\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.OperationalError -
python socket multi-threading with docker issue
I've encountered this issue for 2 days. Hope someone can get me out of this. The program I am write is quite simple, just use python struct to create an ICMP ping packet, then use socket to send out, measure the latency. I don't want to use the system level command because I am trying to make this independent beyond whichever OS is deploying the code. Here is part of the code: def _icmp_ping(host, packet_size, interval, timeout, packet_num): # Sends ICMP echo requests to the specified host and returns the average latency and success rate as a tuple if packet_size < 8: packet_size = 8 payload = b'\x00' * (packet_size-8) icmp_protocol = socket.getprotobyname("icmp") icmp_echo = 8 packet_id = random.randint(1, 0xffff) packet = struct.pack("!BBHHH", icmp_echo, 0, 0, packet_id, 1) + payload # Adds the ICMP checksum to the packet packet = struct.pack("!BBHHH", icmp_echo, 0, socket.htons(NetPack._calculate_checksum(packet)), packet_id, 1) + payload sent_count = 0 received_count = 0 total_latency = 0 # Sends 10 ICMP echo requests for _ in range(packet_num): # Creates a raw socket for sending ICMP packets with closing(socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp_protocol)) as sock: # Sets the timeout for the socket sock.settimeout(timeout) # Sends the ICMP packet to the specified host sock.sendto(packet, … -
For loop catch Exception before called function do it's job
I got a code that connects to Binance api/url and sometime has ConnectionError. My code is like: def initial_connect(self): try: client = Spot(key=self.api_key, secret=self.secret_key, base_url='https://api4.binance.com') except: client = Spot(key=self.api_key, secret=self.secret_key, base_url='https://api2.binance.com') finally: return client And I use this function in another file in a for loop with try block, to log the errors: for trade in trades: try: initial_connect() except Exception as e: error_log(str(e)) So in this case when first connections fails, doesn't go to function (initial_connect) except block and try other url, then in for loop except block get the Exception and write the error log. The question is, How can I edit my code so after a connection failure checks another one, if second fails the for loop try block catch the exception? I just tried with try block in serveral orders and the result was the same. -
swagger with django, can't find module drf_spectacular
I have a django app and I try to implement swagger. But I am stuck on the drf_spectacular.views in the urls.py file. So I installed drf_spectacular. and I am using django version: 3.2.16. I edited the settings.py file: 'drf_spectacular' in the installed_apps and REST_FRAMEWORK={ 'DEFAULT_SCHEMA_CLASS':'drf_spectacular.openapi.AutoSchema', } And I try to import drf_spectacular.views in the urls.py file: from drf_spectacular.views import SpectacularAPIView But I get this error: Unable to import 'drf_spectacular.views'Pylint(E0401:import-error) Question: how to resolve this? Thank you -
Can Django channels receive 30fps video recording from a React Client ? or should I switch another library
I am building a room monitoring app, and I was thinking of sending data using WebSockets and Django channels, but I am not sure if it's a good approach or if Websockets can send/handle 30fps video/image data to the server. -
Best-fit Free Database Choice for small project / Django
I am building a small application that will envolve user authentication and user account info (picture and CV included). I am currently in the early stages, still thinking about the architecture of my system, but I was thinking about using Django in the backend, since it has many authentication features. But owing to the fact I will be storing user info, such as their picture and their CV (which should take up to 200kb per user), I was dubious if the integrated SQLite by Django would be enough. The application is expected to have at max a few hundreds of users. (Is SQLite enough for that?) I was looking for the best free permanent solution for my database, I would appreciate any recommendations given as well as feedback in case my choices of architecture have not been the best. -
Foreign keys in model
I am creating a form to catch registration information into Competitors database. From that database, I want to create group where competitors can be organized and compete again each other. Models.py class Group1(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)], default= 0) rank = models.CharField(max_length=255) point = models.IntegerField class Competitors(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)]) rank = models.CharField(max_length=255) Group = models.ForeignKey(Group1, blank=True, null=True, on_delete=models.CASCADE) Traceback: Exception Type: OperationalError at /admin/appbjjtournament/competitors/ Exception Value: no such column: appbjjtournament_competitors.Group_id I deleted, makemigration, and migrate, but the error still persists. -
How to implement composite primary keys in Django?
Currently, I am using Django version 3.2.3 I have created this model where columns c1,c2 and c3 form composite primary keys class myModel(models.Model): _DATABASE = "my_db" c1 = models.CharField(db_column='c1', primary_key=True, max_length=20) c2 = models.CharField(db_column='c2', max_length=20) c3 = models.CharField(db_column='c3', max_length=20) c4 = models.CharField(db_column='c4', max_length=50) c5 = models.CharField(db_column='c5', max_length=1024) class Meta: managed = False db_table = 'my_table' unique_together = (('c1', 'c2', 'c3'),) ` unique_together is not working Django is considering only c1 as primary key -
Deprecating Django Migrations
I have a long-maintained and large Django project with hundreds and hundreds of migration files at this point. The tests are taking a really long time to run now due to just how many migrations there are to run through before tests begin. I'm wondering if there's a best-practice for deprecating existing migrations and starting fresh, perhaps with the old migration files archived on git but deleted from the working branch, and starting fresh with new 0001's based on the current schema. We've luckily almost never had to roll back – and when we do it's at deploy time and not at some point down the line. Does anyone have any thoughts on what the process for starting migrations fresh on an existing project looks like? -
Django project problem related to login and profile page
I am working on a python Django project. I have a little problem, When I make login through login form after registration. the main page was redirected to login page again despite configuring it to be redirected to profile page. I have searched and tried many solutions and the problem is still existed. Can anyone have an effective solution? Github repo link : https://github.com/khaledomar77/vacc/tree/main -
With Django, is there a way to skip locked rows when performing an update?
I can do MyModel.objects.select_for_update(skip_locked=True) to grab rows that aren't locked. However, if I try to append an .update(some_field='whatever') to that, the UPDATE will sill apply to the FULL result set, including locked rows, and it will wait until the locked rows are freed up before executing (i.e. the select_for_update(skip_locked=True) portion is ignored in the update SQL that is sent). The SQL, in that scenario, will look like: UPDATE "my_model" SET "some_field" = 'whatever' I can get around this by first grabbing the IDs of the rows to update and then sending a separate query to update the rows: ids_to_update = list(MyModel.objects.select_for_update(skip_locked=True).values_list('id', flat=True) MyModel.objects.filter(id__in=ids_to_update).update(some_field='whatever') However, that requires 2 hits to the DB instead of 1 (I'm sure there's a way to do it with 1), and the rows that I'm updating, for the task at hand, have hundreds of thousands to millions of matches, so the 2-step approach is very memory-unfriendly and has high failure potential. Is there a non-raw-sql means of obtaining what I'm after with Django? If I have to resort to raw sql, what would that look like? -
How to send POST request with query params in django tests
I have test.py from rest_framework.test import APITestCase from django.core.files.uploadedfile import SimpleUploadedFile from django.urls import reverse class PostImageTest(APITestCase): def setUp(self) -> None: self.product = Product.objects.create(...) self.sampleImage = SimpleUploadedFile("test_image.jpg", b"binary data", content_type="image/jpeg") def test_with_valid_data(self) -> None: data = { "image":self.sampleImage, "is_featured":true } response = client.post(reverse('images'), data, format='multipart') I want to pass query params like images?product=id to the client.post() method. Also i'm not getting as to how to encode the image and send a POST request. When i tried like this response = client.post(reverse('images'), {'product' : self.product.id}, data=data, format='multipart') It gives me this error TypeError: Client.post() got multiple values for argument 'data' -
CSRF issue in the Django webpage deployed via Kubernetes pod
I am trying to deploy my web application that is written in Django, the image is build and already there, I am just deploying that image into a Kubernetes pod and running it. There is also an nginx pod that runs here. When I am trying to application via the pod and the port exposed through nginx, the error that I am getting is Forbidden (403) CSRF verification failed. Request aborted. I cannot change anything in the application directly. I am not posting the deployment file here as it is too big of a file, and there there is configmap and pv also involved in the backend. The application runs on http at the moment. The application takes me to the login page and after providing credentials it gives me this error. What are some of the things that I can try out. -
Chatgpt integration with Django for parallel connection
I'm using Django framework to have multiple chatgpt connection at same time but it's make complete code halt/down until chatgpt response is back. To encounter this i'm using async with Django channels but still its block Django server to serve any other resource. This is command to run Django server daphne --ping-interval 10 --ping-timeout 600 -b 0.0.0.0 -p 8000 backend.gradingly.asgi:application this is code which is calling chatgpt model = "gpt-4-0314" thread = threading.Thread(target=self.call_gpt_api, args=(prompt,model,context,)) thread.start() this is python code which is sending response to channels async_to_sync(channel_layer.group_send)( f'user_{context["current_user"]}',{ "type": "send_message", "text": json.dumps(json_data) } ) -
Too many redirects on nginx and django applicaiton.Redirecting all http request to https in django, nginx, uwsgi
I'm working on legacy code and trying to configure nginx and ssl certificate of the django based application as I'm not a system adminstrator but I'm trying. I have searched and tried almost all answers on stackoverflow and in the internet but I couldn't solve it. Here nginx configuration file is located on sites-enabled folder not sites-available. nginx version is 1.2.1 and django version is 1.11 # corpmanage.conf # the upstream component nginx needs to connect to upstream django { server unix:/home/corpmanage/corpmanage.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { listen 80; server_name mysite.com; server_name www.mysite.com; client_max_body_size 30m; # Django media location /media { alias /home/corpmanage/mediafiles; # your Django project's media files - amend as required } location /static { alias /home/corpmanage/static-prod; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed uwsgi_read_timeout 600; } } server { # the port your site will be served on listen 443 ssl; # the domain name it will serve for … -
can't redirect user to a certain page after login
so i'm working on a django project, i'm storing users info in phpmyadmin database, the signup process works well, but when a user tries to login , it just reloads the page, i tried to get the values of a record from the table if the username and password are correct (for example, username : ff, pass : ff1, if those are correct, it will display the values from the table, id : 2, email: dd@gg.com, username : ff, password : ff1) views.py : def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] # connect to MySQL database try: cnx = mysql.connector.connect(user='root', password='', database='projet') cursor = cnx.cursor() except mysql.connector.Error as error: print("Failed to connect to database: {}".format(error)) # retrieve user from database query = "SELECT * FROM projetpythonn_user WHERE username=%s AND password=%s" cursor.execute(query, (username, password)) user = cursor.fetchone() print(user) if user is not None: # create Django User object from database user user = authenticate(request, username=user[1], password=user[2]) if user is not None: # login user login(request, user) # redirect to YouTube return redirect('home') # if authentication fails, render login page with error message message = 'Invalid username or password' context = {'message': message} return render(request, 'login.html', context) … -
Range is not working when submit form (django)
we were working with Django and we have got a problem. Range doesn't working. Views.py: from django.shortcuts import render from shop_cookies_app.models import * # Create your views here. def show_catalog(request): response = render(request, "catalog.html", context={'products': Product.objects.all()}) if request.method == "POST": # product_count = request.POST.get("product_count") # product_count = int(product_count) # for i in range(product_count): if "product_pk" not in request.COOKIES: product = request.POST.get('product_pk') response.set_cookie('product_pk', product) return response else: product = request.COOKIES['product_pk'] + ' ' + request.POST.get('product_pk') response.set_cookie('product_pk', product) return response return response HTML: <h1>Каталог</h1> {% for product in products %} <h2>{{ product.name }}</h2> <p>{{ product.desc }}</p> <img src="{{ product.image.url }}" alt=""> <h3 class = "price"><span class = "spanPrice">{{ product.price }}</span> $</h3> <div class = "addAndRemove"> <div class = "buttons"> <button class = "plus">&plus;</button> <button class = "minus">&minus;</button> </div> </div> <form method = "POST" class = "addCookie"> <!-- action="{% url 'catalog' %}" --> {% csrf_token %} <input type="hidden" name="product_pk" value="{{ product.pk }}"> <input class = "count" name = "product_count" value = "1"> <button class = "addToCart">Додати до кошику</button> </form> {% endfor %} <script src = 'https://code.jquery.com/jquery-3.6.4.js' integrity="sha256-a9jBBRygX1Bh5lt8GZjXDzyOB+bWve9EiO7tROUtj/E=" crossorigin="anonymous" defer></script> <script src = '{% static "addCookie.js" %}' defer></script> JavaScript: $(document).ready(function () { // let madeBeforeFunctions = $(".count").val() function changeTimesPlus() { console.log("plus") let a = … -
Django rest framework CSRF_TRUSTED_ORIGINS settings not work
I am setting CSRF_TRUSTED_ORIGINS to make sure, when I send request from localhost it should not validate that. setting.py ... ... CSRF_TRUSTED_ORIGINS = [ ... 'http://localhost', 'https://localhost', 'http://127.0.0.1', 'https://127.0.0.1', ... ] ... ... When I send request it gives me error. curl -k --cert ~/.ssh/cert --key ~/.ssh/key https://localhost/api/v1/key/key/review/ -X PUT -H "Content-type: application/json" -H "Accept: application/json" -d '{"state": "APPROVED"}' --referer https://localhost {"detail":"CSRF Failed: Referer checking failed - https://localhost does not match any trusted origins."} I see localhost is in CSRF_TRUSTED_ORIGINS but still it complain about this. How can I set things where CSRF will be not checked for localhost? -
Structuring Docker Compose for larger Django backends
I'm currently trying to set up my backend with Docker Compose. I successfully managed to integrate my PostgreSQL database, my Django backend service as well as RabbitMQ message broker with each other. What I'm trying to achieve is setting up Celery workers, Celery beat and Celery Flower in separate Docker containers so my Django backend can work with them. The problem: My Celery tasks need to access Django's models and the database. Therefore, I need to copy some backend files into the Celery containers as well. I just don't feel like it's the best way to do that. I need to copy my entire backend, containing my tasks, routines, models, urls and views to get my Celery workers to actually run. What would be the best workflow to realize that? -
Using dj_rest_auth with Django and Azure
I am trying to enable signing in with Azure for a Django app My URL folder is as follows: path("dj-rest-auth/", include("dj_rest_auth.urls")), path("dj-rest-auth/azure/", azure_login.as_view(), name="azure_login"), views.py as follows from allauth.socialaccount.providers.azure.views import AzureOAuth2Adapter from dj_rest_auth.registration.views import SocialLoginView class azure_login(SocialLoginView): adapter_class = AzureOAuth2Adapter client_class = OAuth2Client callback_url = "http://localhost:8000/accounts/azure/login/callback/" I am getting the following error and I understand that I should not pass an Access Token OAuth2Error at /dj-rest-auth/azure/ Error retrieving access token: b'{"error":"invalid_request","error_description":"AADSTS9002339: Unsupported user account for this endpoint. The user is a Microsoft Accounts user, but this app does not have the Microsoft account audience enabled. Either enable Microsoft account support to use the /common endpoint or use the tenanted endpoint to target a specific Azure AD tenant for auth I think this "use the tenanted endpoint to target a specific Azure AD tenant for auth" , we should be able to specify the tenant info somewhere.