Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cookie is not loading to browser
I have this LoginView in django rest framework. class LoginView(APIView): serializer_class = LoginSerializer authentication_classes = [SessionAuthentication, ] def post(self, request): if request.user.is_authenticated: return Response({'message': 'User is already logged in'}, status=status.HTTP_200_OK) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): email = serializer.validated_data.get('username') password = serializer.validated_data.get('password') user = authentication.authenticate(request, username=email, password=password) if user is not None: login(request, user) response = Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK) return response else: return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) else: # If the serializer is not valid, return validation errors return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and this request by axios in vue.js application <script setup> import axios from 'axios' import {ref, onMounted} from 'vue' const email = ref(""); const password = ref(""); axios.defaults.withCredentials = true function login() { axios.post('http://127.0.0.1:8000/api/login/', { username: email.value, password: password.value, })`your text` } </script> when i make request, cookie(session) is load to database, but it is not loaded to browser. Do you have any suggestions why? When i make request from 127.0.0.1:8000/api/login endpoint it works as expected. It doesn't work when i make request from localhost:5173 by axios. -
Use Multi threading in Loop using Python
I have three functions that i want to use async in python in a loop how can I use all 3 functions in a loop using multi-threading I have also mentioned the desired result def sum(a, b): sum= a+b return sum def multi(a, b): mutli= a*b return multi def divide(a, b): divide= a/b return divide final_data = [{'a':1, 'b':3},{'a':7, 'b':5},{'a':6, 'b':4}] for data in final : sum_value = sum(data['a'], data['b'] multi_value = multi(data['a'], data['b'] divide_value = divide(data['a'], data['b'] #desired final output final_data = [{'a':1, 'b':3, 'sum_value':4, 'multi_value':3, 'divide_value':0.34},{'a':7, 'b':5,'sum_value':12, 'multi_value':35, 'divide_value':1.4},{'a':6, 'b':4,'sum_value':10, 'multi_value':24, 'divide_value':1.5}] -
How to create a dynamic menu in Django
The idea is to dynamically create a menu structure with submenus and then expose it in a REST API so frontend can print the menu. Each menu point can have multiple submenu and each submenu can have multiple submenu inside, like: - Menu 1 - Submenu 1.1 - Submenu 1.1.1 - Submenu 1.1.2 - Submenu 1.2 - Submenu 1.2.1 - Submenu 1.2.2 - Menu 2 - [...] What should be the structure of the models and serializers to fulfill the described function? I tried to do it with a single model like: class MenuPoint(models.Model): name = models.CharField(max_length=200) [...] parent_menu_point = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='submenu_point', blank=True, null=True) Thanks! -
How to get callback code of Django OAuth Toolkit use python?
When open http://localhost/o/authorize/?response_type=code&code_challenge=xxx&code_challenge_method=S256&client_id=xxx&redirect_uri=http://127.0.0.1/callback, will be redirected to http://localhost/admin/login/?next=/o/authorize/%3Fresponse_type%3Dcode%26code_challenge%3Dxxx%26code_challenge_method%3DS256%26client_id%3Dxxx%26redirect_uri%3Dhttp%3A//localhost%3A8000/callback, provide user email and password, and after successfully logging into account, will be redirected to http://localhost/callback?code=xxx. I want get callback code in http://localhost/callback?code=xxx. code: import os import requests from urllib.parse import urlparse, parse_qs url = "http://localhost/admin/" auth_url = 'http://localhost/o/authorize/?response_type=code&code_challenge=xxx&code_challenge_method=S256&client_id=xxx&redirect_uri=http://localhost/callback' email = "email" password = "password" session = requests.Session() session.get(url) login_payload = { 'email': email, 'password': password, 'csrfmiddlewaretoken': session.cookies['csrftoken'] } login_req = session.post(url, data=login_payload) print(login_req) print(login_req.url) auth_page = session.get(auth_url) print(auth_page) print(auth_page.url) output: <Response [200]> http://localhost/admin/login/?next=/admin/ <Response [200]> http://localhost/admin/login/?next=/o/authorize/%3Fresponse_type%3Dcode%26code_challenge%3Dxxx%26code_challenge_method%3DS256%26client_id%3Dxxx%26redirect_uri%3Dhttp%3A//127.0.0.1%3A8000/callback Can't get the callback url, like http://localhost/callback?code=xxx. -
MongoDB - How to reproduce the cursor timeout error due to inactivity?
How do I reproduce CursorNotFound error due to 10 minutes of cursor inactivity using PyMongo tools? def sleep_for_minutes(minutes_to_sleep): for i in range(minutes_to_sleep): print(f'{i} sleeping for 1 minute') time.sleep(60 * 1) # Iterate over all documents in the collection for document in collection.find(): print(f'{document} before sleeping') sleep_for_minutes(15) print(f'{document} after sleeping') Context Am iterating a very large Mongo collection. Each document of a collection is quite large as well. Tech stack : MongoEngine, Django My production system is timing out due to CursorNotFound error. Error goes like this : pymongo.errors.CursorNotFound: cursor id <something> not found, full error: {'ok': 0.0, 'errmsg': 'cursor id <something> not found', 'code': 43, 'codeName': 'CursorNotFound'} As per my understanding, there can 2 possible reasons for the same: Session Idle Timeout which occurs at 30 minutes Cursor inactivity timeout after 10 minutes of inactivity To fix and verify the fixes, I am trying to reproduce there errors on a local setup to fix the issue. I do this by using sleep methods. While I am able to reproduce the 1st situation, I am unable to reproduce the situation when cursor times out after 10 minutes of activity. -
Creating a Docker Image for Python Django Backend and NextJS Frontend with Relative URL Interactions
I'm working on a project that consists of a Python Django backend and a NextJS frontend. I'd like to containerize both components into a single Docker image and have them interact with each other using relative URLs. I've tried building the FE docker image and copying built artefacts into BE image, but I'm running into FE is not running. Could someone guide me on the best practices and steps to achieve this integration? Any insights, example Dockerfiles, or configuration tips would be greatly appreciated. Thank you in advance! -
How to configure python django and blockchain?
I need a project or a guide on how to configure Django and blockchain. -
UnboundLocalError: local variable 'par' referenced before assignment:
I want to get the context data into a par variable to be processed into the pipeline context=par. but got this error, how can i fix this ? def index(request): qas_form = QasForms() post_form = MyForm(request.POST) db_context = Context.objects.filter(category=post_form) for con in db_context : par= con.context context = { 'heading' : 'Question Answering', 'data_form' :qas_form, 'form' : post_form, 'Cont' : db_context, } model_name = BertForQuestionAnswering.from_pretrained('./save_model', from_tf=True) tokenizer = BertTokenizer.from_pretrained('./save_model') nlp = pipeline('question-answering', model=model_name, tokenizer=tokenizer) if request.method == 'POST': question = request.POST['question'] par = hasil result = nlp(question=question, context=par) context['question'] = question context['answer'] = result['answer'] return render(request,'qas/index.html',context) I am trying to get a solution to this problem -
I have accidentally deleted views.py file but I have views.pyc file in pycache is it possible to recover views.py file from views.pyc in python 3.11 [duplicate]
I have tried using online decompiler but it doesn't work. I tried softwares like DiskDrill but that file also not showing in those softwares. -
nginx failing to load ssl certificate
The Problem I used mkcert to make local SSL certificates for a Django project using Docker on Windows but get a "This site can’t provide a secure connection" error when I try to access https://localhost. In the Docker log the output was: 2023-09-26 18:19:47 nginx.1 | 2023/09/27 00:19:47 [error] 38#38: *10 cannot load certificate "data:": PEM_read_bio_X509_AUX() failed (SSL: error:0480006C:PEM routines::no start line:Expecting: TRUSTED CERTIFICATE) while SSL handshaking, client: 172.18.0.1, server: 0.0.0.0:443 What I Tried Followed the directions to set up a new Django project with Docker using the Cookiecutter-Django template. Did everything down through the "Run the Stack" section, and the local development website looked good on localhost. Skipped down to "Developing locally with HTTPS" section and followed those directions. The directions don't specify how to change the files from .pem to .crt or .key, but I just renamed them on the first try. The rest of the template website still works fine, but when I go to https://localhost I get a "This site can’t provide a secure connection" error. I tried changing: -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- to -----BEGIN TRUSTED CERTIFICATE----- ... -----END TRUSTED CERTIFICATE----- in a text editor and still got the same error messages as above. I … -
Can't install mysqlclient on Alpine Linux
I'm trying to run a Django server on a Docker image based on python:3.11-alpine. The app uses a remote MySQL database. When installing the pip dependencies I get this error: 16.70 ERROR: Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects ------ failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1 These are the installed apk packages: gcc libc-dev linux-headers nodejs mysql mysql-client mysql-dev Is this related to the fact I'm using Alpine Linux? Did I install the wrong drivers. I tried adding the mysql-dev package but the error didn't change. I also saw this GitHub thread, and I fear it's just impossible to use Alpine. -
Find all the ManyToManyField targets that are not connected to a ManyToManyField haver
Suppose I have 2 models connected by a many to many relation from django.db import models class Record(models.Model): name = models.CharField(max_length=64) class Batch(models.Model): records = models.ManyToManyField(Record) Now I want to find all the Records that are not connected to a Batch. I would have thought it would be one of Record.objects.filter(batch=[]) #TypeError: Field 'id' expected a number but got []. Record.objects.filter(batch__count=0) Record.objects.filter(batch__len=0) #FieldError: Related Field got invalid lookup: count Or something like that. But those don't work. They seem to act like they expect batch to be singular rather then a set. What is the correct way to do this? -
django_celery_results Logs Spill Secrets
I am using Celery tasks with my Django application. It has been configured to use django_celery_results as a backend for logging task results. I am however experiencing some issues. The connection between the broker, Django and Celery is secure. This is no issue. I am sending mails with celery, I am not storing the credentials on the celery side, nor is it possible to do so as they are provided dynamically. However, the credentials I pass to the celery task get logged by django_celery_results. Is there a way to omit these credentials from the task results? I have though about encrypting before sending it to the celery task, but maybe there is a better way. -
Django with multiple websites, shared apps, one domain, Apache server
The goal is to have several websites running on one domain, with Apache and wsgi What I currently have is one virtualhost configuration: WSGIScriptAlias /site1 /opt/django/wsgi.py process-group=site1 Since there is only one project, there is only one wsgi.py, so all apps are running under domain.com/site1, i.e. site2 is available at domain.com/site1/site2 which is not what I want. The desired config is : site1 reachable at domain.com/site1 site2 reachable at domain.com/site2. Also, there are some shared apps between site1 and site2. project/urls.py configuration: path('', include(('site1.urls', 'site1'), namespace='site1')), path('/site2', include(('site2.urls', 'site2'), namespace='site2')), -
How do I log out any user when using the cache session backend?
I am building a form into django admin where I can submit a user id and the system is expected to log the user out. I cannot do django.contrib.auth.logout() because it does not take a user id as a parameter. I also cannot query against django.contrib.sessions.models.Session because I am using the django.contrib.sessions.backends.cache session engine. -
custom id not showing up in paypal webhook
So I'm trying to put in a custom id (order id) in my paypal order so it get's returned to me in my paypal webhook but I cannot find it in my webhook. This is my order code. payment = paypalrestsdk.Payment({ "intent":"sale", "payer":{ "payment_method":"paypal" }, "redirect_urls":{ "return_url":"http://localhost:3000/order/success", "cancel_url":"http://localhost:3000/order/cancel" }, "transactions":[{ "item_list":{ "items":items }, "amount":{ "total":price, "currency":"EUR" }, "description":"This is the payment transaction description.", "custom_id": order_data["products"][0]['order'] }] }) if payment.create(): return JsonResponse({'status': 'success', "url": payment.links[1].href}) else: return JsonResponse({'status': 'error'}) Everything in this code works except for the custom id which i dont get back in my webhook. Am I missing something. Extra note. Just tried this. payment = paypalrestsdk.Payment({ "intent":"sale", "payer":{ "payment_method":"paypal" }, "redirect_urls":{ "return_url":"http://localhost:3000/order/success", "cancel_url":"http://localhost:3000/order/cancel" }, "transactions":[{ "item_list":{ "items":items }, "amount":{ "total":price, "currency":"EUR" }, "description":"This is the payment transaction description." }], "custom_id": order_data["products"][0]['order'] }) if payment.create(): return JsonResponse({'status': 'success', "url": payment.links[1].href}) else: return JsonResponse({'status': 'error'}) I moved the custom id out of the transactions key, it was an oversight of me but now my payment does not get created in the browser I receive {status: error} instead of the payment url of paypal. All help is greatly appreciated -
How do I avoid django URL KeyError but keep my site's URL struture?
I am new to programming with Django and recently started a Django web app with only one "food" app/section that leads to the food app URLs so my base url.py looks similar to this. urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), ] Now I want to add/include a new "water" section for the water app urls.py similar to this urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), path('', include('water.urls')), ] However, when I click on the water URLs I get a KeyError as the water URLs are being applied to the food.urls. My web app is already in production and I don't want to change the URL structure as this is bad for SEO. Therefore, what is the best solution to keep the current URL structure for both the food.urls and water.urls? For example, mysite.com/a-food-url and mysite.com/a-water-url. or is the only solution to change the URL structures to: urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('food/', include('food.urls')), path('water/', include('food.urls')), ] where the URLs will be mysite.com/food/a-food-url and mysite.com/water/a-water-url? -
How to use transaction with async function in Django?
Here is code class Utils: @sync_to_async def get_orders(self): orders = Order.objects.all() return [orders] @sync_to_async def get_sellers(self): sellers = Seller.objects.all() return [sellers] class Orders(View, Utils): async def get(self, request): orders = asyncio.ensure_future(self.get_orders()) await asyncio.wait([orders]) print(orders.result()) return render(request, 'orders.html') Here is logs of error Traceback (most recent call last): File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\base.py", line 192, in _get_response wrapped_callback = self.make_view_atomic(callback) File "C:\Хранилище говна\pythonProject1\venv\lib\site-packages\django\core\handlers\base.py", line 350, in make_view_atomic raise RuntimeError( RuntimeError: You cannot use ATOMIC_REQUESTS with async views. I'm trying to get list of orders from database(PostgreSQL) in async function, but it rasie RuntimeError. I tried to detect where this code raise error by debuging, but "get" function in Orders didn't call at all. Tried find info in django docs, no info. Can some one help me with this one? -
couldn't serve static file for a django app (apache - wsgi )
i have the projected is named Portfolio which is my main page. And i have created an app named experiences on this project. On dev server i'm able to serve static files for both. but on production, i'm only able to serve for main page (project) and not for the app. I have the 404 Not Found error. i have make the collecstatic. I have a static dir on each app (and project). And i'm using apache with wsgi module. i have this conf on settings file : STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "Portfolio/static") ] Below the arch : src/ |-- Experiences | |-- __pycache__ | |-- migrations | | `-- __pycache__ | |-- static | | `-- Experiences | | |-- assets | | | |-- fonts | | | `-- img | | `-- css | `-- templates | `-- Experiences |-- Portfolio | |-- __pycache__ | |-- static | | `-- Portfolio | | |-- assets | | | |-- fonts | | | `-- img | | `-- css | `-- templates | `-- Portfolio `-- staticfiles |-- Experiences | |-- assets | | |-- fonts | | `-- … -
Getting "field does not exist" when running pytest
I added a slug field to a model and re-created the migrations from the initial one. When I try to run a unit test for this model, I always get the django.db.utils.ProgrammingError: column courses_course.slug does not exist. I tried to undo the migration with the code below, but it still doesn't work. python manage.py migrate courses zero python manage.py migrate -
Select a valid choice. That choice is not one of the available choices with django
Hi guys basically I'm working with a license generator with django, i have a javascrit logic so that i can filter users by company name and create licenses for those users, i would like to add an option "select all users" so that i can create multiple licenses for all the users in a specific company, i have something like this: I use dropdowns for the companies and the users {% extends "main_page_layout.dj.html" %} {% block content %} <div class="control"> <a href="/user/management/"> <div class="button">Generate user</div> </a> </div><br> <form action="/avt/generate/" method="post" id="avt-form" data-users-url="{% url 'load_users' %}" >{% csrf_token %} <div class="field"> <label class="label">Company</label> <div class="control"> <div class="is-fullwidth"> <select class=" select2 {% if form.errors.company %} is-danger {% endif %} " type="text" name="company" id="company" value="value={{form.company.name}}">> <option value=" ">Select a company first</option> {% for company in companies %} <option>{{ company.name }}</option> {% endfor %} </select> </div> </div> </div> {% if form.errors.company %} <p class="help is-danger">{{ form.errors.company }}</p> {% endif %} {% include 'users_dropdown_list_options.html' %} <div class="field"> <label class="label">Expire Date</label> <div class="control"> <input class="input avt_datepicker {% if form.errors.expire_date %} is-danger {% endif %} " type="text" placeholder="YYYY-MM-DD e.g. '2000-01-01'" name="expire_date" value="{{ form.expire_date.value | default_if_none:'' }}"> </div> {% if form.errors.expire_date %} <p class="help is-danger">{{ form.errors.expire_date }}</p> {% … -
How do I avoid django URL KeyError but keep my site's URL struture?
I started a Django web app with only one "food" app/section that leads to the food app URLs so my base url.py looks similar to this. urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), ] Now I want to add/include a new "water" section for the water app urls.py similar to this urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='home'), path('', include('food.urls')), path('', include('water.urls')), ] However, when I click on the water URLs I get a KeyError as the water URLs are being applied to the food.urls. My web app is already in production and I don't want to change the URL structure as this is bad for SEO. Therefore, what is the best solution to keep the current URL structure for both the food.urls and water.urls? For example, mysite.com/a-food-url and mysite.com/a-water-url. -
How can I use django-filter's DateTimeFromToRangeFilter with Graphene?
I'm attempting to use an instance of django-filter's DateTimeFromToRangeFilter in conjunction with a custom FilterSet. However, this does not work when I attempt to do the following: class CustomFilterSet(FilterSet): modified = django_filters.IsoDateTimeFromToRangeFilter() class Meta: fields = "__all__" model = Custom This does not result in additional fields or annotations being created, like I'd expect based on the docs. Something like: f = F({'modified_after': '...', 'modified_before': '...'}) If I inspect the single field (modified) which has been added to my DjangoFilterConnectionField, I see the following: {'creation_counter': 395, 'name': None, '_type': <String meta=<ScalarOptions name='String'>>, 'default_value': Undefined, 'description': None, 'deprecation_reason': None} So, how do I configure this filter such that I can write a query like the following? query { allTheSmallThings( modified_before: "2023-09-26 17:21:22.921692+00:00" ) { edges { node { id } } } } -
how i can filter with foregin key
0 I have a football stadium booking site -- the user logs in and then selects the stadium he wants to book and then selects the day and how much he wants to book the canned (an hour or two hours, etc.*) example: user John booked the stadium X on the day of 5 at 10 to 12 I want to make sure that there is no reservation at the same stadium, the same day and the same time, and if there is a reservation at the same data, he does not complete the reservation when i try to filtter in models with Foreign key pitche filter = OpeningHours.objects.filter(made_on=self.made_on,pitche=self.pitche,period = self.period).filter(Q(from_hour__range=in_range) | Q(to_hour__range=in_range)).exists() the error happens (relatedobjectdoesnotexist) OpeningHours has no pitche. my models is : class Pitche(models.Model): Name = models.CharField(max_length=50) city =models.CharField(max_length=50) photo = models.ImageField(upload_to='photos') price = models.DecimalField(max_digits=5,decimal_places=2) location = models.CharField(max_length=500) name_of_supervisor = models.CharField(max_length=50) phone_of_supervisor = models.CharField(max_length=11) manager = models.ForeignKey(Manager,on_delete=models.DO_NOTHING) class OpeningHours(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) pitche = models.ForeignKey(Pitche,on_delete=models.DO_NOTHING) made_on = models.DateField() period = models.CharField(max_length=50,choices=period) from_hour = models.TimeField() to_hour = models.TimeField() timing = models.CharField(max_length=50,choices=timing) def __str__(self): return f"{self.pitche}-{self.from_hour} to {self.to_hour}" def clean(self): if self.from_hour == self.to_hour: raise ValidationError("Wrong Time") if self.made_on <datetime.date.today(): raise ValidationError("InVaild Date") ##################### in_range = (self.from_hour, self.to_hour) filter … -
exec ./start.sh: no such file or directory
I have a Django project that runs in a Docker container within docker-compose.yml with postgresql, pgadmin4 and redis. I have start.sh script that make and run migrations: start.sh: #!/bin/bash # Creating migrations if they are python manage.py makemigrations # Apply migrations python manage.py migrate After building the image and runing docker-compose up command django project give me an error: exec ./start.sh: no such file or directory but my start.sh file is in the same directory where Dockerfile and docker-compose.yml are. PostgreSQL, pgadmin4 and Redis runs successfully. How to solve this problem? My system is Windows 10. Dockerfile: FROM python:3.11.3-alpine ENV PYTHONBUFFERED=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt --upgrade COPY . . COPY start.sh . RUN chmod +x start.sh ENTRYPOINT [ "./start.sh" ] EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml: services: api: image: meduzzen-backend-api container_name: django tty: true stdin_open: true volumes: - .:/code - ./code:/apps ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis postgres-db: image: postgres:latest container_name: postgres_db ports: - "5432:5432" volumes: - data:/var/lib/postgresql/data env_file: - .env networks: api-db-redis: # Have access the database using pgadmin4 ipv4_address: 172.24.0.6 pg-admin: image: dpage/pgadmin4:latest container_name: pg_admin env_file: - .env ports: - "5050:5050" networks: …