Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sub-subcategory for subcategory
How to add sub-subcategory for subcategory? For Category subcategory is added. For subcategory sub-subcategory is not added. Tried to render subid in a separate model, error DocPage has no attribute subid Model class DocPage(models.Model): title = models.CharField(max_length=300, default='', unique = True) parentid = models.ForeignKey('self',related_name='subcategories',blank=True,null=True) subid = models.ForeignKey('self', related_name='childsubcategories', blank=True, null=True) class ChildSubcategorySerializer(serializers.ModelSerializer): class Meta: model = DocPage fields = ('title', 'file', 'subid',) Serializers class SubcategorySerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() childsubcategories = ChildSubcategorySerializer(many=True, read_only=True) class Meta: model = DocPage fields = ('id', 'title', 'file', 'subid', 'childsubcategories',) class DocSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() subcategories = SubcategorySerializer(many=True, read_only=True) class Meta: model = DocPage fields = ('id', 'title', 'file', 'project', 'parentid', 'subcategories',) -
Replace foreign key dropdown with textbox with add/edit icon - Django
Related to foreign key fields in the Django Admin, the default display element is a drop down list box containing all of the foreign key items from the related model. I my app it will contain thousands of items and I am looking to change the admin interface and have it use a text box instead of the populated drop down. Looking for textbox with add/edit icon next to it, so that we dont get populated values, we just directly add or edit. Is there any way around to achieve it. -
Django: DoesNotExist: SocialApp matching query does not exist
I'm trying to activate social logins in my Django web application, which comes from open source software in this GitHub repository (so I didn't write it); and am running into this well-known issue: DoesNotExist: SocialApp matching query does not exist. The base settings file is located here. I do not modify that file at all. Instead, I import (inherit) it at the top of my deploy.py settings file, and make overrides and customization there. Specifically related to this issue, here are the relevant overrides and additions that I made in deploy.py to enable Google and Twitter social authentication, both of which result in the same error: INSTALLED_APPS.remove('allauth.socialaccount.providers.persona') # Remove INSTALLED_APPS.append('allauth.socialaccount.providers.google') # Add INSTALLED_APPS.append('allauth.socialaccount.providers.twitter') # Add _GOOGLE = { 'SCOPE': ['email', 'https://www.googleapis.com/auth/userinfo.profile'], 'AUTH_PARAMS': {'access_type': 'online'}, 'PROVIDER_KEY': get_env("GOOGLE_PROVIDER_KEY"), # Stored in secrets.env 'PROVIDER_SECRET_KEY': get_env("GOOGLE_PROVIDER_SECRET_KEY"), # Stored in secrets.env } SOCIALACCOUNT_PROVIDERS['google'] = _GOOGLE # This isn't enabled in biostar.settings.base _TWITTER = { 'SCOPE': ['email'], 'AUTH_PARAMS': {'access_type': 'online'}, 'PROVIDER_KEY': get_env("TWITTER_PROVIDER_KEY"), # Stored in secrets.env 'PROVIDER_SECRET_KEY': get_env("TWITTER_PROVIDER_SECRET_KEY"), # Stored in secrets.env } SOCIALACCOUNT_PROVIDERS['twitter'] = _TWITTER I show two provider examples here -- Twitter and Google -- to show the pattern of what I am doing, and to show that the issue isn't provider-specific; though let's … -
Django: Form validation strange behaviour
I want to do file validation(size,type) on a field on inlineformset. class ProductDocumentModelForm(ModelForm): class Meta: model = ProductDocument fields = ['document'] def clean_document(self): file = self.cleaned_data['document'] validate_file(file, 'document') Because I want to use the same validation in multiple application I created a separate function. def validate_file(file, for_model, max_size=5000): if for_model == 'document': max_size = FILE_MAX_DOC_SIZE if file.size > max_size: raise ValidationError('Please keep file size under {}. Current file size is {}' .format(filesizeformat(FILE_MAX_DOC_SIZE), filesizeformat(file.size))) The file size validation works as intended but introduce a strange behavior. If this validation is in place and is passed the "This field cannot be blank." default validation is triggered even if the fields are not empty. Without the file size validation in place there are no issue even if the fields are empty. I don't understand what is the cause. -
Gdal-Raster installing for windows
I have problem with Gdal-Raster. Soon i joined to the new project and cloned it from git. So i have installed all requirments txt and at last i have error that i can not understand and fix. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' I can not understand what is GdalRaster and how install this? If somebody can help me please reply. Thanks in advance for the answer. -
Value Error:Cannot assign queryset to attribute it must be instance
I have models.py class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc=models.CharField(max_length=5,choices=LOCATION) manager_id=models.ForeignKey('self',null=True,blank=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P') ltype=models.CharField(max_length=2,choices=LEAVE_TYPE) message=models.CharField(max_length=500,blank=True) class notify(models.Model): sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') date_time=models.DateTimeField() I have views.py def accept(request): approved_emp_id=leave.objects.filter(id=accept_id); approving_emp_id=leave.objects.filter(employee__emp_id=request.user.username); accept_notify=notify(sender_id=approving_emp_id, receiver_id=approved_emp_id,date_time=datetime.datetime.now(),viewed='N'); accept_notify.save() When I want to save values to database I am getting error as ValueError: Cannot assign "<QuerySet [<leave: 121-geeta-2017-10-04-2017-10-06-C-V-2017-09-27 07:48:36.288873+00:00>]>": "notify.sender_id" must be a "leave" instance. Where am I going wrong approving_emp_id and approved_emp_id are both leave instance only. -
Using drf-nested-routers with nested HyperlinkedIdentityFields
I am trying to generate nested HATEOAS links in a serializer using the drf-nested-routes package. My current setup would be as follows: /resource_a/<pk> /resource_a/<pk>/resource_b/<pk> /resource_a/<pk>/resource_b/<pk> /resource_a/<pk>/resource_b/<pk>/resource_c I am unable to create a HyperlinkedIdentityField that points to the last route. According to the documentation, one can create hyperlinked fields like this: nameservers = HyperlinkedIdentityField( view_name='domain-nameservers-list', lookup_url_kwarg='domain_pk') Or nameservers = NestedHyperlinkedRelatedField( many=True, read_only=True, # Or add a queryset view_name='domain-nameservers-detail' parent_lookup_url_kwargs={'domain_pk': 'domain__pk'} ) But these approaches fail when trying to reach a resource that is 2 layers deep in the URL hierarchy. The first method is not compatible, as it does not allow to add a second lookup_url_kwarg, and as for the second one, it throws an exception (ImproperlyConfigured) when configuring with the (in my opinion) proper attributes (resource_a__pk, resource_b__pk). Is this at all possible with this package? Otherwise I will resort to a simpler solution using a SerializerMethodField: resource_c = serializers.SerializerMethodField() def get_resource_c(self, obj): url = reverse('resource_b-resource_c-list', kwargs=dict(resource_a_pk=obj.resource_a.pk, resource_b_pk=obj.pk)) return self.context['request'].build_absolute_uri(url) Thanks in advance! -
how to create dynamic Row/Col table in reactjs
i am trying to render a table using react, there are three entities, Criteria(Row), Rating(Col), and explanation (at their intersection). Row/col can be added i am able to render criteria, rating and explanation, but i want to add a /Popover button if the explanation does not exist. For ex use case R1 R2 R3 R+ C1 E1 E2 C2 E3 C+ At all the empty places i want to add a popover to add Explanation. I am using reactjs, graphql, ant-d, Following is the code for looping return ( <div> { <FlexRow> {" "} <FlexCol key={"rating.id"} span={24 / (ratings.length + 2)}> <CriteriaRatingBox> <CriteriaRatingTitle>{"index"}</CriteriaRatingTitle> </CriteriaRatingBox> {ratings.map((rating, i) => ( <CriteriaRatingBox> <CriteriaRatingTitle>{rating.title}</CriteriaRatingTitle> </CriteriaRatingBox> ))} <CriteriaRatingBox> <Popover content={ <RubricRatingsForm requirementId={this.props.requirementContextId} handleMcAddRubricRating={ this.props.handleMcAddRubricRating } /> } > <CriteriaRatingTitle>{"+Add Rating"}</CriteriaRatingTitle> </Popover> </CriteriaRatingBox> </FlexCol> </FlexRow> } {criteria.map((criteria, i) => ( <FlexRow> <FlexCol key={criteria.id}> <CriteriaBox>{criteria.description}</CriteriaBox> </FlexCol> {ratings.map((rating, i) => ( <div> <FlexCol key={rating.id} span={24 / ratings.length + 1}> <CriteriaRatingBox> {criteria.explanations.map((explanation, i) => ( <Popover content={ <EditRubricExplanationForm handleEditRubricExplanation={ this.props .handleMcRequirementEditRubricExplanation } rubricExplanation={explanation.description} rubricExplanationId={explanation.id} toggleEditRubricExplanationOpen={ this.toggleEditRubricExplanationOpen } /> } > <CriteriaExplanation> {explanation.rating.id === rating.id && explanation.criteria.id === criteria.id && ( <RichTextEditor rawData={explanation.description} /> )} </CriteriaExplanation> </Popover> ))} </CriteriaRatingBox> </FlexCol> </div> ))} </FlexRow> ))} <FlexRow> <FlexCol> <Popover content={ <RubricCriteriaForm requirementId={this.props.requirementContextId} … -
Is it possible to change the 'migrations' folder's location outside of the Django project?
what i'm trying to do is to change the default path for migrations for a specific application in a django project to put it outside the project itself but keeping it transparent, keeping use of makemigrations and migrate. Is it possible? if yes, how? -
Selecting a git workflow for my situation
I'm new to git. I've read the well-written intro book. But gee, it's still not a trivial topic. I've been bumbling around, experiencing various problems. I realized it might be because I'm unaware of workflow, and specifically, "what are the best practices for doing what I'm trying to do?" I started out developing a django project on my win7 with Pycharm. Great way to get the initial 95% written. But then I need to deploy it to my production machine at PythonAnywhere. So I created a private Github repository, pushed my win7 codebase to github. Then in pythonAnywhere, I cloned the github repository. For now, no others work on this project. It will not be released to the public. Now that the server is running on PythonAnywhere, I still need to tweak settings, which is best done on the PythonAnywhere codebase side. But there are other improvements (new pages, or views) that I'd rather do inside Pycharm IDE on my win7 than in vim on python anywhere. So I've been kind of clumsily pushing and fetching these changes. It's been kind of ham-handed, and I've managed to lose some minor changes through ignorance. So I'm wondering if anyone can point … -
Celery periodic tasks once in 2 weeks
I am having trouble setting a periodic task with Celery to run once in 2 weeks on Sunday nights. Does anyone have any idea how to configure that with day_of_month day_of_week options? -
not able to find the variables sqlite for django project
I am creating demo django project in PyCharm. So I keep closing and re-opening the PyCharm. But I have noticed that once I reopen my django project in PyCharm, and go to sqlite command prompt through python manage.py shell, and look for the previously created models, I get below error >>> b.id Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'b' is not defined but when I execute the command Album.objects.all() I do get the details of previously created models >>> Album.objects.all() <QuerySet [<Album: yaad: Sonu Nigam>, <Album: : >, <Album: : Back Street Boys>, <Album: InComplete: Back Street Boys>, <Album: In The End: Linkin Park>]> Is this a kind of any defect, or it's just me who get to see such situation, or am I missing something? Python 3.6 django 1.11 pycharm 2017.2.3 -
Error in migrate after adding DateField in Django Model
This is my Django model, in which I want to add another field, in addition to pre-existent fields class Offerta(models.Model): #old pre-existent fields ... #the field I want to add date_rifiuto = models.DateField(null=True, blank=True) When I run 'makemigrations myapp' there are no problems, but when I run the 'migrate' command, console shows some errors: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: myapp_offerta.data_rifiuto The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/pycharm-2017.2.3/helpers/pycharm/django_manage.py", line 43, in <module> run_module(manage_file, None, '__main__', True) File "/usr/lib/python3.5/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib/python3.5/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/santoryu/richiestaTesi/manage.py", line 22, in <module> execute_from_command_line(sys.argv) I think the main problem is here: sqlite3.IntegrityError: NOT NULL constraint failed: myapp_offerta.data_rifiuto But I have explicitly say null=True -
django window popup with table details
I want to create a button in the template that if i press View i want a popup to show up and in that popup i want to display my Table from models.py. Basically i want that popup to have all the columns names and the all the date of that tabled display. with pagination if its possible. This is part of my seaerch_table.html <script> $("#mytable").dialog({autoOpen: false}); $("#opener").click(function () { $("#mytable").dialog("open"); }); </script> <table class="table table-bordered sortable table-hover" id="mytable"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Url</th> <th>View All Info</th> </tr> </thead> <tbody> {% for lists in details %} <tr> <td>{{ lists.id }}</td> <td>{{ lists.title }}</td> <td><a href="{{ lists.url }}" target="_blank">{{ lists.url }}</a></td> <td> <button id="opener">View</button> </td> </tr> {% endfor %} </tbody> </table> It only shows in the template only 3 fields...and i want to add 2 more field when i do the popup which will include the Createdat and Descriptions field. I don't want to do nothing special on that popup...just display the entire table from mysql (which include the column createdat and description) Can someone please help me ? Thank you -
How to avoid Django unit tests to cause MySQL aborted connection when running in parallel?
I'm trying to run Django tests in parallel by using: python manage.py test --keepdb --parallel But if a test fails, it caused an aborted SQL connection. In MySQL I can see it: SHOW GLOBAL STATUS LIKE 'Aborted_connects'; -- aborted_connects : 1 And because of that, I keep seeing this error in other tests: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 102") What can I do to avoid this situation? This is an sample traceback of other tests failing: Using existing test database for alias 'default'... Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py", line 157, in <module> utility.execute() File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py", line 132, in execute PycharmTestCommand().run_from_argv(self.argv) File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py", line 97, in handle failures = TestRunner(test_labels, **options) File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_runner.py", line 256, in run_tests extra_tests=extra_tests, **options) File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/test/runner.py", line 532, in run_tests old_config = self.setup_databases() File "/Users/dio/code/athena/common/runner.py", line 12, in setup_databases result = super(CITestSuiteRunner, self).setup_databases() File "/Users/dio/.virtualenvs/athena/lib/python2.7/site-packages/django/test/runner.py", line 482, in setup_databases … -
AmoCrm - django convert QueryDict to json
I try to deal django with amocrm webhook. I'm getting in post QueryDict, but I want to have json. How can I get it? I dont know why the key is so full: 'contacts[note][0][note][attachement]' {'contacts[note][0][note][attachement]': ["''"], 'contacts[note][0][note][timestamp_x]': ["'2017-09-29 00:02:28'"], 'contacts[note][0][note][text]': ["'e'"], 'contacts[note][0][note][group_id]': ['0'], 'contacts[note][0][note][element_id]': ['9194307'], 'contacts[note][0][note][modified_by]': ['1760296'], 'contacts[note][0][note][account_id]': ['16500283'], 'account[subdomain]': ['xxxxxx'], 'contacts[note][0][note][main_user_id]': ['xxxxx'], 'contacts[note][0][type]': ['contact'], 'contacts[note][0][note][created_by]': ['xxxxx'], 'contacts[note][0][note][date_create]': ["'2017-09-29 00:02:29'"], 'contacts[note][0][note][element_type]': ['1'], 'contacts[note][0][note][note_type]': ['4']} -
How much time Django take to make a connection with PostgreSQL when both are on the same machine?
For my application, it is taking 14ms to make a connection between Django and PostgreSQL,my system is 40 core cpu and 16 GB ram, can we reduce this time? Thank you -
login doesn't work returh error (1)
hi why login doesn't work my views.py def login(request): if request.method == 'POST': password = request.POST['password'] username = request.POST['username'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login_auth(request, user) return redirect('account') else: context = {'message_error':'3'} return render(request, 'account/login.html',context) else: context = {'message_error': '2'} return render(request, 'account/login.html', context) else: context = {'message_error': '1'} return render(request, 'account/login.html', context) my login.html.tag form <form method="post" action="{% url 'blog:account' %}" > my urls.py url(r'^account/login/$', views.login, name='login'), in terminal whene submit detils [29/Sep/2017 08:20:46] "POST /account/ HTTP/1.1" 302 0 [29/Sep/2017 08:20:46] "GET /account/login/ HTTP/1.1" 200 5158 just return (1) How can I solve this? thanks -
Django restarts when file changes not belong to Django
The problem was the Django is restarting when i change the settings.py but that settings.py is not belongs to django project. Here is the folder structure. - project - django-conf - settings.py - urls.py - ... - apps - apps1 - ... - scrapy-setting - settings.py <------- file to be updated When i update the scrapy-setting/settings.py the django will reload. I dont know why. In my django config, there is no relation between that folder. -
Save multiple objects with a unique attribute using Django formset
TL;DR: How do you save/validate multiple objects with a unique attribute using a formset? Let's say I have a Machine which has multiple Settings (see models below). These settings should have a unique ordering within the machine. This can be accomplished by defining a unique_together attribute in the Meta class of the Setting model: unique_together = (('order', 'machine'), ) However, I'm using an inline formset to update all the Settings of a Machine. Assume I have the following info in my formset: Setting 1: machine=1; order=1 Setting 2: machine=1; order=2 If I were to switch the order on the two Settings: Setting 1: machine=1; order=2 Setting 2: machine=1; order=1 and save the form using the following piece of code: self.object = machine_form.save() settings = setting_formset.save(commit=False) for setting in settings: setting.machine = self.object setting.save() Then I get a Unique Constraint Error since I'm trying to save Setting 1 with order=2, but Setting 2 still has that order. I can't seem to find a clean solution for this problem. I would like to keep the unique_together constraint to ensure the correctness of my data. I know how to solve this in the frontend using Javascript, but I want a check in my … -
Django-admin forgot password
login.html {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} urls.py from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views app_name = 'Web' urlpatterns = [ url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), ] as you can see pasword_reset_url included but i'm not able to see this href in my login page how can i configure ? -
hvad translation error __str__ returns NoneType
I am trying to localize some of my models and adopted hvad. It works fine but not when in related models. I have the following two models: class Family(TranslatableModel): sciencename=models.CharField(max_length=50,verbose_name='Scientific Name',blank=True,null=True) translations=TranslatedFields( name=models.CharField(max_length=50, unique=True), note=models.TextField(null=True,blank=True) ) def __str__(self): return self.safe_translation_getter('name',) And child: class Child(TranslatableModel): sciencename=models.CharField(max_length=50,verbose_name='Scientific Name',blank=True,null=True) family=models.ForeignKey(Family,related_name="child_family") translations=TranslatedFields( name=models.CharField(max_length=50) ) def __str__(self): return 'Dude'#' , '.join([self.family.name,self.safe_translation_getter('name',)]) class Meta: #ordering=('family','name',) unique_together=(('name','language_code')) Now I want to access this from the admin page and have this in admin.py, which generates TypeError. Without languages, it was listing families so I can chose one when adding a child: class cHILDAdmin(TranslatableAdmin): # ... other admin stuff def get_fieldsets(self, request, obj=None): return ( (_('Common fields'), { 'fields': ('sciencename','family' ), }), (_('Translations'), { 'fields': ('name',), }), ) change_form_template = 'change_form.html' list_display = ('__str__','family','sciencename', ) def apply_select_related(self, qs): return qs.prefetch_related('family') def get_family(self, obj): return obj.family def get_name(self,obj): return obj.name get_name.short_description = _('Name') -
How does django rqworker notify the browser that job has been done?
I have to create a major feature of my system. Here are the spec Software Versions: python3.6.2 Django1.11 Requirements: 1. Upload an Excel file with the correct format. Correct sheetname, columns all are set. 2. Dispatch the data processing to child-process. 3. Notify whether the error occur or not and summarize the error all at once to the user. 4. If the error occur. Rollback all the transactions. Planning: 1. Upload File and validate sheetname, and column is not difficult. I had done this before 2. Dispatch with rqworker is very easy 3. Hard part is here 4. Deal with Rollback by using decorator @transaction.atomic Question: 1. How can I let child-process notify the browser that the assigned job has been done? -
Django i18n_patterns with non-standard language codes
I am trying to use django's i18n_patterns in my root URL config to do automatic switching of the page language based on the URL. From looking at the related LocaleMiddleware code code, it does indeed look like hitting the server with a language prefix in the URL it switches the language. The issue I am facing though is that the translations we have in our system all have a country specific code, i.e. en-us instead of en or fr-be instead of fr. For the URLs themselves however we require the short form to be used. Our current solution is to run our custom locale middleware, mapping the current short form language code to the long form language code for activating the translations. I would like to know however if there would be another way around this, such that we could use this standard django implementation. -
I wanna send type1 of select tag
I wanna send type1 of select tag to test.html. I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} <select name="type1" id=type6> {% for value1 in preprocessed1 %} <option value="{{forloop.counter1}}">{{ value1 }}</option> {% endfor %} </select> </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var key; var value; $('select[name="main"] option:selected').each(function(index, option) { key = $(option).text(); }); $('select[name="type"] option:selected').each(function(index, option) { value = $(option).text(); }); $('select[name="type1"] option:selected').each(function(index, option) { value1 = $(option).text(); console.log(value1); }); document.querySelector("input[type=submit]").onclick = e => { const test = window.open(`test_view?${key}=${value}`, "_blank"); } }); $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== …