Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switching from WSGI to ASGI (Gunicorn + Uvicorn) in Django Production – Site Not Loading
I recently built a Django application using Django Channels for WebSocket support. My asgi.py is set up for handling both HTTP and WebSocket connections, and everything works perfectly in development using Daphne and Uvicorn. In Productin initially, my app was running on Gunicorn (WSGI), but since I need WebSocket support, I switched to Uvicorn (ASGI). To achieve this, I modified my gunicorn.service file to use UvicornWorker instead of the default WSGI worker. I encountered the error: Django can only handle ASGI/HTTP connections, not lifespan. To fix this, I created a custom worker class based on a solution from older Stack Overflow answers: from uvicorn.workers import UvicornWorker class MyUvicornWorker(UvicornWorker): CONFIG_KWARGS = {"lifespan": "off"} Then, I updated my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/my_project ExecStart=/home/django/my_project/venv/bin/gunicorn \ --limit-request-line 8190 \ --access-logfile /var/log/gunicorn/access.log \ --error-logfile /var/log/gunicorn/error.log \ -k project.uvicorn_worker.MyUvicornWorker \ --workers 3 \ --env DJANGO_SETTINGS_MODULE=project.settings.base \ --bind unix:/run/gunicorn.sock \ --log-level=debug \ project.asgi:application ExecReload=/bin/kill -HUP $MAINPID [Install] WantedBy=multi-user.target After restarting gunicorn.service, everything appears to be running fine, gunicorn.service and nginx.service are active ping mysite.com is working No errors in /var/log/gunicorn/error.log -
Django: Migrations not detecting changes after manually deleting migration files in production app
What happened: I had an app called app with migrations up to 0012. I mistakenly deleted migration files, including 0001_initial.py. Now, when I run python manage.py makemigrations app, no new migration files are detected, even though I have made changes to the models. This issue is persisting even in a newly created app called comments, where no migration files are being detected either, despite having added new fields to the models. What I’ve tried: I’ve ensured that the app is listed in INSTALLED_APPS. I’ve run python manage.py makemigrations app to generate migration files, but no changes are detected. I can’t drop the database as it is a production environment, and I need to preserve existing posts and data. What I need help with: I need to figure out how to properly reset or re-sync the migrations without losing any production data. For now i have empty migrations folder with init.py innit that doesnt create any migration file. Specifically, how do I: Recreate missing migrations after deleting files manually (i.e., to match the state of the database, which still has migrations applied up to 0012). Ensure that any new apps or changes to models are correctly detected and have corresponding migration … -
Encrypt and decrypt the data that can be seens in the Swagger of the Django when making any Rest API
I am making a django project and using DRF to make the API's also using the Swagger UI to make it interactive for the backend testing Image of the Swagger Request which can be seen So in this image i want to make the "-d" to be encrypted and also in the frontend when i want to encrypt the data when you go see it in the networks also decrypt the data when API is using making the CRUD operations with the database. I am using the serializers here. How can i implement the encryption and make changes in the serializers or the curl "-d" option so that i can only see the encrypted Data in swagger. Shall i make a middleware to encrypt the data? How i can also encrypt the data whenever my response is being given by the API. So that on frontend when using inspect it is encrypted Data. Thanks in Advance and for your suggestion to make my project better and secure!! -
Can't read "csrftoken" from cookies (Django)
I am working on a Django backend. The backend is deployed on Render, and I am testing email validation logic by sending OTP but for that i need to send "csrftoken" for the POST request. At first the cookie was not getting set in cookies in firefox (but was getting set it chrome), since it was asking for the cookie to have partitioned attribute set, since django does not yet support it, i had to include a custom middleware to do it. Now currently for some reason i am not able to read the csrftoken. views.py: @ensure_csrf_cookie def register(request): if request.method == "POST": ...... elif request.method == "GET": return JsonResponse({"message": "GET request handled"}, status=200) prod.py: from .common import * CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:8001", "http://localhost:8001", "https://forkmemaybe.github.io/temp/", ] CSRF_COOKIE_SAMESITE = "None" CSRF_COOKIE_SECURE = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8001", "http://localhost:8001", "https://forkmemaybe.github.io/temp/", ] SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_SECURE = True HTML page i am making requests from URL: [http://127.0.0.1:8001/live.html] ...... <script> function getCookie(name) { let cookieValue = null; console.log(document.cookie); if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the … -
Get mutual settlements from records. using SQL
How to Generate Mutual Settlements for a Specific Employee in SQL? I have a table where I track mutual settlements for employees. The table contains the following columns: employee_id: The ID of the employee amount: The transaction amount (can be positive or negative, based on the reason) reason: A description of the transaction created_at: The timestamp when the transaction occurred I need to generate a report showing how an employee's balance changes over time, like this: Start Balance Change Final Balance 0 +50 50 50 -15 35 35 +10 45 45 -5 40 My SQL Query (Not Working as Expected) I tried using a window function to calculate the previous balance, change, and final balance, but the results are incorrect: SELECT id, employee_id, COALESCE(LAG(SUM(amount)) OVER (ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS prev_amount, amount AS change, SUM(amount) OVER (ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS final_amount FROM settlement_settlement GROUP BY id ORDER BY created_at; -
Why is request.user not being populated in Django when using custom JWT middleware?
I'm implementing custom JWT authentication in Django and I'm using middleware to decode the JWT token and assign request.user to the authenticated user. However, when I try to access request.user inside my view or decorator, it's not being populated, even though the middleware is correctly decoding the token and assigning it. class JWTAuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check for the presence of the JWT in the Authorization header # Debugging the Authorization header print(f"Authorization Header: {request.headers.get('Authorization')}") auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header.split(" ")[1] try: user = decode_jwt_token(token) print(f"JWT Decoded Payload: {user}") # Print decoded token request.user = user # Assign the user here request._force_auth_user = user print(f"JWT Middleware: User assigned: {request.user.email} - {request.user.role}") except jwt.ExpiredSignatureError: print("JWT Middleware: Token expired") except jwt.DecodeError: print("JWT Middleware: Invalid token") response = self.get_response(request) print( f"JWT Middleware (After Response): {request.user if hasattr(request, 'user') else 'No User'}" ) # Debug after response return response class InviteUserView(APIView): """Invite a user via email with role assignment""" @bypass_csrf @authorize @role_required([UserRoleEnum.SUPER_ADMIN.value]) def post(self, request): print(f"DEBUG: User in request inside view - {getattr(request, 'user', 'No User')}") serializer = UserInvitationSerializer(data=request.data) try: if serializer.is_valid(): invitation_link = send_invitation(request, serializer, request.user) response = create_response(201, ResponseCodes.SUCCESS, … -
Bootstrap 4 Navbar Toggler Button Appears but Does Not Expand the Menu
I am using Bootstrap 4 for my Django project, and my navbar toggle button appears when the screen size is reduced. However, clicking the button does nothing—the menu does not expand or collapse. Here is my code:(base.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SkyLog - {% block title %}Home{% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="icon" type="image/svg+xml" href="{% static 'images/airplane-svgrepo-com.svg' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="#"><b>SkyLog</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link mx-3 active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">LogBook</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">Search</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">Analytics</a> </li> </ul> </div> </div> </nav> <div class="container mt-4"> {% block content %} <!-- Page content goes here --> {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha384-fQybjgWLrvvRgtW6jwXnDdRjjvQcTbLrR9fOr5bT8i4QgFO44FtfFZ4lAAey7m70" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-Uo5Xkna0FgAq06YLyj2hx5Lu5A5xN1W6zVnHJvaApGsXOMA5ol3KSk2EjPmhoUmR" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy5E2fHk1hCwLlG5OWv9F7JqxMk5DQCVRHsENBO" crossorigin="anonymous"></script> </body> </html> I have included Bootstrap 4.3.1 CSS and JS from a CDN. I used data-toggle="collapse" and data-target="#navbarNav" on the button. … -
DRF allauth email authentication unique constraint failed
I am trying to implement an email authentication with djangorestframework, dj-rest-auth and allauth. Here is my custom user model class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Here is my settings.py ... AUTH_USER_MODEL = "users.CustomUser" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_LOGIN_METHODS = {'email'} ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ... It registers a new user as expected if the there is not an existing user with the same email, but if I try to create an user with an email that has already been registered, I got this error: django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I expected allauth to handle this error since it does with username authentication. Am I missing something? Should I handle this error manually? -
Trying to pull Google Reviews with Python/Django, failed by ChatGpt, Claude and DeepSeek
I have a django app where user sign’s in with google and gives permission to access google business profiles to pull reviews. I store those google tokens in my database. But when I try to pull google reviews, it can not pull. It can not even get google business profile data. I tried Chatgpt, Claude, Deepseek but failed. Here is my django and python code what I tried before. Google sign in code in Django: def google_integration(request, location_id): app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') params = f'?location={location_id}&redirect_url={request.META.get("HTTP_REFERER")}' params += f'&gb_url={gb_url}' params += f'&gb_incentive={gb_incentive}' return redirect(app_url + reverse('business:google_integration_from_origin') + params) #@subscribed_business_only def google_integration_from_origin(request): location_id = request.GET.get('location') previous_page = request.GET.get('redirect_url') gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') if not location_id: messages.error(request, 'Location not found') return redirect('dashboard:index') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL flow = Flow.from_client_secrets_file( 'client_secrets.json', scopes=['https://www.googleapis.com/auth/business.manage'], redirect_uri=app_url + reverse('business:google_callback') ) auth_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true', prompt='consent' # Forces Google to show the permission screen again ) request.session['google_auth_state'] = state request.session['location_id'] = location_id request.session['google_callback_redirect_url'] = previous_page or reverse('dashboard:index') request.session['gb_url'] = gb_url request.session['gb_incentive'] = gb_incentive return redirect(auth_url) # @subscribed_business_only def google_callback(request): state = request.session.get('google_auth_state') location_id = request.session.get('location_id') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url … -
collaborative plateform Real time cursor problem in web socket
My problem is a cursor position in my project. When the web socket open and at setTimeout send code to the another connection room. then my cursor position and text is not showing currently and my cursor go back. and i am facing experience like gaming ping issues., i am also keep track cursor. My script code is: //This is onmessage if (data.action === "code_update") { if (editor.getValue() !== data.code) { // Prevent redundant updates const cursorPosition = editor.getCursorPosition(); console.log("Cursor: ",cursorPosition) editor.setValue(data.code,-1); // Update without moving cursor to the end editor.moveCursorTo(cursorPosition.row, cursorPosition.column); } } // Send code updates on editor changes (debounced to reduce spam). let debounceTimeout; let lastSentCode = ''; editor.session.on("change", function () { clearTimeout(debounceTimeout); debounceTimeout = setTimeout(() => { const currentCode = editor.getValue(); if (currentCode.trim() !== lastSentCode.trim()) { sendCodeUpdate(currentCode); lastSentCode = currentCode.trim(); // Update the last sent code } },100); }); // Send code updates on the WebSocket async function sendCodeUpdate(code) { const cursorPosition = editor.getCursorPosition(); // Store cursor position await chatSocket.send(JSON.stringify({ action: "code_update", username: username, code: code, cursor_position: cursorPosition, // Send cursor position })); } please check and help me -
how to refer back to the model from utils.py in a Django object
I'm trying to create a field in a django model, that forces a unique value in the model. I'm using utils.py to generate the value. The error I get is: File "/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/utils.py", line 2, in <module> from MCARS.models import Profile ImportError: cannot import name 'Profile' from partially initialized module 'MCARS.models' (most likely due to a circular import) (/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/models.py) Here's my model: class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberid = models.CharField( max_length = 10, blank=True, editable=True, unique=True, default=utils.create_new_ref_number() ) avatar = models.ImageField(upload_to="static/mcars/img/avatars", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) here's my utils: import random from MCARS.models import Profile def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000000000, 9999999999) if not Profile.objects.filter(memberid=unique_ref): not_unique = False return str(unique_ref) how do I tell the utils.py to refer back to the model to check if the value is unique and if not, to try again? Thanks! -
Issue with cron django
I am trying implementing django crontab into my django project. Everything works fine except logging, in the docker container folder with logging does not exist. My settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', 'core', 'crypto', ] CRONJOBS = [ ('* * * * *', 'crypto.management.commands.run_cron_job', '>> /var/log/cron.log 2>&1'), ] Cron task from django.core.management.base import BaseCommand from django.utils.timezone import now import logging logging.basicConfig(filename="/var/log/cron.log", level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **kwargs): logging.info(f"Cron ran at {now()}") self.stdout.write(f"Cron ran at {now()}") Docker compose file version: '3.8' services: db: image: postgres container_name: postgres_server ports: - "5432:5432" networks: - local_network volumes: - db_data:/var/lib/postgresql/data environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} pg_admin: image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL} PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD} networks: - local_network ports: - "8080:80" depends_on: - db web: working_dir: /app container_name: app image: python ports: - "8000:8000" networks: - local_network command: > bash -c " apt-get update && apt-get install -y cron vim && mkdir -p /var/log && touch /var/log/cron.log && chmod 777 /var/log/cron.log && service cron start && pip install -r requirements_test.txt && pip install -r requirements_dev.txt && python manage.py makemigrations && python manage.py migrate && python manage.py crontab add && python manage.py createsuperuser --noinput && python manage.py runserver 0.0.0.0:8000" volumes: … -
Django Scraper Matching Issue: match_maker Only Returns 4 Members Instead of 150
Question: I'm working on a Django project that uses Scrapy to scrape member profiles from a website. The scraped data is processed by a method called match_maker. However, I'm encountering an issue where match_maker only returns 4 members, despite having 150 members in the database (excluding 3 staff members). Details: Database: Contains 153 members; 3 are staff members, leaving 150 regular members. Profile Types: Each member has a profile_type of either 'Man', 'Woman', 'Trans', or 'Couple'. Issue: In the match_maker method, there's a loop that processes rooms and assigns them to members. A set named used_rooms is used to track assigned rooms to ensure each room is only assigned once. The relevant code snippet is: if room["username"] in used_rooms: continue When this condition is active, only 4 members are returned. If I comment out this check, the method processes all 150 members, but the number of available rooms exceeds one million, which is incorrect. Objective: I need each room to be assigned to only one member, ensuring no more than one member owns a particular room. I'm looking for guidance on how to resolve this issue so that match_maker correctly processes all 150 members without assigning multiple members to the … -
Django Streaming Video / Audio - RangedFileResponse
Folks, For ages I've been using RangedFileResponse to enable streaming (particularly with Safari), but to allow ranged streaming with Django. (Please note, it's been forked quite heavily, the one I've been using is from https://github.com/devmonkey22/django-ranged-fileresponse. Now, I've been always wondering if there was a more up-to-date way to do this, since there hasn't seemed to be a better answer? I just recently started to use django-extensions more fully, and bumped into the Werkzeug extensions when I enabled SSL for the Dev environment. But I also found that Werkzeug can help with the Ranged file response. This is what I came up with, and it seems to be faster than using the django-ranged-fileresponse. Sometimes significantly faster. from werkzeug.http import parse_range_header from django.http import FileResponse, HttpResponseNotAllowed, HttpResponseBadRequest def stream_video(request, fqpn, content_type="video/mp4"): file_size = os.path.getsize(fqpn) if request.method != 'GET': return HttpResponseNotAllowed(['GET']) if request.is_secure(): range_header = request.META.get('HTTPS_RANGE') else: range_header = request.META.get('HTTP_RANGE') ranges = parse_range_header(range_header) if not ranges: return FileResponse(open(fqpn, 'rb')) # For simplicity, handle only single range requests start, end = ranges[0] with open(fqpn, 'rb') as file_to_send: file_to_send.seek(start) data = file_to_send.read(end - start + 1) response = FileResponse(data, content_type='application/octet-stream') response['Content-Length'] = len(data) response['Content-Range'] = f'bytes {start}-{end}/{file_size}' response['Accept-Ranges'] = 'bytes' response.status_code = 206 # Partial … -
Why transition-duration along with transform scale could not be set via js/css? (But could be set via DevTools)
The problem is setting transition-duration along with transform scaling results in transformation with zero duration (although style shows up in DevTools as expected) if being set through css, js or html style. But results correctly if being set manually through browser DevTools (changing aforesaid style in DevTools). The MRE is just: <div style="transform: scale(~times~); transition-duration: ~time~"> sandy </div> Working through Django latest version. In the meantime, opacity trasition-duration works as expected, so the trouble is about scaling. Checked the issue in firefox, edge and chrome Though the MRE works as expected in fiddle -
why request.post only send csrftoken, not my form's field
im new in django and this is my first project. I create a loginform and when I want to use it, It just send csrftoken not my requierd fields this my form: class MyLoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput()) and this is my views: def login_view(request): if not request.user.is_authenticated: if request.method == "POST": form = MyLoginForm (request.POST) print(request.POST) if form.is_valid(): print('valid!!!') data = form.cleaned_data username = data["username"] password = data["password"] try: account = Account.objects.get(username=username) except Exception as error: print(error) return HttpResponseRedirect(reverse("login")) if account is not None: if password == account.password: login(request, account) return render(request, "home.html", {"account": account}) else: return HttpResponseRedirect(reverse("login")) else: return HttpResponse(f"<h2>No such a User : {username}</h2>") else: print(form.errors) # Print form errors to debug return HttpResponse("form is not valid") else: form = MyLoginForm(request.POST) return render(request, template_name="login.html", context={"form": form}) else: return HttpResponseRedirect(reverse("home")) and this is my html: <form method="post" action = ""> {% csrf_token %} <div class="form-group"> <label for="username">نام کاربری</label> <input type="text" id="username" name="username" required> </div> <div class="form-group"> <label for="password">کلمه عبور</label> <input type="password" id="password" name="password" required> </div> <button type="submit">ورود</button> </form> and Im getting this: <QueryDict: {'csrfmiddlewaretoken': ['rxjKh3oNsgdRBtT20rT1uVWLw2qOR2oQqjOct9iPhEsnJiHAUVgriiDj3Tg1qoog']}> usernameThis field is required.passwordThis field is required. -
How to store images
I store various image files in my media file in the Django framework and I use MongoDB to store my data, but as far as I understand, storing photos directly in MongoDB is not a preferred method. What path should I follow at this point to get a more efficient result? I thought about using tools like AWS S3, but I'm not sure if this is the right way, and I'm inexperienced in data management. I would appreciate it if you could briefly explain how to do it. -
How to Dockerize a Django and Vite app in a Single docker-compose Setup?
I have a Django project that connected with a Vite app, and I’m trying to set up Docker Compose to run both together. However, I’m facing issues while building and running the containers. I'm using vite for installing the tailwind and everything is working fine without docker, I already configure the django project in docker, but need to configure the frontend vite app which is called webapp, it's in the same directory as django. Goal: Django backend → runs on 8000 Vite frontend → runs on 3000 and connects to Django Both services should run using docker-compose up --build However, when I try to run docker-compose up --build, I get several erros, or even the docker will build without the vite working. Issue: When running docker-compose up --build, I get various errors, including: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory Vite does not start properly in the container, even if Django works. My file directory: For_Testing_Purpose-1/ django_project ┣ __pycache__ ┣ asgi.py ┣ settings.py ┣ urls.py ┣ wsgi.py ┗ __init__.py homepage ┣ migrations ┣ __pycache__ ┣ admin.py ┣ apps.py ┣ models.py ┣ tests.py ┣ urls.py ┣ views.py ┗ __init__.py templates ┗ home.html webapp ┣ … -
Select2 Drop downs not loading in multi-modals django page
I have an issue with a Django front I'm trying to implement. I'm using select2 to show dropdown menus in which I can search in. The problem is that I have two different modals, each has it's dropdown menus. When I click on the button that shows the first modal, dropdown menus data load and the search bar appears and is functional. However, when I quit the first modal (no page reload) and I click on the button that shows the second modal, the dropdown menus are empty, and the search bar doesn't show. Here the HTML code I use for this page : {% extends 'listings/base.html' %} {% block content %} {% load static %} <script type="text/javascript"> $(document).ready(function () { $('#createCustomerModal').on('shown.bs.modal', function () { console.log("Modal create opened"); $('.django-select2').djangoSelect2('destroy'); $('.django-select2').djangoSelect2({ dropdownParent: $('#createCustomerModal .modal-content') }); }); $('#modifycustomerModal').on('show.bs.modal', function (event) { console.log("Modal modify closed"); var button = $(event.relatedTarget); var affectation_id = button.data('id'); var modal = $(this); $.ajax({ url: "{% url 'customer-update' %}", type: 'GET', data: { 'id': affectation_id }, success: function (data) { modal.find('.modal-body').html(data); $('.django-select2').djangoSelect2('destroy'); $('.django-select2').djangoSelect2({ dropdownParent: $('#modifycustomerModal .modal-content') }); } }) }); }); </script> <div class="d-flex justify-content-between align-items-center mb-3"> <h1>Customer list</h1> </div> <div class="d-flex justify-content-between align-items-center mb-3"> <form method="post" enctype="multipart/form-data"> {% … -
Ubuntu + Apache (mod_wsgi) + Django - HTTPSConnectionPool NewConnectionError - [Errno 111] Connection refused
Environment: Ubuntu 24.04, Apache 2.4 (+ libapache2-mod-wsgi-py3 5.0.0-1build2), Python 3.12 (+ requests 2.32.3), Django Admin 5.1.6 Error: I have connected a Django project through Apache (mod-wsgi) and it is running fine (at 'https mysub.mydom.com/myapp') except the requests.post in the python codes failing with: HTTPSConnectionPool(host='mysub.mydom.com', port=443): Max retries exceeded with url: /myapp/api/v1/endpoint (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7191eb589e50>: Failed to establish a new connection: [Errno 111] Connection refused')) 'https mysub.mydom.com/myapp/api/v1/endpoint' is working (200) from the browser. "Apache Full" is allowed from ufw. mysub.mydom.com.conf (for Apache sites-enabled alongwith mysub.mydom.com-le-ssl.conf generated by certbot): Define wsgi_daemon "mydjango_proc" <VirtualHost *:80> ServerName mysub.mydom.com ServerAdmin webmaster@mydom.com DocumentRoot /home/myuser/my_django/my_project <IfModule mpm_itk_module> AssignUserId myuser www-data </IfModule> ErrorLog /home/myuser/my_django/log/my_project.error.log CustomLog /home/myuser/my_django/log/my_project.access.log common Alias /static /home/myuser/my_django/my_project/static <Directory /home/myuser/my_django/my_project/static> Require all granted </Directory> <Directory /home/myuser/my_django/my_project/my_project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/myuser/my_django/my_project> Require all granted </Directory> <IfDefine !wsgi_init> WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup %{GLOBAL} WSGIDaemonProcess ${wsgi_daemon} python-home=/home/myuser/my_django/sklp_env python-path=/home/myuser/my_django/my_project user=myuser socket-user=myuser WSGIProcessGroup ${wsgi_daemon} WSGIScriptAlias / /home/myuser/my_django/my_project/my_project/wsgi.py Define wsgi_init 1 </IfDefine> </VirtualHost> The Django location + structure: home |-- myuser |-- my_django (group: www-data) |-- sklp_env `-- my_project (group: www-data) |-- myapp |-- my_project |-- static |-- db.sqlite3 (group: www-data / permission: 664) `-- manage.py Some settings of the project (/home/myuser/my_django/my_project/my_project/settings.py): ... ALLOWED_HOSTS = … -
ModuleNotFoundError: No module named 'app.project' when running pytest on a Django project in GitLab CI
I'm having trouble running my tests with pytest in a Django project on GitLab CI. My project structure looks like this: my-project/ ├── app/ │ └── app/ │ ├── settings.py │ └── (other Django files) ├── project/ │ ├── __init__.py │ ├── models.py │ └── tests/ │ ├── __init__.py │ └── test_models.py └── conftest.py In my test file (project/tests/test_models.py), I import my modules like this: from project.models import User, Course, Lesson, Exercise I also have the following in my pytest configuration (pytest.ini): [pytest] DJANGO_SETTINGS_MODULE = app.app.settings When I run pytest from GitLab CI pipeline: docker --context digitavox compose -f docker-compose.yml exec -T app bash -c 'export DJANGO_SETTINGS_MODULE=app.settings && export PYTHONPATH=$(pwd):$(pwd)/app && pytest -v --collect-only --disable-warnings' I get the following error: ModuleNotFoundError: No module named 'app.project' I have verified that: All necessary init.py files are present. The tests use the import statement from project.models import ... (without the “app.” prefix). The conftest.py file is located at the project root, so the project root should be added to sys.path automatically when pytest runs. My question is: How should I configure the PYTHONPATH or adjust my imports/structure so that pytest can correctly locate my modules when running on GitLab CI? Do I need … -
I'm trying to deploy a python app to azure but it doesn't work even with a quickstart sample app
Here's an article from Microsoft with a quickstart guide for python app at azure. So I'm trying to deploy a python app on azure using free tier but it simply doesn't work. I've tried multiple things already. I've cloned sample project code from here as the article suggests. Then I've tried to run it locally using python 3.12. That version is the latest supported for an azure web app at the moment. It works locally on my pc even though /admin/ doesn't work there, but whatever: at least some page opens successfully. I've ran it via pycharm community with a virtual environment. Then I've tried to upload these folders and files to the site/wwwroot folder: folder: .venv hello_azure quickstartproject static .env.sample db.sqlite3 manage.py requirements.txt Before doing that I've created a web app on free tier, chose python 3.12 and opened public access to the website. In the overview of the app it's running. I've also tried to add as a startup command these: manage.py runserver, site/wwwroot/manage.py runserver, python manage.py runserver, python site/wwwroot/manage.py runserver, but non of that worked. On attempt to open the website it shows this error: :( Application Error If you are the application administrator, you can access … -
Django CSRF Token Suddenly Stopped Working
I've been programming a Django application for over a year now. I got the CSRF token working fine in the beginning and there haven't been any problems since. But now, it's suddenly stopped working, both locally and in my development environment despite pushing no changes to it. Does anyone know why this might be, and how I could fix it? Here is a list of everything I've tried: Going through the list of 5 recommendations given in the error report: Browser is accepting cookies: YES Passing a request to the render method: YES Using {% csrf_token %} inside form tag: YES Using CsrfMiddleWare: YES Form has valid csrf token: YES, because I'd reset the cookies manually Removing mismatched data the following ways: Clearing cached data, cookies, and browsing history Restarting my computer Updating Chrome Using Incognito Mode Clearing user session data before every form submission Using decorators '@ensure_csrf_cookie' and '@csrf_protect' either individually or in combination before my view functions. Used this syntax: from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.csrf import csrf_protect ... @ensure_csrf_cookie @csrf_protect def templateFunc(request): In settings.py, making sure to assign the correct localhost to csrf variables, with and without the port numbers: ALLOWED_HOSTS = ['127.0.0.1', 'localhost', ".awsapprunner.com", "dev.org"] CSRF_COOKIE_DOMAIN … -
Key Error when trying to remove slug from my models
I am getting this error when I run migrations: *old_field = model_state.fields.pop(name) KeyError: 'slug'* I have no reference to a slug apart from in my migrations where I had added it then tried to removed it. I am reluctant to delete any migrations but I cannot see another way of moving past this error. I have found this code, in this file env\Lib\site-packages\django\db\migrations\state.py: def remove_field(self, app_label, model_name, name): model_key = app_label, model_name model_state = self.models[model_key] old_field = model_state.fields.pop(name) if self._relations is not None: self.resolve_model_field_relations(model_key, name, old_field) # Delay rendering of relationships if it's not a relational field. delay = not old_field.is_relation self.reload_model(*model_key, delay=delay) Which is where the error is pointing but I don't think this should be touched. I have tried to run a fake migration for the removal of the slug migration and although that goes through; the next time I ran a migration I got the same error again. I am using a postgres DB. -
what dose clean functions do in model django? NOT IN FORMS
I was reading THIS-SOLUTION and I wonder what dose "clean function" do ? is clean where we should put our checkings ? then I found this picture : enter image description here so we have bunch of clean functions , I just want to know what they do . and is it correct to use "clean" if we want to add a filter which makes sure we wont have more than x object from one model(table)? I think using " def save() " seems more suitable to solve this kind of checking but Im not sure.