Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle user login through Spotify (what to do with tokens)
I'm trying to create a web app using a Django backend and React frontend. This is my first time using Django and dealing with accounts specifically. The app revolves around Spotify accounts so to login a user has to login through Spotify. I understand the authorization process and can get a user's access/refresh token, but I'm not sure what to do from here. I have found a lot of conflicting information online. Most people say not to use local storage which makes sense. Right now I am trying to implement it using Django sessions, but I've read online about that not scaling well/not being RESTful so I'm confused. I also looked at using django-allauth and it worked, but I'm confused with how it would work with my React frontend because as far as I understand it, it's just something I can do only in Django (localhost:8000). I want to be able to create a User in my database once a user logs in for the first time. From here, do I store the user's tokens inside the database too? Do I use Django's User model at all? I saw people mentioning Django's built-in authorization but confused how that ties in … -
Django flush raises "cannot truncate a table referenced in a foreign key constraint"
Consider the following models.py: from django.db import models class Foo(models.Model): bars = models.ManyToManyField( "Bar", blank=True ) class Bar(models.Model): foos = models.ManyToManyField( "Foo", blank=True, through="Foo_bars" ) and the associated migration: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Bar", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], ), migrations.CreateModel( name="Foo", fields=[ ( "id", models.BigAutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("bars", models.ManyToManyField(blank=True, to="demo.bar")), ], ), migrations.AddField( model_name="bar", name="foos", field=models.ManyToManyField(blank=True, to="demo.foo"), ), ] Running python manage.py migrate && python manage.py flush --no-input --traceback produces the following trace back File "/opt/venv/lib/python3.13/site-packages/psycopg/cursor.py", line 97, in execute raise ex.with_traceback(None) django.db.utils.NotSupportedError: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "demo_bar_foos" references "demo_foo". HINT: Truncate table "demo_bar_foos" at the same time, or use TRUNCATE ... CASCADE. How can I fix this problem? How can I add cascade? A full reproducible example is available at https://github.com/rgaiacs/django-flush-problem. -
Django getting 404 error when trying to load files from MinIO on the same server
I have setup a Django web app (Django version 5.0.6) on an Ubuntu 22.04 LTS operating system with its default backend file system running MinIO 2024-08-03T04-33-23Z. The services are all running using HTTPS. My Django web app is configured to run with Gunicorn version 22.0.0 and Nginx version 1.26.2 My Django settings are provided below. ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', [subdomain_ip], 'subdomain.domain.org' ] CSRF_TRUSTED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS] CSRF_ALLOWED_ORIGINS = [f'https://{host}' for host in ALLOWED_HOSTS] CORS_ORIGINS_WHITELIST = [f'https://{host}' for host in ALLOWED_HOSTS] INTERNAL_IPS = ['127.0.0.1', 'localhost', [subdomain_ip], 'subdomain.domain.org'] # MINIO BACKEND SETTINGS MINIO_CONSISTENCY_CHECK_ON_START = True MINIO_ENDPOINT = 'subdomain.domain.org:9000' MINIO_REGION = 'eu-west-1' # Default is set to None, current is Ireland MINIO_ACCESS_KEY = '[REDACTED]' MINIO_SECRET_KEY = '[REDACTED]' MINIO_USE_HTTPS = True MINIO_EXTERNAL_ENDPOINT = 'subdomain.domain.org:9000' MINIO_EXTERNAL_ENDPOINT_USE_HTTPS = True MINIO_STORAGE_ENDPOINT = 'subdomain.domain.org:9000' MINIO_STORAGE_ACCESS_KEY = '[REDACTED]' MINIO_STORAGE_SECRET_KEY = '[REDACTED]' #MINIO_STATIC_FILES_BUCKET = 'bridge-static-files-bucket' MINIO_MEDIA_FILES_BUCKET = 'bridge-media-files-bucket' # Media files storage configuration #DEFAULT_FILE_STORAGE = 'minio_storage.storage.MinioMediaStorage' DEFAULT_FILE_STORAGE = 'django_minio_backend.models.MinioBackend' MINIO_STORAGE_MEDIA_BUCKET_NAME = MINIO_MEDIA_FILES_BUCKET MINIO_STORAGE_MEDIA_URL = f"{MINIO_EXTERNAL_ENDPOINT}/{MINIO_MEDIA_FILES_BUCKET}" MINIO_PRIVATE_BUCKETS = ['django-backend-dev-private', ] MINIO_PUBLIC_BUCKETS = ['django-backend-dev-public', ] #MINIO_PRIVATE_BUCKETS.append(MINIO_STATIC_FILES_BUCKET) MINIO_PRIVATE_BUCKETS.append(MINIO_MEDIA_FILES_BUCKET) # Default: True // Creates bucket if missing, then save MINIO_BUCKET_CHECK_ON_SAVE = True # SSL SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_INCLUDE_SUBDOMAINS = True … -
why django makemigration command creates python based code instead of creating sql commands
why django makemigration command creates python based code instead of creating sql commands, Someone please explain from design decision point of view, and what benefits we get from it. -
Authentication with Django Ninja, allauth or other solid solution?
I'm creating an API with django ninja, and I wanted to implement user authentication and accounts. I like allauth for it's social account functionality built in, as I plan for users to be able to link steam/xbox accounts and I've seen you can use this with drf relatively easily? Can I implement it with django ninja, or is there any other good authentication for ninja specifically. Also, will I need token authentication for this if at some point in the future it may interface with a mobile application? Thanks for the support. -
How to alter data entered into django models to fit a criteria?
I have a django models.py file that I use to store information in my database. I store information on businesses and the countries that they operate in. I get the list of countries from their website. However they may call each country by a different name or use different formatting, for example 'The Gambia' vs 'Gambia', 'Eswatini' vs 'Swaziland', 'Trinidad and Tobago' vs 'Trinidad & Tobago'', 'The United States' vs 'United States of America'. I want that when I store the names of these countries in my database they automatically follow a set of rules to ensure consistent formatting of their names. Additionally, some websites state something like 'We operate in 150 countries'. I want to enter this information into the database but not have it come up when I request a list of countries from the frontend. Here is my models.py: class Company(models.Model): #the newly created database model and below are the fields name = models.CharField(max_length=250, blank=True, null=True) #textField used for larger strings, CharField, smaller slug = models.SlugField(max_length=250, blank=True, db_index=True, unique=True) available_merchant_countries = models.TextField(max_length=2500, blank=True, null=True) available_merchant_countries_source = models.URLField(max_length=250, blank=True, null=True) -
How to dynamically list fields for products
I have various products, and their fields need to change depending on the category. Is it possible to implement this in the most optimized way? Also, can the fields be managed from the admin panel? -
Datatables instance not synced with DOM (input checkbox status)
I have a table my_tbl initialized with datatables2.1.8.js jQuery library: /* using python django template because table template is not in the same html file */ {% include 'my_tbl_template.html' %} let my_tbl=$('#my_tbl').DataTable({...}), each cell containing <input type="checkbox" value="some_value"> whether initially checked or unchecked; The problem exactly is that my_tbl is not synced with the html dom after changing manually the checkboxes status! (check or uncheck); e.g. when I have two checkboxes (2 cells) initially both checked, when user unchecks one of them printCheckboxStatusDom() prints 1 //(expected number of checked checkboxes) but printCheckboxStatusTbl() prints 2 //the initial checked checkboxes $(document).ready(function(){ $('input[type=checkbox]').change(function() { printCheckboxStatusDom(); // prints correctly how many checkbox is checked at this time printCheckboxStatusTbl(); //always prints initialized values (no change) }); function printCheckboxStatusDom(){ let checkeds = $(document).find('input[type=checkbox]:checked'); console.log('DOM: checked boxes: ' + checkeds.length); } /* Function to print checkboxes status in the my_tbl instance */ function printCheckboxStatusTbl() { my_tbl.rows().every(function (rowIdx, tableLoop, rowLoop) { let rowNode = this.node(); let cellCheckboxes = $(rowNode).find('input[type=checkbox]:checked'); console.log('Tbl: checked boxes: ' + cellCheckboxes.length); } ); } -
Transferring a Django + React Project to a New PC in an Offline Environment Without Reinstalling Dependencies
I have a full-stack Django and React project that I need to transfer to a new computer in a completely offline environment. My current setup includes: Django backend with custom app React frontend Virtual environment Specific dependency requirements Project Structure: development/ ├── .git/ ├── .gitignore ├── backend/ │ ├── app/ │ ├── db/ │ ├── manage.py │ └── myproject/ ├── frontend/ │ ├── node_modules/ │ ├── package.json │ ├── package-lock.json │ ├── public/ │ └── src/ ├── initial_data.py ├── packages/ ├── README.md ├── requirements.txt └── venv/ Challenges Dependency Management No internet access for pip or npm install Potential system-specific binary incompatibilities Preserving exact package versions Environment Reproduction Virtual environment setup Python and Node.js version compatibility Native library dependencies Current Attempts I've tried: Directly copying the entire project directory Manually installing requirements from requirements.txt Using pip and npm to install packages Invariably, these methods fail due to: Missing system libraries Version conflicts Binary incompatibility Specific Questions How can I package all project dependencies for offline transfer? What's the most reliable method to reproduce the development environment? Are there tools that can create a complete, transferable project snapshot? Detailed Environment Details Backend: Django 5.0.6 Frontend: React (based on package.json) Python: 3.12.4 Operating … -
What could be the possible reasons for encountering the error?
What could be the possible reasons for encountering the error 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? I am try to solves that error but I cant find solution on Internet related to this error please if you optimized and best solution kindly give me proper answer? 'OperationalError: no such table: auth_user' when running a Django application, and how can it be resolved? -
How to solve 'django.db.migrations.exceptions.InconsistentMigrationHistory' error?? (using powershell/VSCode)
I am making a web app (I am a student and this is my first attempt of building a project) using stack: Django, Vue and MySQL. Attaching link to git repo here: https://github.com/yeshapan/LearningDashboard (please refer ReadME for details) I completed initial setup and then created an app called dashboard where I defined models for the features. Edit: Here's the error message as text: Traceback (most recent call last): File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 22, in <module> main() File "C:\Users\DELL\Desktop\LearningDashboard\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 121, in handle executor.loader.check_consistent_history(connection) File "C:\Users\DELL\Desktop\LearningDashboard\venv\Lib\site-packages\django\db\migrations\loader.py", line 327, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency dashboard.0001_initial on database 'default'. However, it is raising error: Error message I tried asking ChatGPT for help. It said to delete everything in dashboard/migrations and delete db.sqlite3 file in root folder (Edit: I also deleted the table from MySQL and applied migrations again but it is still giving error) and apply … -
The dropdown menu is not expanding. CSS and JS are connected correctly
I am a beginner in web development. I need some help. The dropdown menu is not expanding. CSS and JS are connected correctly. What could be the reason? I checked the CSS/JS classes and connected files. Everything seems to be correct, I even used GPT, but no results. :( I can provide other project files if needed. Here is the code from the main file layout.html. {% load static %} <!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}Головна{% endblock %}</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/5.10.1/main.min.css"> </head> <body> <button class="btn btn-primary" id="sidebarToggle"> <i class="fas fa-bars"></i> </button> <div class="d-flex"> <aside class="flex-shrink-0 p-3 bg-dark text-white sidebar" id="sidebar"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <img src="{% static 'main/img/2.png' %}" alt="Logo" class="small-logo"> </a> <hr> <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="{% url 'layout' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'layout' %}active{% endif %}" aria-current="page"> <i class="fas fa-heart"></i> Головна </a> </li> <li> <a href="{% url 'staff' %}" class="nav-link text-white {% if request.resolver_match.url_name == 'staff' %}active{% endif %}"> <i class="fas fa-users"></i> Особовий склад </a> </li> <li> <a href="{% url 'calendar' %}" … -
"C# PBKDF2 password hashing with Django-compatible format (pbkdf2_sha256), issues with password verification"
I am working on a C# application where I need to verify user passwords that were hashed using Django’s PBKDF2 algorithm (pbkdf2_sha256). The passwords are stored in the format: pbkdf2_sha256$iterations$salt$hash For example: pbkdf2_sha256$870000$wyEbTcPvbTOet9npIyftqZ$Xv274JNGq1ZMQQHzmZx8q5n+Nly/U5Wf1WYLRO4d8YY= I'm trying to replicate the same process in C# using Rfc2898DeriveBytes to verify the password. However, I am encountering an issue where the computed hash does not match the stored hash, even though the entered password is correct. Here's the C# code I’m using to verify the password: public static bool VerifyPassword(string enteredPassword, string storedPasswordHash) { var parts = storedPasswordHash.Split('$'); if (parts.Length != 4 || parts[0] != "pbkdf2_sha256") { Console.WriteLine("Invalid password format."); return false; } string iterationsStr = parts[1]; string salt = parts[2]; string storedHash = parts[3]; if (!int.TryParse(iterationsStr, out int iterations)) { Console.WriteLine("Invalid iterations count."); return false; } byte[] saltBytes = DecodeBase64Salt(salt); if (saltBytes == null) { return false; } byte[] passwordBytes = Encoding.UTF8.GetBytes(enteredPassword); byte[] computedHashBytes; using (var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, saltBytes, iterations, HashAlgorithmName.SHA256)) { computedHashBytes = pbkdf2.GetBytes(32); } string computedHash = Convert.ToBase64String(computedHashBytes); Console.WriteLine($"Computed Hash: {computedHash}"); return storedHash == computedHash; } private static byte[] DecodeBase64Salt(string salt) { switch (salt.Length % 4) { case 2: salt += "=="; break; case 3: salt += "="; break; } … -
my is the block content on django is displaying below the footer
this is the base.html the block content is between the header and the footer <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>header</h1> {% block content %} {% endblock content %} <h1>footer</h1> </body> </html> this is index that include the base html {% include "base.html" %} {% load static %} {% block content %} <p> body </p> {% endblock content %} the p tag boby should display in a middel expected output header body footer the outout header footer fghj the p tag should be in the middel right or is there something i missed? -
Join Our Exciting New Startup: Transform Business with Cutting-Edge IT Solutions
Are you a passionate developer looking to make an impact? We are a dynamic business consultation and implementation startup helping companies optimize their operations with customized software solutions, automation, and CRM tools. We’re looking for talented individuals to join our team on a profit-sharing basis, where your success is directly tied to the growth of the company. If you're looking for an opportunity to grow with a rapidly expanding startup and be part of innovative projects, this is the role for you! Positions Available: Frontend Developers Backend Developers Full Stack Developers Django Developers Custom Software Developers RPA Specialists CRM Specialists (Zoho, Salesforce, HubSpot) What We're Looking For: Frontend Developers: Expertise in HTML, CSS, JavaScript, and popular frameworks like React, Angular, or Vue.js. Backend Developers: Proficiency in Node.js, Python, Ruby, Java, or similar technologies. Full Stack Developers: A combination of both frontend and backend expertise with the ability to work on entire application stacks. Django Developers: Solid experience with Django for backend development, REST APIs, and integration with frontend frameworks. Custom Software Developers: Experience in creating bespoke solutions tailored to clients' needs, focusing on scalability and security. RPA Specialists: Expertise in automating business processes using tools like UiPath, Blue Prism, or … -
Django Function Update
I'm doing the update function but I get a message Page not found enter image description here views.py def detalle_tarea(request, tarea_id): if request.method == 'GET': tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(instance=tarea) return render(request, 'tarea_detalles.html', {'tarea': tarea, 'form': form}) else: tarea = get_object_or_404(Tarea, pk=tarea_id) form = TareaForm(request.POST, instance=tarea) form.save() return redirect('tareas') url.py from django.contrib import admin from django.urls import path from tareas import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.inicio, name='inicio'), path('registrar/', views.registrar, name='registrar'), path('tareas/', views.tareas, name='tareas'), path('tareas/crear/', views.crear_tarea, name='crear_tarea'), path('tareas/<int:tarea_id>/', views.detalle_tarea, name='detalle_tarea') ] Any suggestion ??? -
How to get my favicon at `example.com/favicon.ico` in my Django project?
Google currently does not show my website's favicon in its search results and I learned that it is becuase it should be located at example.com/favicon.ico. I'm looking for a simple way to do this, hopefully without relying on redirects. I've used redirection to the version in my static folder but when I visit the url it redirects to example.com/static/favicon.ico, which I do not want. I want that if a user or a crawler visits example.com/favicon.ico they see my favicon. It is currently located at: my_project/ ├── my_project/ │ ├── ... │ ├── settings.py │ ├── ... ├── manage.py └── static/ └── img/ └── favicon.ico I use gunicorn as my web server and whitenoise as my http server. Here is my urls.py: from django.urls import path, include # new from django.contrib.sitemaps.views import sitemap # new from finder.views import ProcessorDetailSitemap, ArticleDetailSitemap, StaticViewSitemap # Correct import path #from django.conf import settings #from django.conf.urls.static import static sitemaps = { 'processor':ProcessorDetailSitemap, 'article': ArticleDetailSitemap, 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls), path('', include('finder.urls')), #new path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap",), ] It is also linked in my template usingn<link rel="icon" type="image/x-icon" href="{% static 'img/favicon.ico' %}"> -
Django view to PNG
I'm writing django webapp, and part of it is to generate view and convert it to png image. (any ideas other then below are appreciated). I've looked at some tools to convert "html to png", but there is mainly problem with {%static files and templates. Another approach is to render page using django templates in browser, and take screenshot. It can be done using "chromedriver" + selenium. I was able to do it in my local ubuntu. But on production - all I've got is remote (ssh) access to some linux bash, where my application is hosted. I've created venv, pip-installed selenium and (chromedriver-py or chromedriver-binary). For the second one - it looks like it is closer to start working, but I've got error message: SessionNotCreatedException Message: session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir Stackoverflow says, that I should somehow put there a path to my chrome installation's user dir, but is there any chrome installation in that console bash of mine? Any ideas how to move forward ? or any other ideas how to do it? My code: import chromedriver_binary def render_to_png(request ): … -
How to make Django's Browsable API Renderer generate correct URLs with an /api/ prefix when behind Nginx?
I'm deploying a Django application using the Django Rest Framework (DRF) on a server behind Nginx. The application is accessible via https://my-site.com/api/ where /api is routed to the Django application. However, when I access the API's browsable UI at https://my-site.com/api/locations, everything works fine. But when I try to click the "Get JSON" button from the UI, it generates an incorrect URL: /locations?format=json instead of the correct /api/locations?format=json. Or when i try to POST it posts to /locations instead of /api/locations The issue is that the DRF Browsable API Renderer seems to be constructing the URLs as if the app is running directly under the root path (/), but in reality, it's running under /api/ on the server due to Nginx routing. # Proxy requests to the Django backend (API) location /api/ { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Script-Name /api; # Tell Django it's running under /api proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } What I'm Looking For: A solution to make the Django Browsable API Renderer correctly generate URLs with the /api/ prefix when behind Nginx. -
SessionStore object has no attribute 'get_session_cookie_age'
I have a Django project, everything goes well, but when I tried to handle the expiration of the session I got confused In a test view print(request.session.get_session_cookie_age()) give me this error SessionStore' object has no attribute get_session_cookie_age According to the documentation it should returns the value of the setting SESSION_COOKIE_AGE Trying debugging with this code : from django.contrib.sessions.models import Session sk = request.session.session_key s = Session.objects.get(pk=sk) pprint(s.get_decoded()) >>> {'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': '055c9b751ffcc6f3530337321e98f9e5e4b8a623', '_auth_user_id': '6', '_session_expiry': 3600} Here is the config : Version Django = 2.0 Python 3.6.9 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'drf_yasg', 'wkhtmltopdf', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] Thank's in advance -
Javascript fetch return 403 on Apache Server
Struggling with this issue for a few days now so any help is greatly appreciated. I managed to deploy my django project on a Linux server and it works fine apart from the model form submit. On the local development server it work fine and here is the workflow: User fills the form; User clicks submit; Javascript catches the submit event, submits a "POST" request and gets a response back; On the server side, the form is checked and if all is good an email is sent; HTML is updated to add the confirmation of form registration; Here is my code: home.html <div class="col-lg-8 offset-lg-2"> <form method="POST" class="row mt-17" id="form" onsubmit="return false"> {% csrf_token %} {% for field in form %} {% if field.name not in "message" %} <div class="col-12 col-sm-6"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% else %} <div class="col-12"> <div class=form-group> <label for={{field.name}} class="form-label">{{ field.label }}</label> {{ field }} </div> </div> {% endif %} {% endfor %} <div class="form-group mb-0"> <button type="submit" class="btn btn-primary btn-lg">Submit</button> </div> </form> </div> main.js const form = document.getElementById('form'); form.addEventListener("submit", submitHandler); function submitHandler(e) { e.preventDefault(); fetch("{% url 'messages-api' %}", { credentials: "include", method: 'POST', headers: { 'Content-Type': … -
can i save changes in the value before redis key expires
I could not find better solution. I have IDs and ranks in my Redis. Is it possible for me to save the changed ranks to the database before the Redis key expires?. can I trigger some function before it expires x time earlier -
CVAT OpenID Connect login doesn't show on Login page
I am trying to set up CVAT to support login using a custom IdP with OpenID Connect. I tried to make changes to base.py and docker-compose.override.yml to configure the server, but once I build and launch CVAT, nothing happens. I followed this guide, which was directly linked in the code. Here are the base.py changes: INSTALLED_APPS += ['cvat.socialaccount.providers.openid_connect',] ... SOCIALACCOUNT_PROVIDERS = { "openid_connect": { # Optional PKCE defaults to False, but may be required by your provider # Can be set globally, or per app (settings). 'OAUTH_PKCE_ENABLED': True, 'EMAIL_AUTHENTICATION' : True, "APPS": [ { "provider_id": "NAME", "name": "Service Name", "client_id": "client_id", "secret": "secret", "settings": { "server_url": "https://server/cvat/.well-known/openid-configuration", # Optional token endpoint authentication method. # May be one of "client_secret_basic", "client_secret_post" # If omitted, a method from the the server's # token auth methods list is used "token_auth_method": "client_secret_basic", "oauth_pkce_enabled": True, }, }, ] } } SOCIAL_AUTH_OPENIDCONNECT_KEY = 'client_id' SOCIAL_AUTH_OPENIDCONNECT_SECRET = 'secret' SOCIAL_AUTH_OPENIDCONNECT_API_URL = 'https://server/cvat/.well-known/openid-configuration' SOCIALACCOUNT_ONLY = True And this is the added docker-compose.override.yml file: services: cvat_server: environment: USE_ALLAUTH_SOCIAL_ACCOUNTS : true Since none of this worked, I tried creating a auth_config.yml as follows: --- social_account: enabled: true openid_connect: client_id: client_id client_secret: secret domain: https://server.it/ and told CVAT to use it by … -
Django Rest Framework login failure
I'm trying to make DRF work without custom serializers, views and urls, just using the default ones, but there is an issue with my login. Whenever i create a user on /api/v1/auth/register (this happens successfully) and then try to log in on /api/v1/auth/login, I get this error message: { "non_field_errors": [ "Unable to log in with provided credentials." ] } On the admin panel I login successfully with the same credentials, a proof they are correct. Even when I set up to use just the email as credentials, I am still required a password. Here is my settings.py: ... ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'rest_framework_simplejwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', ] MIDDLEWARE = [ ... "allauth.account.middleware.AccountMiddleware", ] ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(hours=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } REST_AUTH = { "USE_JWT": True, "JWT_AUTH_COOKIE": "_auth", "JWT_AUTH_REFRESH_COOKIE": "_refresh", "JWT_AUTH_HTTPONLY": False, } SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_CONFIRM_EMAIL_ON_GET = True LOGIN_URL = "/api/v1/auth/login" I've tried many other approaches like custom user model, views and serializers, but it never worked, even became worse. I suppose there is something to … -
How to use uv run with Django in a PyCharm Docker environment?
I am developing a Django application using a Docker environment in PyCharm. Until now, I have been using pip for package management, but I am considering using uv to potentially reduce container build times. I managed to install uv in the Docker container, but I am unsure how to configure PyCharm to start Django development using uv run. It seems that the screen where I typically configure run/debug settings does not have an option for this. How can I set up uv run in PyCharm for my Django project? If possible, I would like to know the best practices or any alternative solutions for this setup. Thank you in advance for your help!