Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dokku Procfile "release: python manage.py migrate" results in a NodeNotFoundError "Migration XYZ dependencies reference nonexistent parent node"
When i push to the dokku test environment, i get the following error when the Procfile is being used: -----> Releasing aha-website-test... -----> Checking for predeploy task No predeploy task found, skipping -----> Checking for release task Executing release task from Procfile in ephemeral container: python manage.py migrate =====> Start of aha-website-test release task (825335cfe) output remote: ! Traceback (most recent call last): remote: ! File "/app/manage.py", line 10, in <module> remote: ! execute_from_command_line(sys.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line remote: ! utility.execute() remote: ! ~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 436, in execute remote: ! self.fetch_command(subcommand).run_from_argv(self.argv) remote: ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 413, in run_from_argv remote: ! self.execute(*args, **cmd_options) remote: ! ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 459, in execute remote: ! output = self.handle(*args, **options) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/base.py", line 107, in wrapper remote: ! res = handle_func(*args, **kwargs) remote: ! File "/usr/local/lib/python3.13/site-packages/django/core/management/commands/migrate.py", line 118, in handle remote: ! executor = MigrationExecutor(connection, self.migration_progress_callback) remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/executor.py", line 18, in __init__ remote: ! self.loader = MigrationLoader(self.connection) remote: ! ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 58, in __init__ remote: ! self.build_graph() remote: ! ~~~~~~~~~~~~~~~~^^ remote: ! File "/usr/local/lib/python3.13/site-packages/django/db/migrations/loader.py", line 276, in build_graph … -
Git pull fails with "RPC failed; curl 92 HTTP/2 stream 7 was not closed cleanly: CANCEL (err 8)"
I'm having trouble running git pull from my repository. The command fails with the following error messages: remote: Enumerating objects: 42, done. remote: Counting objects: 100% (34/34), done. remote: Compressing objects: 100% (11/11), done. error: RPC failed; curl 92 HTTP/2 stream 7 was not closed cleanly: CANCEL (err 8) error: 4136 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: unpack-objects failed It seems like the operation is failing during the transfer. I've tried running the command multiple times, but I keep getting the same error. Increased the Git buffer size using the following command, but it didn’t resolve the issue: git config --global http.postBuffer 524288000 Checked my internet connection, which seems stable and works fine with other services. -
Selenium(chrome driver) and Gunicorn problem workers close immediately after starting with daemon
I'm publishing my app to a vps everything works great when starting the app using runserver or normal testing with Gunicorn but when trying to run my server through Gunicorn the driver keeps crushing any help please ? ideas to help fix the problem -
How to implement one-way data transfer at specific intervals using SSE or WebSockets?
I'm working on a web application where I need to send data from the server to the client at specific times rather than continuously. I want to achieve this using either Server-Sent Events (SSE) or WebSockets. Requirements: One-way communication: Data only flows from the server to the client. Timing control: Data should be sent only at predefined intervals or specific triggers, not continuously. Questions: Can I use SSE for this purpose, and if so, how would I structure the server to send messages only at specified times? Would using WebSockets be a better approach for sending timed messages? If yes, how would that be implemented? Are there alternative methods (like HTTP polling or long polling) that could suit my needs better? I initially tried using Server-Sent Events (SSE), but I found that it sends data continuously, which isn't what I need. -
Hi, I'm new to the Django. I wanted to know how to bind selected objects to another model object at once on web page (like a checkbox)
I wanted to know how to create a model object by binding multiple other selected objects at once on a web page (like a checkbox or something). For example If I want to create a model named group for university but I need to include students from another model to this group excluding some of them (not all of the given students will be included). So, I was not able to create a form to choose all of them or exclude some of them at once, please help. Thanks in advance. -
Timeout error when uploading PDF and CSV files in Django app on o2switch server
I deployed a Django application on an o2switch server and I am trying to upload files to my media folder. My code works perfectly for .txt and .xlsx files, but it does not work for .pdf or .csv files. I get a timeout error, and it seems that the request does not even reach the server, because nothing appears in the logs. I tried to do a test with a PHP script on the same domain, and it works for all file types. So the problem seems to come either from the Django Rest Framework application, or from a specific configuration on o2switch. As a reminder, uploads work fine with .txt files, but I get a timeout for .pdf and .csv files. Do you have any ideas on what could cause this behavior? Is it a problem related to Django Rest Framework or to the o2switch configuration? and python 3.8.18 Thanks in advance for your help import os import sys sys.path.append(os.getcwd()) os.environ['DJANGO_SETTINGS_MODULE'] = 'Back_end_Gaz_elec.settings' import django.core.handlers.wsgi from django.core.wsgi import get_wsgi_application SCRIPT_NAME = os.getcwd() class PassengerPathInfoFix(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset … -
Calculate max parallel elements by time in elasticsearch
I need to calculate max parallel people survey in elastic search. Mapping for this fields are: "start_at": {"type": "date"}, "end_at": {"type": "date"}, So, for one week i need to know with accuracy ~10s when in our system was max people and how much of them :-) Thx for help :-) "aggs": { "seconds_histogram": { "date_histogram": { "field": "start_at", "fixed_interval": "1s", "min_doc_count": 0, "extended_bounds": { "min": ..., "max": ... } }, "aggs": { "active_surveys": { "bucket_script": { "buckets_path": { "start": "_key", "end": "_key" }, "script": """ // Survey should have started before or at the bucket second and ended after or at the second. if (doc['start_at'].value.getMillis() <= params.start && doc['end_at'].value.getMillis() >= params.end) { return 1; } else { return 0; } """ } } } } -
Creating an SPA - use AJAX or django urls?
I am building a website as a school project, which should use django for the backend and vanilla js for the frontend. My question is, for loading different html files, is it better to use AJAX or django urls? I am not sure if using different django urls would make the content load dynamically, as it is required by a SPA. If there is a better way to load my content, please let know. I will really appreciate any help with this. -
Django Wagtail, React Native and 3rd Party Signup and Signin
I'm working on a marketplace platform. My sellers have a web portal to manage their stores. My buyers have a react native mobile application to access the platform. My server is running on django wagtail. I am using django allauth and I'm able to login to my django server from my mobile application. Using username and password and it creates a jwt which my app uses to consume my django api's. However I would like for my mobile users and web portal users to signup using Google and Facebook providers. Using the following two links documentation and doc. I have sort of an idea of the flow. However I'm not clear how to use it with firebase as the examples is directly to the 3rd party provider of github. Based on my research I keep coming across Firebase, how will it play nice with django allauth social? And will my web portal and mobile app need different integration methods? I came across this post but the answer doesn't seem complete because if Django doesn't have anything to do with this flow how will it know a user is authorised to consume my API's? -
Access Denied while sending email from AWS SES in ElasticBeanstalk (Django application)
I have recently (noticed) that I'm getting the following error in my Django application running on AWS An error occurred (AccessDenied) when calling the GetSendQuota operation: User: arn:aws:iam::123412341234:user/USER-IAM-NAME is not authorized to perform: ses:GetSendQuota with an explicit deny in an identity-based policy My user has full SES access via the direct policy AmazonSESFullAccess. In order to ensure GetSendQuota is explicitly stated, I have also added this inline policy { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "ses:SendEmail", "ses:SendRawEmail", "ses:GetSendQuota" ], "Resource": "*" } ] } I do not understand how to fix this. Help would be greatly appreciated -
What is the best option for Django+Celery in Google Cloud run?
We currently have an application which runs in Django and background tasks are in Celery. Now, we need to move to Google Cloud Run, and how to Celery in that case, since celery can not be run in Google cloud run (because it is serverless). I have background tasks like generate video (which may take around 10 minutes) and like generate image, and also sending requests to other services asynchronously. For sending asynchronous request to other services, I used Google Tasks, but the functions for generating video is in my service actually, but Google Task requires to send in this format: "http_request": { 'http_method': tasks_v2:HttpMethod.POST, 'url': url } Is there something that I need to put my function just in background task as celery does simply? What will be the best option for my case to use for background tasks? -
Can you use HTMX with datatables?
I have this in my datatables: columns: [ { data: 'product.item_code', className: 'text-start align-middle', render: function (data, type, row) { return '<a href="#" class="btn btn-primary" hx-post="/app/function/" hx-trigger="click" hx-target="#details" hx-swap="beforeend">' + row.product.item_code + '</a>' } } I am not able to get into the hx-post function when the anchor tag is in the datatable but works if it's in a regular HTML page -
After adding the HOST setting in django, I get a utf-8 error when creating a superuser
I am new to django. I am trying to open my project with a postgresql database in docker. There is no problem in the build process, but when I try to create a superuser, I get a utf-8 error. yml file services: app: build: . volumes: - .:/project ports: - "8000:8000" image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db postgres_db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data ports: - '5432:5432' environment: - POSTGRES_DB=project - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_data: {} docker file FROM python:3.12.7 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ libpq-dev build-essential WORKDIR /project COPY requirements.txt /project/ RUN pip install -r requirements.txt COPY . . settings database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'firstproject', 'PASSWORD': 'postgres', 'USER':'postgres', 'HOST': 'postgres_db', 'PORT': 5432, } } Error Traceback (most recent call last):File "D:\django code\first\firstp\manage.py", line 22, in <module>main()File "D:\django code\first\firstp\manage.py", line 18, in mainexecute_from_command_line(sys.argv)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_lineutility.execute()File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management_init_.py", line 436, in executeself.fetch_command(subcommand).run_from_argv(self.argv)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argvself.execute(*args, **cmd_options)File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 88, in executereturn super().execute(*args, **options)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 457, in executeself.check_migrations()File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 574, in check_migrationsexecutor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\executor.py", line 18, in initself.loader = MigrationLoader(self.connection)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\MONSTER\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\migrations\loader.py", line 58, … -
Django returns "Authentication credentials were not provided" when I attempt token authentication
(I tried the solutions in similar questions, but they didn't work for me). I am creating a simple Django REST based web-app, where a user will register, create some events, log in later and view events. Here's the event's view: class EventGetCreate(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request): created_user = request.user events = Event.objects.filter(creator=created_user) serializer = EventSummary(events, many=True) return Response(serializer.data) Its urls.py is as below: from django.urls import path, include from . import views app_name = 'event' urlpatterns = [ ... path('eventviewall/', views.EventGetCreate.as_view()), ] In core/urls.py, I have this to obtain the token: from .views import UserViewSet from rest_framework.authtoken.views import ObtainAuthToken, obtain_auth_token app_name = 'core' router = routers.DefaultRouter() router.register('users', UserViewSet) urlpatterns = [ path('auth/', obtain_auth_token), path('register/', include(router.urls)), ] Using postman, I can login successfully and get the token: Send request to http://127.0.0.1:8000/api/auth/ and get the following (example token): { "token": "xxyyzz" } Now what I want to do is to send this token in a get request, and view the events the user created. I send the request to http://127.0.0.1:8000/event/eventviewall/, with the above token set in Authorization tab -> Bearer token. However, I get the following response: { "detail": "Authentication credentials were not provided." } Now, if … -
Django: Favicon Not Displaying for Extracted Link Previews
I'm developing a Django application where users can create blog posts that include links. I want to display a preview of these links, including the website's favicon. However, despite implementing the logic to extract the favicon from the linked websites, it doesn't show up in the frontend. Here’s what I’ve implemented: Model Definition: I have a BlogPost model that includes a title, content, and a timestamp. from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) def get_link_previews(self): links = extract_links(self.content) previews = [] for url in links: previews.append(fetch_link_preview(url)) return previews Link Extraction Logic: I use regex to extract links from the blog post content. import re def extract_links(text): url_pattern = r'https?://[^\s]+' return re.findall(url_pattern, text) Preview Extraction Logic: I use requests and BeautifulSoup to extract the title, description, image, and favicon from the linked page. import requests from bs4 import BeautifulSoup def fetch_link_preview(url): try: response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') title = soup.title.string if soup.title else 'No Title' description = soup.find('meta', attrs={'name': 'description'}) description_content = description['content'] if description else 'No Description' image = soup.find('meta', attrs={'property': 'og:image'}) image_content = image['content'] if image else None # Find the favicon favicon_url = None for link in … -
Django system Not Logging User Out on Browser/Tab Close (Chrome/Safari)
Safari Incognito: Sessions expire as expected. Chrome Incognito: Sessions don't expire, regardless of settings. Regular Safari/Chrome: Sessions don't expire on tab or browser close. #middleware.py if manager: if client.logout_browser_close_manager: request.session.set_expiry(0) request.session.modified = True #settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True I can confirm the middleware.py is added to the middleware configuration in settings.py The session cookie shows session instead of a date with the following code, but does not log the user out. -
PyCharm autocomplete not working for context variables in Django templates
Normally, PyCharm autocomplete (code completion) works for context variables in Django templates. For example, if the context is {"question": question}, where question is an instance of the Question model, PyCharm will offer autocomplete suggestions when I start typing {{ question. }}, like this: However, in my current Django project, PyCharm autocomplete fails to work for context variables in Django templates. Even pressing Ctrl + Space will not bring up code completion suggestions: I think that I have everything configured in PyCharm for Django as usual for this project, although I could be mistaken. It's a larger project, so I suspect that something about the project structure itself might be causing the problem. Other convenience features are still working in Django templates, e.g., Emmet abbreviations, auto-closing of {{ and {%, etc. At first, I suspected the problem was that I have the models, views, etc., split out into multiple files. For example, instead of all models being contained in a single models.py file, the models are organized like this: models/ __init__.py model_a.py model_b.py model_c.py However, I don't think this is causing the autocomplete failure, because when I created a small Django project and organized it this way, autocomplete still worked for … -
Adds extra www when entering django admin panel
My website worked very well yesterday but today i have a problem. My website is https://www.622health.com.tr When i write https://www.622health.com.tr/admin and click enter, Its redirect to https://www.www.622health.com.tr/admin I made some redirect things for example 622health.com.tr to www.622health.com.tr , but this problem i removed all redirects but still i have an error. How can i fix this. I use ai for this but nothing. -
Django Postgres Json Filtering
there is a django model Model. It has a JSONField type field. There are approximately 1000 json files in postgresql in the table of this model. Json has a strict structure. 'food' -> foodid -> 'field' -> fieldname -> {....}. There can be arbitrary values instead of foodid and fieldname. How do I get unique possible pairs (foodid, fieldname) from postgres? Model.objects.annotate( foodid=Func( F('food'), function='jsonb_object_keys', output_field=models.CharField() ) ).annotate( field_name=Func( Value('food__') + F('foodid') + Value('__field'), function='jsonb_object_keys', output_field=models.CharField() ) ).values_list('food_id', 'field_names') The first annotate works. In the second annotate, I want to take the food_id field from the first annotate, but simply specifying F('foodidid__field'), the postgres will look for the foodid field in the table itself which does not exist. -
Django Error: DisallowedHost - Invalid HTTP_HOST header when using custom domain from Namecheap
I recently deployed a Django application on AWS EC2 and successfully accessed it via its public IP. I then purchased a domain from Namecheap (www.myproject.com) to use instead of the IP address. After configuring the domain, I encountered the following error when running Gunicorn with the command: gunicorn –bind 127.0.0.1:8001 wsgi:application Error traceback: DisallowedHost at / Invalid HTTP_HOST header: 'www.myproject.com,www.myproject.com'. The domain name provided is not valid according to RFC 1034/1035. Request Method: GET Request URL: http://www.myproject.com,www.myproject.com/ Django Version: 5.1.1 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'www.myproject.com,www.myproject.com'. The domain name provided is not valid according to RFC 1034/1035. Exception Location: /home/ubuntu/myproject/.venv/lib/python3.12/site-packages/django/http/request.py, line 151, in get_host Raised during: transcribe_audio.views.index Python Executable: /home/ubuntu/myproject/.venv/bin/python3 Python Version: 3.12.3 Python Path: ['/home/ubuntu/myproject/e', '/home/ubuntu/myproject/.venv/bin', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/ubuntu/myproject/.venv/lib/python3.12/site-packages', '/home/ubuntu/myproject'] Server time: Sun, 13 Oct 2024 13:37:50 +0000 From the error, it looks like the HTTP_HOST header is somehow being duplicated (www.myproject.com,www.myproject.com), which is causing the request to fail. I'm unsure why this duplication is happening and how to resolve it. NGINX Configuration: Here’s my NGINX config file: server { listen 80; server_name myproject.com www.myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/your/static/files; } location / { proxy_pass http://127.0.0.1:8001; … -
Authentication Cookie Not Sent with Axios Request in Browser
I'm having trouble with cookie-based authentication in my Django + React app. I've set the cookie on the backend, but it's not being sent with subsequent requests from the frontend React (Using Vite) app running on Google Chrome. I'm trying to implement authentication using cookies in a Django backend using Simple JWT. After a successful login, I set an authentication cookie ("CAT") in Django. Here’s the code I use to set the cookie: final_response.set_cookie( "CAT", combined_token, httponly=True, secure=False, samesite="None", max_age=86400, path="/", ) return final_response Setting.py at the Django server: CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = ["http://localhost:5173/"] CORS_ALLOW_CREDENTIALS = True SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin" I can see the cookie stored in Chrome after logging in: However, when my React app makes subsequent requests, the browser doesn’t seem to include the cookie, and I get an authentication failure ("Cookie not found"). Here’s my Axios request setup in the React app: try { const auth_response = await axios.get( "http://my-django-server/api/auth/auth-checker", { headers: { "Content-Type": "application/json", }, withCredentials: true, timeout: 5000, } ); console.log(auth_response?.data); if (auth_response?.status === 200) { navigate("/profile"); } else { console.error("Unauthorized access. Please try again."); } } catch (error) { console.error("An error occurred. Please try again.", error); } Manual authentication works: Interestingly, when I … -
Products Not Filtering Correctly with AJAX in Django
I'm working on an e-commerce website using Django and jQuery to filter products based on selected criteria (price range, categories, and vendors). While the AJAX request seems to be sent correctly and I receive a response, all products are still displayed on the page, regardless of the selected filters. What I've Implemented: JavaScript (AJAX) Code: $(document).ready(function() { function filterProducts() { let filter_object = {}; // Get price range values let min_price = $("#price-min").val() || 0; let max_price = $("#price-max").val() || 9999999; filter_object.min_price = min_price; filter_object.max_price = max_price; // Get selected categories and vendors $(".filter-checkbox").each(function() { let filter_key = $(this).data("filter"); filter_object[filter_key] = Array.from( document.querySelectorAll('input[data-filter=' + filter_key + ']:checked') ).map(function(element) { return element.value; }); }); // Send AJAX request to filter products $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function() { console.log("Filtering products..."); }, success: function(response) { console.log("Products filtered successfully."); $(".showcase").html(response.data); }, error: function(xhr, status, error) { console.error("Error filtering products:", error); } }); } // Event listener for checkbox and filter button $(".filter-checkbox, #filter-btn").on("click", filterProducts); }); HTML Structure: <div class="u-s-m-b-30"> <div class="shop-w"> <div class="shop-w__intro-wrap"> <h1 class="shop-w__h">PRICE</h1> <span class="fas fa-minus shop-w__toggle" data-target="#s-price" data-toggle="collapse"></span> </div> <div class="shop-w__wrap collapse show" id="s-price"> <form class="shop-w__form-p"> <div class="shop-w__form-p-wrap"> <div> <label for="price-min"></label> <input class="input-text input-text--primary-style" type="text" id="price-min" placeholder="Min"> … -
js not loading in html
This is the error that keeps coming up : 2/:47 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:47:64) onclick @ 2/:47 2/:48 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:48:63) But I just finished my javascript for the control carousel & the buttons but it seems like its not loading htmlwarningsjs I have tried and verified all my code but with no luck to find the issue I have also found something interesting when viewing my sources page in the inspectorhome page sources that shows my js scriptproject page that doesnt show my js in its sources let slideIndex = 1; showSlides(slideIndex) function moveSlide(n) { slideIndex += n showSlides(slideIndex) } function showSlides(n) { let slides = document.getElementsByClassName("carousel-item") if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length; } for (let i = 0; i < slides.length; i++) { slides[i].style.display = "none" } slides[slideIndex - 1].style.display = "flex" } {% extends 'base.html' %} {% load static %} {% block title %} Project Page {% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static 'css/project.css' %}" /> {% endblock %} {% block content %} <div class="project-card"> <div class="project-info"> <h1>{{ project.title }}</h1> <p> … -
Sending array of texts to Django, via POST, cannot get as array, getting string
I'm sending this data to Django, these texts are from multiple CKEditors chk_vals = ["Some text","Other text"]; const data = new URLSearchParams(); data.append("csrfmiddlewaretoken", "{{csrf_token}}"); data.append("tmplData", JSON.stringify(chk_vals)); fetch(uri, { method: 'post', body: data, }) .then(response => response.json()) .then(data => { It's from Chrome's network: tmplData: ["Some text","Other text"] Now Django: data = request.POST templateArr = data.getlist('tmplData') templateList = list(templateArr) And the length of the templateList is 1, it is getting it as one string and I cannot split it with ',' because these texts can contain ',' too. I also tried templateArr = data.getlist('tmplData[]') and sending without JSON.stringify, but nothing works data = request.POST templateArr = data.getlist('tmplData[]') templateList = list(templateArr) and this variable templateArr is empty -
Add primary key for existing table
I have database table core_config and basic model core.Config model connected to it. Initial migration has definition of id AutoField as default, but there is no PRIMARY KEY in database table (I have no idea why), so I can't create relations to it from another tables. Is there any ways to generate migration like 'add_constraint_pk_if_not_exists'? I want to make it with "if_not_exists" because there is a probability of existing PRIMARY KEY in other database mirrors.