Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prevent Django DetailView from adding template context with name of object
I have a DetailView for users, and it seems to be adding a user context variable. This is problematic because I have an application-wide context variable, user that contains the current user that is being overridden. How can I prevent the DetailView from adding this context variable? -
Error related to connecting Django from Docker to Nginx
I am currently working on Docker and have done the following: The Django test page was working fine on localhost. I connected it to Docker. I also connected Docker to Gunicorn. However, when I try to connect it through Nginx, only the default Nginx page is displayed, and it is not connecting to the application I created. nginx/Dockerfile FROM nginx:latest RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d # nginx/nginx.conf upstream daniel_blog { server web:8000; } server { listen 80; server_name localhost; # Default location location / { proxy_pass http://daniel_blog; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } # Static files location /static/ { alias /usr/src/app/_static/; } # Media files location /media/ { alias /usr/src/app/_media/; } } --- # .env.dev DEBUG="1" SECRET_KEY="django-insecure-88ndzs0z0uzko4x5f=*ngu=#h+a(k=!#ooyvt*0h+78r1n=^oy" DJANGO_ALLOWED_HOSTS = localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_dev SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod DEBUG=0 SECRET_KEY=w4+=--yyyigm1-=na@9et*1ldt-q-x4x=57m2xkiru6!oxeh5b DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=daniel_blog_prod SQL_USER=daniel_blog_user SQL_PASSWORD=daniel_blog_db_password SQL_HOST=db SQL_PORT=5432 --- # .env.prod.db POSTGRES_USER=daniel_blog_user POSTGRES_PASSWORD=daniel_blog_db_password POSTGRES_DB=daniel_blog_prod --- # docker-compose.yml services: nginx: build: ./nginx volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media ports: - 80:80 depends_on: - web web: build: . command: gunicorn daniel_blog.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volumes:/usr/src/app/_static - media_volumes:/usr/src/app/_media - ./:/usr/src/app/_media expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:17.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ … -
Sorting a string before a number with Postgres and Django
I want to use fuzzy dates for sorting a Django query, so you can use a full date if you have it, but maybe you only know year and month. For example, Jan XX 2024 would come before Jan 1 2024 and Jan 2 2024. I was originally planning to store as a string 202401XX, 20240101, etc, but Postgres naturally sorts characters after numbers so this would put the date with no day AFTER the date with day specified. I was thinking of converting the 20240101 to letters before saving to the database (X=A, 0=F, 1=G, etc) since this is a computationally cheap thing and I could control where everything sorted. Is this a terrible idea? Is there a better way? I don't want to do a custom Postgres query because that would be complicated with Django's built-in pagination -
Is there way to display historical records for all model instances using django-simple-history?
I am using django-simple-history for saving history of the objects. And it works fine. But I want to create a view in django admin that displays history records for all instances in model in one page. For example I have a model class TestModel(models.Model): title = models.CharField('title', max_length=100) history = HistoricalRecords() and admin class TestModelAdmin(SimpleHistoryAdmin): list_display = ['title'] admin.site.register(TestModel, TestModelAdmin) And now I can see the history of each instance. Not sure how I can solve this problem. May be there is a way to create custom views in admin site (without model), or maybe I should create another model? What's the best way to display all history records (for all instances) in admin panel? -
Redirecting from DELETE to GET in Django
I use Django django 4.0.8 and django-tastypie. Why is it that when I send a request (for example) http://127.0.0.1:8000/api/v1/courses/3 via Postman, I get a redirect to GET /api/v1/courses/3/? If I send http://127.0.0.1:8000/api/v1/courses/3/ it work correctly. Adding 'APPEND_SLASH = True' in settings.py does not resolve this problem. String "MIDDLEWARE = ['django.middleware.common.CommonMiddleware']" I have in settings.p -
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