Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decode django HttpResponse
I am working on calendar view on my project. But I met a problem with not-latin symbols I tried to transfer data to script in template and it worked good, but only with latin symbols. I used HttpResponse like view.py events = [] # place holder for event in user_events: temp = {"title" : str(event.title).encode('utf-8').decode('utf-8'), "start": str(event.startDate)[0:-6], "end": str(event.endDate)[0:-6]} events.append(temp) events.append(',') response = HttpResponse(events, content_type='text/html; charset=utf-8') but i got this after HttpResponse instead of this What i need to do? probably you know other ways to to transfer code-like data to templates? -
What is the equivalent of following query in Django python?
SELECT REPLACE(field1, pattern, 'desk' ), REPLACE(field2, pattern, 'desk') FROM table_name WHERE field1 LIKE pattern OR field2 LIKE pattern; The following is my model. How can I code above sql in django python? class news(models.Model): dbemail = models.CharField(max_length=100) dbsubject = models.CharField(max_length=300) dbdetail = models.CharField(max_length=5000) dbimage = models.CharField(max_length=100) dbdatetime = models.DateTimeField(auto_now_add=True) def __str__(self): return "Email: " + self.dbemail + " | Subject: " + self.dbsubject + " | datetime: " + str(self.dbdatetime) I want to query on subject and detail and replace the founded text with another text This is what I did but it is not doing the job: usernews = news.objects.filter(dbsubject__contains=search).order_by('-dbdatetime').values() -
Django Return Info Message If Database Unavailable
I have Django set up split database mode, with default being the write-primary, and replica1 being a read-only replica. I have routers enabled in Django settings so that writes go to the default db and db_for_read returns the replica1 database. However, when the read replica is down, the server still runs. But requests spin forever and eventually timeout. Is there a way to detect when the database is down, and if so, return an informational response instead of just spinning forever. Maybe a middleware to check the connection or something in the view itself? We don't want to allow read fallback on the primary database. -
Serializing with Django
I am getting very weird behaviour during serialization when retrieving data from Database during GET request. The idea is to get the following information: municipality_id (included in municipality table) municipality_name(included in municipality table) total_population (included in demographics table which is connected to community table and associated with a municipality) municipality_distance (included in municipalityDistance table) I am posting this question as a self check to confirm I have everything I need and to open the analysis on this. Because the highest hierarchy table is Community, so I created hybrid properties to get the above information (Not sure if this is the best approach). The following sections are the models: general.py: class Municipality(models.Model): area_id = models.IntegerField(null=True) name = models.CharField(max_length=127) project.py: class MunicipalityDistance(models.Model): municipality_id = models.ForeignKey(Municipality, on_delete=models.SET_NULL, db_column="municipality_id", null=True) municipality_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) @property def name(self): return self.municipality_id.name class Project(models.Model): project_name = models.TextField(blank=True, null=True) municipality = models.ForeignKey('Municipality', on_delete=models.SET_NULL, blank=True, null=True) nearest_municipalities = models.ManyToManyField(MunicipalityDistance, db_column="nearest_municipalities", blank=True, null=True) class Meta: ordering = ("id", ) demographics.py: class Demographics(models.Model): census_subdivision_id = models.IntegerField(primary_key=True, null=False, blank=False) census_subdivision_name = models.CharField(max_length=127) pop_total = models.IntegerField(null=True) class Meta: ordering = ("census_subdivision_id", ) community.py: class Community(models.Model): place_id = models.CharField(null=True, blank=True, max_length=255, unique=True) place_name = models.CharField(null=True, blank=True, max_length=255) census_subdivision = models.ForeignKey('Demographics', null=True, db_column="census_subdivision_id", … -
unknown shorthand flag: 'r' in -rm
docker-compose run -rm app sh -c "python manage.py startapp core" firstly this command is working wiht -rm flag but not it is showing "unknown shorthand flag: 'r' in -rm" Error i am trying to solve this proble but unable to find something -
Unable to add Styling for Django Template
I have created a HTML page using Django,where I have four different categories of forms named as Live, Report, Planning and Old. These four categories of forms are connected with SQL server to show various sub-forms under these categories. I can get all the forms here and my below code is working fine. The name of the Page is "FORM TRACKING APP".I have added two more logics here which shows the different user names when they logged in and a logout link. Here the user name and logout is in the top right of the page, also below that I have link which creates new form. About the styling I am facing few issues that I want to do. 1.I want to create a fixed Navbar where it shows the page name in the middle and shows user name in the right side of the bar with an image and also with the logout link. 2.Want to replace link for Add new form with a button. 3.Want to create borders for four categories of forms. My code is given below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title> </head> <body> <h1><b><center><u>FORM TRACKING APP</u></center></b></h1> … -
Python: how to schedule a task to happen after 1 hour?
I am creating a user registration that requires an activation code. I want the activation code to expire after 1 hour, so I did this: def register(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.data) if form.is_valid(): email = request.POST.get('email') password = request.POST.get('password') user = get_user_model() user = user_manager.create_user(email=email, password=password) # Generate an activation code and store it in the database code = generate_activation_code() # activation = Activations.objects.create(user=12, code=code) # Schedule the activation code for deletion after 1 hour schedule_activation_code_deletion(user, code) # schedule_activation_code_deletion(user, code) # Send the activation code to the user's email address subject = "Your verification code" message = f"Your verification code is {code}" send_email(subject, message, settings.EMAIL_HOST_USER, email) return Response('User created.') return Response(status=400) def schedule_activation_code_deletion(user_id, code): queue = django_rq.get_queue('default') queue.enqueue_in(datetime.timedelta(minutes=1), test) With this code I get Error while reading from localhost:5432 : (10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None) Is there any other library that works? -
Django crash when installing Tensorflow
I want to use a tensorflow model in a django API deployed with docker Problem : Importing tensorflow in API Django will stop the server view.py: from rest_framework.parsers import MultiPartParser from rest_framework.response import Response from rest_framework.views import APIView from django.http import JsonResponse import random import numpy as np import tensorflow as tf if I comment the tensorflow line it works but if I don't my docker will stop with the following output : terminal: Attaching to web-1 web-1 | Watching for file changes with StatReloader web-1 | Performing system checks... web-1 | web-1 exited with code 252 OS : Ubuntu 22.04 ( VM ) Dockerfile : FROM tensorflow/tensorflow ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ I also tried FROM python:3.9 and RUN pip install tensorflow docker-compose.yml version: '3.9' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 --verbosity 2 volumes: - .:/app ports: - "8000:8000" requirements.txt Django==4.2.1 djangorestframework==3.14.0 pandas==2.0.1 numpy==1.24.3 django-cors-headers==3.14.0 tqdm==4.62.3 I am really stuck with this. I hope I did not forget any critical info if so feel free to ask. I would appreciate any help I probably miss something . Thank you a lot and … -
Django - Paython: TypeError at /news news() got an unexpected keyword argument 'dbemail'
Here is my model: class news(models.Model): dbemail = models.CharField(max_length=100) dbsubject = models.CharField(max_length=300) dbdetail = models.CharField(max_length=5000) dbimage = models.CharField(max_length=100) dbdatetime = models.DateTimeField(auto_now_add=True) def __str__(self): return "Email: " + self.dbemail + " | Subject: " + self.dbsubject + " | datetime: " + self.dbdatetime Here is a function in my view that is responsible for handling post method for the news: def news(request): if 'email' in request.session: email = request.session['email'] if request.method == 'POST' and request.FILES['newsimage']: myfile = request.FILES['newsimage'] fs = FileSystemStorage(location='newsimages/') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) newsinfo = newsForm(request.POST) if newsinfo.is_valid(): subject = newsinfo.cleaned_data['subject'] detail = newsinfo.cleaned_data['detail'] newsData = news(dbemail = email, dbsubject = subject, dbdetail = detail, dbimage = uploaded_file_url) newsData.save() message = "News has been added" form = newsForm() return render(request, 'news.html', { 'myform': form, 'message': message }) else: form = newsForm() return render(request, 'news.html', {'myform': form}) else: request.session['profileError'] = "You have to sign up or log in first!" return redirect('login') Error is on this line: newsData = news(dbemail = email, dbsubject = subject, dbdetail = detail, dbimage = uploaded_file_url) This is the error detail: TypeError at /news news() got an unexpected keyword argument 'dbemail' Request Method: POST Request URL: http://localhost:8000/news Django Version: 4.2.1 Exception Type: TypeError … -
Exclude duplicate elements with lower priority (Django)
I have the following model: class Action(BaseModel): action_id = models.IntegerField(unique=True, db_index=True) name = models.CharField(max_length=25) object = models.CharField(max_length=25) priority = models.IntegerField(default=0) Suppose there are two 4 objects: {"action_id":1, "name":"read", "object":"post", "priority":1} {"action_id":2, "name":"write", "object":"post", "priority":2} {"action_id":3, "name":"read", "object":"user", "priority":1} {"action_id":4, "name":"update", "object":"user", "priority":2} How can I filter out objects with the same object value, and leave only those with a priority higher in the duplicate set? [{"action_id":2, "name":"write", "object":"post", "priority":2}, {"action_id":4, "name":"update", "object":"user", "priority":2}] I tried filtering methods with - annotate, Max, Count and filter but duplicates are returned if i filter by priority -
Django: How to add data to 2 tables at the same time
Having the following table models, I would like to write data from the form to 2 tables at the same time. class Order(models.Model): department = models.CharField(max_length=20) responsible = models.CharField(max_length=20) month = models.DecimalField(max_digits=2, decimal_places=0, default=0) year = models.DecimalField(max_digits=4, decimal_places=0, default=0) def __str__(self): return str(self.department) class Article(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=20) quantity = models.DecimalField(max_digits=5, decimal_places=0, default=0) order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="Order") comments = description = models.CharField(max_length=200) def __str__(self): return str(self.name) I would like a new order to be created simultaneously when the user adds the first item. Then the user would add articles to this order and the data would be saved in one table. In addition, each item would have to have the ID of the order to which it was assigned. In the case of subsequent articles, there will be no problem, how to add this ID to the first added article? My question is: How to write data to 2 tables at once? -
filter feeds containing a similar hashtag using django-taggi
We have the django-taggi library which is related to the user feed, I need to generate the filter by tags according to the library in an example of the documentation is done in this way. Food.objects.filter(tags__name__in=["delicious"]) [<Food: apple>, <Food: pear>, <Food: plum>] Model Feed: class Feed(UUIDModel, TimeStampedModel, mongo_models.Model, TaggitManager): #Other fields class TaggitManager: hashtags = TaggableManager(through=UUIDTaggedItem) class Meta: abstract = True class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): pass ViewSet @extend_schema(description="", tags=["feed"]) class FeedViewSet(LPCDRModelViewSet): def _check_required_param(self, param_name): param_value = self.request.query_params.get(param_name) if not param_value: return exceptions.ValidationError( {"error": f"params {param_name} is required"} ) return None def get_queryset(self): if self.action == "feed_hashtag_list": error = self._check_required_param("hashtag") if not error: return Feed.objects.filter(hashtags__name__in=["demo", "red"]) When we want to query or filter by a tag we get the following error: django.core.exceptions.FieldError: Cannot resolve keyword 'hashtags' into field. Choices are: background, background_id, blocked, can_audio, can_be_shared_inside, can_be_shared_outside, can_commentary, can_download, can_duos, can_paste_video, comment_feeds, content, count_shared, created, draft, event, exclusive_adult_content, feed_event, feed_private, feed_type, finish_poll, friends_concrete, friends_concrete_id, friends_except, friends_except_id, id, is_announcement, link, link_external, mediafeed, modified, near, parent, parent_duos, parent_duos_feed, parent_duos_id, parent_feed, parent_id, programed, publish, questionfeed, reactions, reactions_feed_relation, reactions_id, special_announcement, sponsors, sponsors_id, state, state_id, time_to_programed, user, user_id, user_tags, user_tags_id -
Why TrigramSimilarity is not working on postgresql
I want change SearchRank with TrigramSimilarity but i got this error ProgrammingError at /search/ function similarity(character varying, unknown) does not exist LINE 1: ...ows_show"."description", '')), 'B')) AS "search", SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. My code: def search_content(query: str) -> QuerySet | None: if query: search_vector = SearchVector("name", weight="A") + SearchVector("description", weight="B") shows = ( Show.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) movies = ( Movie.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) episodes = ( Episode.objects.annotate( search=search_vector, similarity=TrigramSimilarity('name', query), ) .filter(similarity__gt=0.4) .values("id", "name", "baner", "release_date", "search", "similarity") ) qs = shows.union(movies, episodes).order_by("-similarity") return qs else: return None -
CORS error on sending API request via browser from a React pod to a Django pod
I've created a basic Django-React web application, and am trying to deploy it through Kubernetes, on my local system. But, while sending an API request from the frontend to the backend, I'm getting the following message alert on the browser: A server/network error occurred. Looks like CORS might be the problem. Sorry about this - we will get it fixed shortly. I have set up ingress to basically deploy the pods, and to connect them. The alert message looks like the following: On clicking the 'OK', the console logs the following: I have already tried setting the CORS headers in the axios request, as well as setting the Django settings as necessary. Here is the axios request: const baseURL = API_SERVER + '/api/'; // API_SERVER resolves to http://127.0.0.1:8000 const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', accept: 'application/json', }, }); And the Django settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ . . . 'corsheaders', . ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', . . . ] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1", "http://localhost:3000", "http://kubernetes.docker.internal", ] CORS_ALLOW_CREDENTIALS = False CORS_ORIGIN_ALLOW_ALL = True kubernetes.docker.internal is the URL through which I'm … -
Django-Crontab setting up wrong path in Cron table executables on Elastic Beanstalk
I realised my Cron jobs were not running on my server, so I connected to it and issued a crontab -e command, which output: 0 0 * * * /var/app/venv/staging-LQM1lest/bin/python3 /var/app/staging/manage.py crontab run a1d4c02847fcb8cb1b61b437ec1c399d 0 0 * * * /var/app/venv/staging-LQM1lest/bin/python3 /var/app/staging/manage.py crontab run 7332312af81aa515804fd180d12a2294 The problem is that manage.py is not in the /var/app/staging/ folder, that doesn't exist, but in /var/app/current/. Does anybody know where the staging come from and how can I replace it? I don't manipulate my Cron tab directly, but create my Cron jobs by using Django-Crontab and defining them in settings.py: CRONJOBS = [('0 0 * * *', 'app1.cron.task'), ('0 0 * * *', 'app2.cron.task')] (I don't know if this is anyhow related, but staging is indeed the name of one of my environments.) -
Django-tenants difference between django.db.connection.tenant and request.tenant
I am working on a multitenant Django application using django-tenants library. Getting the current tenant object can be done through one of the two ways: This can be used anywhere: from django.db import connection tenant = connection.tenant This can be used in views.py only where the request object is accessible: tenant = request.tenant So, why we have it added to request while it is globally accessible on the connection object? -
How to restrict a user's rights to click on a url, django
In my app, no anonimus uzer can switch to another profile, he only should know the pers_id. How can I forbid doing this? my views.py: @login_required def home(request): pers_id = request.GET.get('pers_id', None) if pers_id is None: return redirect('/') user_profile = Profile.objects.get(profile_id=pers_id) try: user_memories = Memory.objects.get(profile_id=pers_id) except Memory.DoesNotExist: user_memories = False context = {'memories': user_memories, 'user_profile': user_profile} return render(request, 'home.html', context) def vk_callback(request): try: vk_user = UserSocialAuth.objects.get(provider='vk-oauth2', user=request.user) vk_profile = vk_user.extra_data user_info = UserInfoGetter(vk_profile['access_token']) pers_id, first_name, last_name, photo_url = user_info.get_vk_info() try: user_profile = Profile.objects.get(profile_id=pers_id) except Profile.DoesNotExist: user_profile = Profile.objects.create( profile_id=pers_id, first_name=first_name, last_name=last_name, photo_url=photo_url ) user_profile.first_name = first_name user_profile.last_name = last_name user_profile.photo_url = photo_url user_profile.save() return redirect(f'/home?pers_id={pers_id}') except UserSocialAuth.DoesNotExist: pass return redirect(home) When the user take auntification he redirected to /home?pers_id={pers_id}. if authorized user knows the pers_id he can check antoher profiles. How can i fix it? -
I'm trying to make a searcher but when i send a request from my frontend in react Django doesn't get the data sent
Sorry for my English. When I'm trying to get the data sent in the frontend (its seems its working well because is generating a json with the searchValue) the function in django is not getting the data that i sent, the print(search) return None This is my code in Django: views.py: @csrf_exempt def search_locations(request): search = request.POST.get('search') print(search) results = [] if search: locations = Location.objects.filter(name=search) print(locations) for location in locations: results.append({ 'id': location.id, 'name': location.name, 'latitude': location.latitude, 'longitude': location.longitude }) return JsonResponse(results, safe=False) urls.py: urlpatterns = [ path('locations/', LocationsView.as_view(), name='locations'), path('locations/search/', search_locations, name='search_locations'), path('locations/<int:pk>/', location_detail, name='location_detail'), ] React code: const [searchValue, setSearchValue] = useState(""); const handleSearch = async (event) => { event.preventDefault(); await axios .post("http://127.0.0.1:8000/apilocations/locations/search/", { search: searchValue, }) .then((response) => { setPlaces(response.data); console.log(searchValue) console.log(response) console.log(places) }) .catch((error) => { console.error(error); }); }; When i use the searcher search return None -
Trying to access the other side of a ForeignKey in the django admin display
I'm working off the django tutorial, and I was trying to figure out how to call the other side of a ForeignKey. My models right now are just Question and Choice, and under class Choice right now I have: question = models.ForeignKey(Question, related_name="choice", on_delete=models.CASCADE) (the only change I made from the tutorial was adding related_name) Then when creating class QuestionAdmin, I added "choice" to list_display, hoping to show choice for a question. list_display = ["question_text", "choice", "pub_date", "was_published_recently"] In the tutorial, they do something with another class and "inlines" but I'm trying to keep this simple, and I was hoping I could just treat the related_name as another attribute of the Choice model. I've tried changing the name, and I get different error messages depending on which admin function I'm using (list_display, fields, etc.) but I'm mostly seeing this: TypeError at /admin/polls/question/ Is there a way to just access the choices as a regular attribute? Am I doing something wrong? -
Issues installing packages from requirements.txt for Django project
I'm working with Python 3.11.3 and I'm having difficulty installing from my requirements.txt file, this is what my output is: https://pastebin.com/0Tcqfjvz This is what my requirements.txt is: asgiref==3.6.0 autopep8==2.0.2 distlib==0.3.6 Django==4.2.1 django-dotenv==1.4.2 environ==1.0 filelock==3.12.0 platformdirs==3.5.0 psycopg2-binary==2.9.6 pycodestyle==2.10.0 python-dotenv==1.0.0 sqlparse==0.4.4 tzdata==2023.3 virtualenv==20.23.0 -
unable to install django debug toolkit
Im new to django and trying to learn the basics, but when i try to install django debug tool kit in a virtual environment the installations keeps on failing and i get an error. is it because i need a specific version of django? im not sure and would appreciate any help. in the terminal i used pipenv install django-debug-toolkit and get this: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing django-debug-toolkit... Resolving django-debug-toolkit... Installing... [ =] Installing django-debug-toolkit...[31m[1mError: [0m An error occurred while installing [32mdjango-debug-toolkit[0m! Error text: [36mERROR: Could not find a version that satisfies the requirement django-debug-toolkit (from versions: none) ERROR: No matching distribution found for django-debug-toolkit [0m Installation Failed -
Django DRF validation on GET method
I suppose that DRF framework / django has a better way to do that. class Providers(APIView): def get(self, request): from .doctor_search_helper import DoctorSearchHelper from .gmaps_helper import GMapsHelper localizacao = request.query_params.get("localizacao", None) especialidade = request.query_params.get("especialidade", None) plano = request.query_params.get("plano", None) tipo_estabelecimento = request.query_params.get("tipo_estabelecimento", None) distancia_maxima = request.query_params.get("distancia_maxima", None) if (not localizacao) or (localizacao == ""): return Response({"error": "localizacao is required"}, status=400) if (not especialidade) or (especialidade == ""): return Response({"error": "especialidade is required"}, status=400) if (not plano) or (plano == ""): return Response({"error": "plano is required"}, status=400) if (not plano) or (plano == ""): return Response({"error": "plano is required"}, status=400) if (not distancia_maxima) or (distancia_maxima == ""): return Response({"error": "distancia_maxima is required"}, status=400) Do DRF has any library that supports validation? -
Save data in a real-time application using websocket in Django
I developed a Django application to view live heart rate. For now, I generate the heart rate signal in a Jupyter Notebook and access it in Django using websocket for Python. When the connection with the Websocket closes, I want to record the entire received signal. How do I save this signal? My whole project is build on this model : Real_time_Django_App consumer.py from channels.generic.websocket import AsyncJsonWebsocketConsumer import json class DashConsumer(AsyncJsonWebsocketConsumer): print('==================') async def connect(self): self.groupname='dashboard' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self,close_code,signal): await self.channel_layer.group_discard( self.groupname, self.channel_name ) async def receive(self, text_data): datapoint = json.loads(text_data) val =datapoint['value'] await self.channel_layer.group_send( self.groupname, { 'type':'deprocessing', #function name to run 'value':val #value to send function } ) print ('>>>>',text_data) async def deprocessing(self,event,signal): valOther=event['value'] #@valOther = f'{valOther}' await self.send(text_data=json.dumps({'value':valOther})) Jupyter Notebook I tried to save each point individualy by accessing the Database in the receive function and modifying the instance stored but given the number of points and frequency at which they are send it doesn't seem to be a viable solution. Is it possible to save all the points send one time before closing the websocket ? Any help would be greatly appreciated! -
Customize the CSS classes passed to django form errors with custom `ErrorList`
I want to utilize Bootstrap for my django project and therefore always pass a CSS class to every form error. Let's name it "custom_class". I read the docs and it tells me that theoretically this setup should work: from django.forms.utils import ErrorList class BootstrapErrorList(ErrorList): error_class = "custom_class" class BaseForm(forms.BaseForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = BootstrapErrorList class FormA(forms.ModelForm, BaseForm): # ... class FormB(forms.Form, BaseForm): # ... There is no error or anything but also the "custom_class" does not show up in rendered html. This is where I informed myself. I also checked this unanswered "question". -
Folder picker on web application in Django Python
I want to integrate a folder picker on my web application such that when the user uploads a folder, I should be able to retrieve all the files inside it to perform some processing on it. To my knowledge, we CANNOT directly select the folder from web application HTML front end (unlike a file) via simply adding a button for upload (please correct me if I am mistaken here) Thus, I figured out a workaround by integrating JavaScript snippet to my HTML webpage. I am using Microsoft Visual Studio (VS code) to code this. This is what I have tried. I am providing all the required snippets that can be directly used to mimic this scenario: In "folder_processing.html" : <!doctype html> <html lang='en'> <head> <title>Scan Files</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <b> SELECT THE FOLDER FROM CHOOSER BELOW: </B> <br> <form id="scanForm" method="post"> {% csrf_token %} <input type="text" id="folderPathInput" name="folder_path" required readonly> <button type="button" id="selectFolderBtn">Select Folder</button> <button type="submit" name="folder_submit">Scan Folder</button> </form> <script> $(document).ready(function() { $('#selectFolderBtn').click(function() { // Open a file input dialog to select a file $('<input type="file" id="folderInput" style="display:none;">').change(function() { var folderPath = $(this).val(); if (folderPath) { // Set the selected folder path in the input field $('#folderPathInput').val(folderPath); } }).click(); …