Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset update migration
I'm trying to optimize a migration, it's taking too long, about 15 minutes every time you try to run it, because there is a lot of data on this table. It's an old database that have dates like this '14102019' (%d%m%Y) as String, and need to convert them to DateField. I created a DateField for both. Database is MySQL. dtobito and dtnasc are the old strings that need to be converted data_obito and data_nasc are the new DateFields What works (very slowly): def date_to_datefield(apps, schema_editor): Obitos = apps.get_model('core', 'Obitos') for obito in Obitos.objects.all(): if obito.dtnasc and obito.dtnasc != '': obito.data_nasc = datetime.strptime(obito.dtnasc, '%d%m%Y') if obito.dtobito and obito.dtobito != '': obito.data_obito = datetime.strptime(obito.dtobito, '%d%m%Y') obito.save() What doesn't work: Obitos.objects.update( data_nasc=datetime.strptime(F('dtnasc'), '%d%m%Y'), data_obito=datetime.strptime(F('dtobito'), '%d%m%Y') ) What could work, but I don't know how: Obitos.objects.raw(""" UPDATE obitos new, ( SELECT STR_TO_DATE(dtnasc, '%d%m%Y') AS dtnasc, STR_TO_DATE(dtobito, '%d%m%Y') AS dtobito, FROM obitos ) old SET new.data_nasc = old.dtnasc SET new.data_obtio = old.dtobito """) -
Django 2.2.4 unable to server my static files
In my application i was unable to server static files like images and js looks like everything is correct but still i am unable to figure out why it is not loading I have tried few options in stackoverflow none of them worked or me Settings.py STATICFILES_DIR = [ os.path.join(BASE_DIR, "static") ] STATIC_URL = '/static/' My project structure mydjangonginx |-mydjango_app | -urls.py | -views.py | -... |-mydjangonginx | -urls.py | -settings.py | -... |-static | -images | -login.jpg | -js | -my.js mydjango_app/urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('login', views.login, name='login'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) mydjangonginx/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('mydjango_app.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) login.html <html> {% load static %} login <script src="{% static 'js/my.js' %}"></script> <img src="{% static 'images/login.jpg' %}" /> </html> both the js and images are not loading can anyone help on this -
What did my pipenv disappear after python upgrade?
I had an existing project an everything was fine. As Heroku seemed to need a specific python runtime version for deployment, i upgraded python (windows 64) to 3.7.4 When running pipenv shell in my usual folder, i have this message : C:\Users\henry\Desktop\testldc>pipenv shell Creating a virtualenv for this project… Pipfile: C:\Users\henry\Desktop\testldc\Pipfile Using c:\users\henry\appdata\local\programs\python\python37\python.exe (3.7.4) to create virtualenv… [=== ] Creating virtual environment... but this message keeps running (up to 20 minutes)until it freezes ! I've tried to run pipenv shell on another previous project folder, and the problem is the same : installation i didn't ask for, and stuck during the installation. Thanks for your help ! I just wanted to run my usual virtual environment with a newer python version. -
How to query two models under a class view, get specific attributes associated with each models and compare one record against another
I have two models Job and Applicants, the Job model has an attribute years_of_experience and the Applicants model has an attribute applicant_experience. I want to get the applicants years of experience and compare it the required years of experience for each particular job, and return only those that meet the requirement under a view. models.py class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) years_of_experience = models.IntegerField(blank=True, null=True) class Applicants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) views.py class QualifiedApplicantPerJobView(ListView): model = Applicants template_name = 'qualified_applicants.html' context_object_name = 'applicants' paginate_by = 2 @method_decorator(login_required(login_url=reverse_lazy('login'))) def dispatch(self, request, *args, **kwargs): return super().dispatch(self.request, *args, **kwargs) def get_queryset(self): return Applicants.objects.filter(job_id=self.kwargs['job_id']).order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['job'] = Job.objects.get(id=self.kwargs['job_id']) return context applicants.html {% for applicant in applicants %} {% if applicant.experience >= job.years_of_experience %} <div class="col-lg-6"> <div class="box applicant"> <h4>{{ applicant.user.get_full_name }}</h4> <h4>{{ applicant.user.email }}</h4> </div> {% endif %} {% endfor %} I don't want to do it like this, I want to be able to do it in my views, get the number of qualified applicants(count) and return the qualified applicants. What is the best way to approach this. Thanks -
Not able to get the data selected form Django: ChoiceField
My application from an uploaded CSV file, reads header values and passes these headers into another class which extends Form. The goal is to get the selected value from the ChoiceField. The definition of selected is - current value displaying from the ChoiceField, should be considered selected. I am able to read the header values list. But when I am trying to print the selected choice field value expense_form.is_valid() returns False. My question is how could I get the selected data/value out from the ChoiceField. Python Version : 3.7.1, Django Version : 1.9.8 1.visualize_view.html {% extends 'base.html' %} {% block content %} {{ expense_form.as_p }} {% endblock %} 2.urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from uploads.core import views urlpatterns = [ url(r'^$', views.loginForm, name='loginForm'), url(r'^uploads/', views.simple_upload, name='simple_upload'), url(r'^admin/', admin.site.urls), url(r'^visualize_view/', views.visualize_view, name = 'visualize_view'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.AKASH_ROOT) 3.view.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage from uploads.core.models import Document from .forms import ExpenseForm def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() fs.save(myfile.name, myfile) return visualize_view(request, myfile) else: return render(request, 'core/simple_upload.html') def visualize_view(myfile): for row in … -
Can we define models.CASCADE only without using on_delete?
As I know is that when we defining foreign key in django we can set like on_delete=models.CASCADE. Recently I have seen code like content_type = models.ForeignKey(ContentType,models.CASCADE). My question is that does django allow to define models.CASCADE without using on_delete ? OR if we define like above does it work differently? content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) -
Generating JSON progress events from Django file upload
I'd like to display an upload status bar in my GUI when uploading a (large) file to my Django backend. My problem is that the 'onprogress' event appears only once when the upload is finished (both in the Django development server as well as in the Apache server (Windows). I suppose I have to code something that reports back a status message, but I seem to be unable to locate any hints at which point or how this could be implemented. Would be glad for any pointers where to start Currently I have this Javascript code: var data = new FormData(); data.append('localvideo',value) data.append('uploader',{% if request.user.id %}{{request.user.id}}{% else %}null{% endif %}) $.ajax({ type: "POST", contentType: false, processData: false, url: ajaxsnippetvideobaseurl, data: data, success: function (result) {ajaxfinished(); console.log(result); /*save(section,[result["id"]])*/}, error: function (result) {errorprofiles (result);}, xhrFields: { onprogress: function (e) { console.log(e)} } }); And this Django code: class VideoSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' class VideoSnippetViewSet(viewsets.ModelViewSet): queryset = VideoSnippet.objects.all().order_by('id') parser_classes = (MultiPartParser, FormParser) serializer_class =VideoSerializer -
DRF: Username still required after customizing Abstract User
I'm trying to write a REST API using Django and DRF. I'm trying to create a user model and use it in my application. But the problem is that it returns a 400 error status code which says: {"username":["This field is required."]} This is my code for models: import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings from django.dispatch import receiver from django.utils.encoding import python_2_unicode_compatible from django.db.models.signals import post_save from rest_framework.authtoken.models import Token from api.fileupload.models import File @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) address = models.CharField('Address', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) The Serializer: class CreateUserSerializer(serializers.ModelSerializer): username = None def create(self, validated_data): validated_data['username'] = uuid.uuid4() user = User.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.phone_no = validated_data.get('phone_no', instance.phone_no) instance.email = validated_data.get('email', instance.email) instance.save() return instance class Meta: unique_together = ('email',) model = User fields = … -
Docker: execute django migration into a db container from inside of the web container
I run a CI pipeline in gitlab. The stage executes several steps: First I start db container: docker run --name db -p 5432:5432 \ -e DJANGO_SETTINGS_MODULE=<myapp>.settings.postgres -d postgres:9.6 Then I check if it worked: docker inspect db true Note that I specify a non-default settings file (which contains my db credentials) Now I build web container with Django 2.2 inside and feed it the DB credentials of the postgres container : docker build --pull -t test_image . --build-arg DB_NAME=<mydbname> --build-arg DB_HOST=db --build-arg DB_USER=<mydbuser>--build-arg DB_PASS=<mydbpassword> That runs Dockerfile sequence of may steps and at some point arives to DB migration: RUN python manage.py migrate --settings .settings.postgres That invariably chokes with this error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (127.0.0.1) and accepting TCP/IP connections on port 5432? Which means to me that the name I gave to the postgres container ("db") does not mean anything inside this (web) container. I checked the db redentials variables before "migrate" step (just printed with echo) - they all made it ok. How do I correctly run "python manage.py migrate " from inside of the build (Dockerfile) of web container AGAINST THE DB IN THE DB CONTAINER … -
Gunicorn no wsgi module
I'm following this tutorial this time: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 But I think it misses out a step, as I am unable to test the dev server is running using manage.py runserver 0.0.0.0:8000, but I never have before, so no biggie there, but I am unable to get gunicorn working as there is no wsgi.py module in my project. I assumed that this gets created by gunicorn itself. What do I have to do to get that working properly please? -
change account authenticate method from username to email
I want to change login method from username to email. urls.py from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token urlpatterns = [ url(r'^login/$', obtain_jwt_token), url(r'^tokenRefresh/', refresh_jwt_token) ] setting.py ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False I have used above solution but not working for me. can you please help!! -
replace spaces with % in django or python app
im having a hard time fixing this one. i have a search function that will look for campaign name or campaign launcher name. for example if a user look for all campaigns launched by john doe. i want to enclose all spaces with '%' (%john%doe%) expected. campaigns = Campaign.objects.filter(title(re.sub('/\s/g ', '%', search)) | launcher(re.sub('/\s/g ', '%', search))) i also tried campaigns = Campaign.objects.filter(title(re.sub(' ', '%', search)) | launcher(re.sub(' ', '%', search))) but my code is not doing the right thing. im getting `camp`.`name` LIKE '%john doe%' OR `user`.`name` LIKE '%john doe%' and if i did the search.replace(" ", "%") im getting `camp`.`name` LIKE '%john\\%doe%' OR `user`.`name` LIKE '%john\\%doe%' any help will be much appreciated. -
Django: QuerySet with group of same entries
My goal is to show for a specific survey the Top 10 "Entities" per question ordered from high to low by salience. A survey has several questions. And each question has several answers. Each answer can have several entities (sometimes the same name (CharField), sometimes different names). I thought the following final result makes sense: [ 5: # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 4, # E.g. answer__pk = 1, answer__pk = 1, answer__pk = 2, answer__pk = 3. Leonardo Di Caprio was mentioned twice in answer_pk 1 and therefore has entries. 'salience': 3.434 # Sum of all 4 entities }, { 'name': 'titanic', 'count': 5, 'salience': 1.12 }, { 'name': 'music', 'count': 3, 'salience': 1.12 } ], 3: # question.pk [ { 'name': 'Leonardo Di Caprio', 'count': 5, 'salience': 1.5 }, { 'name': 'titanic', 'count': 4, 'salience': 1.12 }, { 'name': 'music', 'count': 2, 'salience': 1.12 } ], ] Now I am struggling to write the right QuerySet for my desired outcome. Anyone here who can help me with it? I came to the point that I probably have to use .values() and .annotate(). But my results are quite far away from what my goal ist. Here … -
how to write views for models and display in templates
I am new Django. created models and i want to display those models in html.please help me in writing views and templates this is the models class Author(models.Model): author_name=models.CharField(max_length=300) def __str__(self): return self.author_name class Events(models.Model): event_author=models.ManyToManyField(Author) event_title=models.CharField(max_length=300) event_title_image = models.ImageField(upload_to='images/', blank=True, null=False) event_description=models.TextField(blank = True) event_image_description = models.ImageField(upload_to='images/', blank=True, null=True) event_release_date = models.DateField(null="false") def __str__(self): return self.event_title def publish(self): self.event_release_date = timezone.now() self.save() this is are the URLS def Event(request): return render(request, 'polls/events.html', {}) please help me out from this and how to write views from models -
Django: Module not Found on Azure App Service - Azure DevOps CD
I am looking to set up a simple Django application on Azure App Service (Linux OS) by running an Azure Devops Build and Release pipeline. The application builds and creates a release without a problem. However when the application has been released it runs into runtime errors. 2019-10-15T09:48:16.161816610Z ModuleNotFoundError: No module named 'django' I run pip3 install -r requirements.txt as part of the bash post deployment script, and requirements.txt contains Django but it claims the requirement is already satisfied. Or if I bash into the App Service and run the same command it get the same message with the requirements already being satisfied. Therefore my question is, why am I receiving a ModuleNotFoundError? -
get data first table from middle table
I want to display a series of books as a subset of a book model class Book(models.Model): rate_book = models.ManyToManyField("Book", blank=True) view book_rete = Book.rate_book.through.objects.filter( from_book_id=book_id).select_related() I need books details of books to show how I have to join between tow tabel -
Django-allauth URL Returns callback error for github despite correct url
I am trying to implement all-auth using Github in my django project. I have set the callback url as per this tutorial. So far, even if the login page for github shows up, it doesn't call back properly and I get this error in the url http://127.0.0.1:8000/accounts/github/login/callback/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23redirect-uri-mismatch&state=exDbVJKNYzUI This is the github repo of the project. http://127.0.0.1:8000/accounts/github/login/callback/ is my authorization callback url set as per the tutorial. Any insight to why the callback url is not working is welcome. Thanks. -
Problem with queries ith Q object ('works' but not all the time)
I use Q object in a search input area I have many field to test in the search area so I use OR (|) in my query Sometime it works, sometimes not I mean, I test search on a field -> it work I had new field in the query and it does'nt work anymore... I check my code go back and test again but i do not understand what is wrong @login_required def liste_participantes(request): """ A view to list participants. """ liste_existe = True if request.POST: ide = request.POST.get('ide', False) try: # Participante.objects.get(pat_ide_prn_cse=ide) Participante.objects.get( Q(pat_ide_prn_cse=ide) | Q(pat_nom=ide) | Q(pat_pre=ide) | Q(pat_pti_nom_001=ide) | Q(pat_pti_nom_002=ide) | Q(pat_nai_dat=ide) ) except: liste_existe = False else: # participantes = Participante.objects.filter(pat_ide_prn_cse=ide) participantes = Participante.objects.filter( Q(pat_ide_prn_cse=ide) | Q(pat_nom=ide) | Q(pat_pre=ide) | Q(pat_pti_nom_001=ide) | Q(pat_pti_nom_002=ide) | Q(pat_nai_dat=ide) ) else: participantes = Participante.objects.all() return render(request, 'participante/liste_participantes.html', locals()) none of the fields works but if I suppress the last field (Q(pat_nai_dat=ide) and run again all fields works !!! -
Use date range in query filter
I have an HTML form which returns me two dates in a format like this: 2019-10-15. When I checked the type() of the date return it came out to be "str" how can I use this string in my Django query? Code: start = request.POST['from'] end = request.POST['to'] foo = bar.objects.filter(dispatch_date = ??) -
add url for category with django 2
I'm working on my blog page basically the blog has category for split the same posts, for this I made a class for category and made a relationship between the category and my post class like this : class Category(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Post(models.Model): image = models.ImageField(upload_to='Posts_image') title = models.CharField(max_length=256) configure_slug = models.CharField(max_length=512) slug = models.SlugField(max_length=512,null=True,blank=True) content = HTMLField('Content') date = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField(Category) tags = TaggableManager() publish = models.BooleanField(default=False) def __str__(self): return self.title after this I made some code for create a slug for the title of category because I want link the posts that has same title but I can't found a solution I want you help me for this problem and learn or help me what can i do for create a slug or Link the same posts together This is my views.py def category_count(): queryset = Post.objects.values('categories__name')/. annotate(Count('categories__name')) return queryset def blog(request, tag_slug=None): category = category_count() post = Post.objects.filter(publish=True) tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) post = post.filter(tags__in=[tag]) paginator = Paginator(post, 2) page = request.GET.get('page') try : posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts':posts, 'page':page, 'tag': tag, … -
django Serializer object has no attribute
I don't have much experience in python but got task to write server in django which will handle api requestes I sent from front part, the thing is that eventho GET works well, POST still throw some errors. If I add new Logo via admin panel, it works, when I try to do so via postman it throw this error: Traceback (most recent call last): File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/user/.local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) AttributeError: 'LogoSerializer' object has no attribute 'name' my code: class LogoViewSet(viewsets.ViewSet): def list(self, request): queryset = Logo.objects.all() serializer_class = LogoSerializer(queryset, many=True) return Response(serializer_class.data) def create(self, request): serializer_class = LogoSerializer(data=request.data) bg = Logo( name=serializer_class.name, thumb=serializer_class.thumb, thumbL=serializer_class.thumbL, dataL=serializer_class.dataL, ) bg.save() return Response(bg) and Serializer: class LogoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Logo fields = … -
Heroku not correctly installing tulipy from requirements.txt
When deploying my django app on Heroku, I have a ModuleNotFoundError happening when it tries to install tulipy package from requirements with pip. It says No module named 'numpy' when importing numpy but it is the first package on the requirements.txt list so it should be installed first. The app is deploying fine without tulipy package. I tried calling another requirements file with -r ./requirements-prior.txt containing only numpy but it doesn't work. How can I force Heroku to install numpy before tulipy? Full error message Thanks -
Combination of foreigh keys and pre-defined values as choices for Django model field
A ForeignKey field (let's call it tc) in one of models (let's call it Venue) stores reference to terms and conditions model (let's call it TC) where different versions of document are stored. This way every Venue can select one of versions of tc that suits their needs. class Venue(models.Model): tc = models.ForeignKey( 'my_app.TC', on_delete=models.CASCADE, help_text=_('Version of tc used by this venue') ) Records in TC table are added frequently so if given Venue wants to use latest version of document someone needs to manually update it via django admin. This is a poorly though solution because there are dozens of Venue records in database and they all have different approaches to tc usage: some of venues want tc to be updated automatically to latest version some want/need to bump up their tc version manually some venues do not use tc at all The goal that needs to be achieved is having 2 default options for each Venue: 1. ---- (blank: venue does not use any `tc`) 2. Latest (venue automatically uses latest version of `tc` available` And unspecified number of available tc options (for example foreign keys to TC model) 1. v1.0.0 2. v2.1.0 3. ... So list of … -
How to redirect users after password change django 2?
I have a password change view in my project. Instead of the default django password_change_done/done/ I want users to be redirected to my custom page eg homepage. For login we need to edit the settings and add LOGIN_REDIRECT_URL. Is there anything like PASSWORD_CHANGE_REDIRECT_URL that we can specify in our settings.py file. This is my URL patterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name="logout"), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name="password_reset"), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name="password_reset_done"), path('password_reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name="password_reset_confirm"), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name="password_reset_complete"), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='users/change_password.html'), name="password_change"), path('password_change_done/done/', auth_views.PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name="password_change_done"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I want the users to be redirected to custom view and not the default one. Any help would be highly appreciated. -
I want to add dependent dropdown in django, how to achieve it
I want to create multiple dependent dropdowns in Django. eg. list1 = ['home','school','hospital'], home = ['mixer','grinder','cooker'] #sublist of 'home' element of list1 and so on.. so if user selects the 'home' option my next dropdown which is item list of the selected option should show all related items to 'home' without refreshing the page. how can I achieve this in Django?