Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Unable to access SSL cert
For various reasons, I am using pyodbc to connect to a postgres database which has SSL verification in my Django project views.py file. I can successfully connect by referencing the files in a local drive, however I am trying to get them to become part of the static files. Here is the relevant structure of the project: my_project -mysite -views -views.py -static -ssl -postgres -root.crt I have tried this in my views.py: from django.contrib.staticfiles.storage import staticfiles_storage rootcert = staticfiles_storage.url('ssl/postgres/root.crt') link = r"Driver={PostgreSQL UNICODE};Server=my_server;Port=my_port;Database" \ r"=my_db;Uid=my_uid;Pwd=my_pwd;sslmode=verify-ca;pqopt={" \ r"sslrootcert='" + rootcert + "' " \ r"sslcert='" + sslcert + "' " \ r"sslkey='" + sslkey + "'} " However, I get an error that says that the root cert does not exist. If I access this directly with the local server running (http://localhost_ip:port/static/postgres/root.crt), then it successfully downloads the file and in the logger I get a 200 message. On the Django error report, it says the rootcert variable is: '/static/ssl/postgres/root.crt' I have tried doing py manage.py collectstatic and py manage.py runserver --insecure but I still get the same error. In my settings.py file, here is how I have the static files set: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Why is django … -
Running django-q using elastic beanstalk on aws linux 2 instances
I use Elastic Beanstalk on aws to host my webapp which needs a task runner like django q. I need to run it on my instance and am facing difficulty doing that. I found this script https://gist.github.com/codeSamuraii/0e11ce6d585b3290b15a9ad163b9aa06 which does what I need but its for the older version of ec2 instance. So far I know I must run django q post deployment, but is it possible to add the process to the procfile along with starting the wsgi server. Any help that could point me in the right direction will be greatly appreciated. -
can not save pages any more in wagtail
when clicking publish or save draft I got this error wagtail.core.models.Page.DoesNotExist: Page matching query does not exist. this happens only with old pages, the newly created pages are being able to be created and saved without any errors NB: the new pages do not have children pages yet trying to find out what is causing this error despite I did not override the save method any suggestion or hint will be very helpful thank you -
django: pass an element to my template through context dictionary
in this view ... def home(request): context = {'page_title':'Volunteers', 'action':'<button class="btn btn-primary btn-small">Leave</button>'} return render(request, 'app/home.html', context) I try to send a button element (or some other HTML) through the context dictionary. I add it to the template like this <div class="row"> <div class="col-md-6"><h4>{{page_title}}</h4></div> <div class="col-md-6 text-md-right mt-1">{{action}}</div> </div> When the page renders, it just shows the text and does not allow it to be HTML. Any idea how I can get this to treat it as HTML? Thanks, Django beginner here finally coming from the dark side (PHP) =) -
How to load my javascript and css library using django webpack loader
I started using Django with Vuejs and Webpack, and I would like to load my dashboard CSS and Javascript files. I don't know how can I do that. this my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://127.0.0.1:8080/", outputDir: "./dist/", chainWebpack: (config) => { config .plugin("BundleTracker") .use(BundleTracker, [{ filename: "./webpack-stats.json" }]); config.output.filename("bundle.js"); config.optimization.splitChunks(false); config.resolve.alias.set("__STATIC__", "static"); config.devServer // the first 3 lines of the following code have been added to the configuration .public("http://127.0.0.1:8080") .host("127.0.0.1") .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .disableHostCheck(true) .headers({ "Access-Control-Allow-Origin": ["*"] }); } // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; how can I load my CSS styles and javascript ? -
how can I fix this error: Field 'id' expected a number but got ['Air Condition', 'Pool']?
I created a checkbox list by ManyToMany relationship as you can see here: class Store(models.Model): amenities = models.ManyToManyField(myChoices, blank=True) this model holds the following data: class myChoices(models.Model): choice = models.CharField(max_length=154, choices=AMENITIES) which get their choices from the following data options: AMENITIES = [ ("Electricity", "Electricity"), ("Water", "Water"), ("Gas", "Gas"), ("Elevator", "Elevator"), ("Maids Room", "Maids Room"), ("Garden", "Garden"), ("Air Condition", "Air Condition"), ("Pool", "Pool"), ] now as you can see the input will be multiple selections and the output will be the list of string but I got this error: Field 'id' expected a number but got ['Air Condition', 'Pool']. I don't know why the process ask me to write the id of data instead of the string object itself? also, How can I save the multiple objects in the database? -
Extract fields from a json in pyhon(Django)
Hello I am new to the python world, and I am learning, I am currently developing a WebApp in Django and I am using ajax for sending requests, what happens is that in the view.py I get a json, from which I have not been able to extract the attributes individually to send to a SQL query, I have tried every possible way, I appreciate any help in advance. def profesionales(request): body_unicode = request.body.decode('utf-8') received_json = json.loads(body_unicode) data = JsonResponse(received_json, safe=False) return data //**Data returns the following to me** {opcion: 2, fecha_ini: "2021-02-01", fecha_fin: "2021-02-08", profesional: "168", sede: "Modulo 7", grafico: "2"} // **This is the answer I get and I need to extract each of the values of each key into a variable** -
ImportError: 'tests' module incorrectly
I am working on unittest and when I type that : python manage.py test I got that : ImportError: 'tests' module incorrectly imported from '/home/user/Documents/myproject/dev/Project/tests'. Expected '/home/user/Documents/myproject/dev/Project/Project/Project/Project/Project/Project/Project/Project/Project/Project'. Is this module globally installed? Clearly, the expected path is wrong... Do you know where I can fix that ? Thank you very much ! -
Correct loading of jquery and usage of extended base.html templates within Django framework
I think this is not very related to Django more to jQuery and html behavior however what is the problem statement: Using a more or less standard base.html template base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> {% block stylesheets %} <!-- load Stylesheets --> {% endblock stylesheets %} <title> {% block title %} Base Title {% endblock title%} </title> </head> <body> <header> {% block header %} {% endblock %} </header> <main> {% block body %} {% endblock %} </main> <footer> {% block footer %} {% endblock %} </footer> {% block scripts %} <!-- Jquery 3.5.1 CDN --> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <!-- Popper 1.12.9 CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <!-- Bootstrap 4.0.0 CDN --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {% endblock %} {% block extrascripts %} {% endblock %} </body> </html> From this dashboard.html is derived by extension of base.html {% extends 'base.html' %} {% block title %}Dashboard{% endblock %} {% block body %} <div class="navbar navbar-expand justify-content-end"> some navigation bar content </div> some else stuff <div class="container"> <div class="row" style="margin-top: 1em"> {% include 'dash_cards/dash_card.html' %} </div> </div> some more content {% endblock %} {% block extrascripts %} {% endblock %} This works all fine … -
ftps in django app is not working after deploying on Apache2?
I am facing a problem after deploying my django project on apache2 server. In my django project I have connected to a remote ftp server using ftp with tls form ftplib. Which is working perfectly while I am running on development. Issue created after deploying it on apache2 server. Here ftps connection is not working. Can anyone help me to sort out this issue. -
celery_1 | ImportError: No module named 'hh_ru_django'
Watched many tutorials with dockerize celery + django, did like in the video.I think the problem is in docker-compose file, but i didn't found the solution.It took to much time, and i couldn't solve the problem. Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/hh_ru_django COPY requirements.txt /usr/src/hh_ru_django/ RUN pip install -r requirements.txt COPY . /usr/src/hh_ru_django docker-compose.yml version: '3.9' services: pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - pgdata:/var/lib/postgresql/data/ django: build: . container_name: django command: python manage.py runserver 0.0.0.0:80 volumes: - .:/usr/src/hh_ru_django ports: - "80:80" environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0/ depends_on: - pgdb - redis redis: image: redis ports: - '6379:6379' celery: image: celery command: celery worker -A hh_ru_django --loglevel=info volumes: - .:/usr/src/hh_ru_django depends_on: - django - redis volumes: pgdata: hh_ru_django/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hh_ru_django.settings") app = Celery("hh_ru_django") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() hh_ru_django/settings.py just the variables with broker CELERY_BROKER = os.environ.get("CELERY_BROKER", "redis://redis:6479/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", "redis://redis:6479/0") -
Modern method to run Django scripts as alternate user in Apache deployment
I have seen a number of similar questions, however none seem to have current solutions. I have a Django deployment running on Apache and mod_wsgi, as outlined in the Django guides here, hosted on an Ubuntu 20.04 LTS server. By default, Apache, and hence any python script run by it, is run as the www-data user. I have some scripts on my website that require privileged access to run, and for security reasons I would like to avoid granting the necessary privileges to www-data to run these scripts directly. Ideally I'd like a solution I can implement directly in the relevant views.py file to run the privileged script as a user with the permissions to do so only after inputs have been sanitized. What are my options to achieve this? As an example of a script requiring privileged access: my company uses this web portal for (among other things) setting up remote servers at client sites. That setup requires ssh access, which is restricted to certain users, and should not be granted to the www-data user. I have considered recreating the privileged scripts as daemon processes, however they do not need to be run frequently so I don't feel it's … -
Wagtail adds '#' to {{page.slug}} in address bar
I'm using Wagtail for a blog site with auto-populating blog links on a listing page. However, when I click the link for the blog page, it adds a '#' to the address bar. So, for example, I am working on localhost with the blog address of http://127.0.0.1:8000/blog/ and once I click on the blog link, with slug blog-slug, I get http://127.0.0.1:8000/blog/#/blog-slug. I am not sure why it is adding the hash tag at a location even behind the parent page 'blog'. This is the code I have on the blog listing template: {% for post in all_posts %} <figure class="item standard" data-groups='["all"{% for tag in post.tags.all %},"{{tag}}"{% endfor %}]'> <div class="portfolio-item-img"> {% image post.blog_image max-350x200 as img %} <img src="{{img.url}}" alt="{{img.alt}}" title=""> <a href="{{post.slug}}" class="ajax-page-load"></a> <!-- Blog slug --> <br> <i class="{{post.icon}}"></i> <p>{{post.gallery_text|safe|truncatewords:30}}</p> </div> <h4 class="name"> {{post.title}} </h4> <div class="post-info"> <div class="post-date"> <strong>Tags:</strong> {% for tag in post.tags.all %}| {{tag}} |{% endfor %} </div> <div class="post-date">{{post.published_date}}</div> </div> </figure> {% endfor %} Any ideas what could be going wrong? -
Django by Example Chapter 5. urllib.error.URLError
I am stuck on chapter 5 on the bookmarks tools that I followed in the book. I am using Django 3.1 and following (I have checked evrything almost 10 times) this version on github : [https://github.com/PacktPublishing/Django-3-by-Example/tree/master/Chapter05][1] But I still have this error : urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)> File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py", line 1319, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1230, in request self._send_request(method, url, body, headers, encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1276, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1225, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1004, in _send_output A message_body may be specified, to be appended to the request. """ self._buffer.extend((b"", b"")) msg = b"\r\n".join(self._buffer) del self._buffer[:] self.send(msg) if message_body is not None: # create a consistent interface to message_body if hasattr(message_body, 'read'): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 944, in send self.connect() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect self.sock = self._context.wrap_socket(self.sock, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() During handling of the above exception, another exception occurred: File "/Users/ricardoponce/Documents/WebSocial/venv/lib/python3.8/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/Users/ricardoponce/Documents/WebSocial/venv/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = … -
CORS problem with Django setup in Digital Ocean Spaces
I have a django website hosted inside a Digital Ocean Droplet and we decided recently to move all static and media files to a Digital Ocean Spaces. So far it's working under some situations and not working for others. I added my origin and allowed headers to CORS configuration in Spaces as below: When I run "collectstatic" from my Droplet its copying my files to Spaces and it's working perfectly for the website. When I go to admin, icons and some other static resources are not being loaded, getting a 403 error (FORBIDDEN), as below: Looking more in deep I went to Digital Ocean Spaces to check files permissions, all files have the same permission (private) and all are stored correctly. So, first question, why some of them work for the main website and others specially in admin don't? However, other weird things are happening also when I try to load some files via XMLHttpRequest using THREE.js. All I get is this message: Access to XMLHttpRequest at 'https://nyc3.digitaloceanspaces.com/MYSPACE/file.stl?AWSAccessKeyId=2I6LYDQXCYZWQHXJVRSO&Signature=4lnHY7WnPh5jracKZoEj7jqKAGc%3D&Expires=1612816348' from origin 'https://shopping.mydomain.com.br' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Why I'm getting this error if CORS are set in Digital Ocean Spaces and … -
trouble with unit testing graphene-django schema
when i run this test def test_get_all_messages(mock_resolve): assert mock_resolve is Query.resolve_all_messages MSG_TXT = 'abc' mock_resolve.return_value = [Message(id=1, text=MSG_TXT)] query = ''' query{ allMessages{ id } } ''' result = schema.execute(query) assert mock_resolve.called_once() assert not result.errors EXPECTED_DATA = { 'allMessages': { 'id': 1 } } assert result.data == EXPECTED_DATA I get this error RuntimeError('Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it i'm trying to run the unit test in isolation and not using the db Adding pytest.mark.django_db @pytest.mark.django_db @patch(RESOLVE_ALL_MESSAGES) def test_get_all_messages(mock_resolve): assert mock_resolve is Query.resolve_all_messages MSG_TXT = 'abc' mock_resolve.return_value = [Message(id=1, text=MSG_TXT)] query = ''' query{ allMessages{ id } } ''' result = schema.execute(query) assert mock_resolve.called_once() assert not result.errors EXPECTED_DATA = { 'allMessages': { 'id': 1 } } assert result.data == EXPECTED_DATA Now i get this error E Differing items: E {'allMessages': []} != {'allMessages': {'id': 1}}``` -
Django select_related/prefetch_related not working as expected
In my Admin page I have Order model with TabularInline of OrderItem model class OrderItemStackAdmin(admin.TabularInline): model = OrderItem extra = 0 fieldsets = ( (_('Product'), { 'fields': ('product', 'variant') }), (_('Add-Ons'), { 'fields': ('product_add_ons', 'add_ons_note') }), (_('Price'), { 'fields': ('quantity', 'product_price', 'add_ons_total_price') }), (_('Discount'), { 'fields': ('discount',) }) ) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related( "customer_order", "product", "variant" ).prefetch_related('product_add_ons') Two FK are given: Product, Variant One Many to Many given: product_add_ons With select_related/prefetch related i manage to reduce queries, however, 35 duplicate/similar queries are found. all duplicated queries share this NO SCROLL CURSOR WITH HOLD FOR SELECT Please note removing the inline removes all duplicated queries. -
Why can't object_set get unique items?
I am trying to pull a user's objects viewed from the Product model. It's pulling all of the user's viewed products right now but with duplicates. I have tried putting .distinct() in views = request.user.objectviewed_set.by_model(Product, model_queryset=False).distinct() but it does not work, I think because that is just pulling the rows for Object viewed, not the products themselves. Appreciate the help! from html {% for obj in object_list %} <div class='col-xl-12'> {% include 'products/card.html' with instance=obj.content_object %} </div> {% endfor %} from products/card.html <div class="card" style="width: 20rem;"> <a href="{{instance.get_absolute_url}}"> <img style="width:30%;" src="{{instance|get_thumbnail:'sd'}}" alt="{{instance.title}} logo"> </a> <div class="card-body"> <h4 class="card-title">{{ instance.title }}</h4> <p class="card-text">{{ instance.description|linebreaks|truncatewords:14 }}</p> </div> from products models.py class Product(models.Model): seller = models.ForeignKey(SellerAccount, null=False, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False) slug = models.SlugField(unique=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): #defining str as self and returning self, which is used ie in admin.py return self.title def get_absolute_url(self): view_name = "products:detail" return reverse(view_name, kwargs={"slug": self.slug}) from analytics models.py class ObjectViewedQuerySet(models.query.QuerySet): def by_model(self, model_class, model_queryset=False): c_type = ContentType.objects.get_for_model(model_class) qs = self.filter(content_type=c_type) if model_queryset: viewed_ids = [x.object_id for x in qs] return model_class.objects.filter(pk__in=viewed_ids) return qs class ObjectViewedManager(models.Manager): def get_queryset(self): return ObjectViewedQuerySet(self.model, using=self._db) def by_model(self, model_class, model_queryset=False): return self.get_queryset().by_model(model_class, model_queryset=model_queryset) class ObjectViewed(models.Model): user = models.ForeignKey(CustomUser, … -
How to create a middleware to intercept request before url discovery so that unauthorized users cannot learn urls?
I was requested to write a middleware for my company's Django project to avoid repeating code for user authentication when accessing admin/ pages. For this, I wrote a basic LoginRequiredMiddleware. I exhausted my knowledge on this middleware thing and now I have to give it some steroids to it so it can avoid external parties discovering existing views in our project especially for our /api/. Right now, when someone tries to access something like: api/v1/existing-page, Django, goes through the URLs and when it finds a url-view pair, it then goes through authentication and the middleware comes in the picture. However, if an unauthenticated user tries to access: api/vi/foo-does-not-exist/ page, then I get a Not Found page (error 404). What I would like to do is have a middleware intercepting the request and asking for user authentication (error 401 unauthorized) before Django can start scanning for an existing URL. This is a security measure to prevent anyone from learning the existing URLs/views of the project. The thing is that I don't know where to begin. Is this possible to accomplish with a middleware? If yes, can I use the same middleware or it would be better to write a separate one? … -
Increasing image size after uploading React js + Django
I have a react frontend backed by Django rest API. I use react-cropper to crop and upload images. When I upload images, the image size gets increased. Ex:- When I upload 149.5kb image it increases to 1.5MB. I notice that size in my API calls. But when I directly upload images to Django admin it remains in the same size. I can not figure out the exact reason for this. Photos are saved in DIgitalOcean Spaces. Cropper <div className="cropper_be"> <Cropper style={{ height: '100%', width: "100%" }} initialAspectRatio={16 / 9} aspectRatio={16 / 9} preview=".img-preview" src={image} viewMode={1} guides={true} minCropBoxHeight={10} minCropBoxWidth={10} background={false} responsive={true} autoCropArea={1} checkOrientation={false} onInitialized={(instance) => { setCropper(instance); }} /> </div> //function for base64 to blob const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; } -
Django. How i can run my function every 5 second and update the page
I have a Django app. I want that every 5 seconds, the script will update DB dates and reload my page. I tried with a simple: while(), but this stopped all code. I tried with async function, but nothing is working My code: `from django.shortcuts import render from django.http import HttpResponse from django.db import models from main.models import Prices import requests from bs4 import BeautifulSoup import time # Create your views here. timeout = 5 def parseSite(): Prices.objects.all().delete() URL = "https://www.coindesk.com/price/bitcoin" page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') cont = soup.find(class_="coin-info").find_all(class_="coin-info-block") final_price = cont[0].find(class_="price-large").text bitoc = Prices(curency_type = "bitcoin", curency_price = final_price) bitoc.save() parseSite() def dates(): bitoc2 = Prices.objects.get(curency_type= "bitcoin") return bitoc2 def index(request): data = dates() return render(request, 'main/index.html', {'data': data}) ` -
¿Cómo puedo utilizar el username de un usuario como campo de una tabla en sqlite3?
I'm new in this and I'm trying to use in Django the username as id in other model. I import the base model for User in Django, but when i'm doing: author = User().get_username() The field doesn't appear. Is there any method to use the "username" from the User model? Thanks for your help and sorry for my English. -
Django and Celery - Insert action when user goes previous page
I would like to stop a certain task when a user opens the edit page for this certain task. What I would like to avoid is that when the user opens the edit page and goes to the previous page without saving that the task remains disabled. Is there a way to put an action, to re-activate the task, in case the user pushes the return button on his webpage? Thank you! -
Issues with Django deployed on the server only
This is the error message Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 576, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <module 'api.urls' from '/app/api/urls.py'> (None:None) 'api/'>], [<URLResolver <URLPattern list> (admin:admin) 'admin/'>]], 'path': ''} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'URLResolver' object has no attribute 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 843, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/template/base.py", line 848, in _resolve_lookup raise VariableDoesNotExist("Failed lookup for key " django.template.base.VariableDoesNotExist: Failed lookup for key [name] in <URLResolver … -
How to upload multiple files asynchronously before form submit in Django?
Intro: I have Django web app where users are allowed to create posts. Each post has multiple images that are associated with that post. What I want to do: I want such that when the user uploads each image to a form. I want to use Filepond javascript library for remove image, add more image and previews of selected images. The issue: The code below is getting error Reason given for failure: CSRF token missing or incorrect. I want to add multiple images to a django form asynchronously before form submit.I have the Javascript code for uploading of the images on the client side and asynchronously adds it to my server. All I need to do is give it a endpoint, which is a simple url I have a rough idea of how I plan to achieve this. I would be grateful for any help. MODELS class FileModel(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE) file = models.FileField(upload_to='stories', blank=True, null=True) VIEWS def post_image_create(request, post): for f in request.FILES.getlist('file'): FileModel.objects.create(file=f) f.save() if post: post = f class NewsCreateView(CreateView): form_class = FileForm template_name = 'news/news_create.html' success_url = '/' def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post_image_create(request=self.request, post=post) # This function is defined above …