Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is a good way of allowing a user to add text filters to a stream without heavily impacting speed?
I have a service where I get a large amount of text data flowing in, in real time. The idea is that users are notified of certain portions of data when it passes through two filters - a positive match and negative match (do not notify). The stack is: Django - sqlite Redis RabbitMQ (Celery) Currently, I have filters hardcoded, however I wish to allow users to add their own filters. My concern is that by storing filters in a db, making requests to the db for every piece of data flowing through will impact heavily on the speed which users receive notifications (being as fast as possible is imperative). -
error after get request googleoauth2
Getting an error after getting the authentication from Google Oauth2. please help Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/login/?next=/complete/ Using the URLconf defined in edgrab.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='home'] ^login/(?P<backend>[^/]+)/$ [name='begin'] ^complete/(?P<backend>[^/]+)/$ [name='complete'] ^disconnect/(?P<backend>[^/]+)/$ [name='disconnect'] ^disconnect/(?P<backend>[^/]+)/(?P<association_id>\d+)/$ [name='disconnect_individual'] ^login/$ [name='login'] ^logout/$ [name='logout'] ^password_change/$ [name='password_change'] ^password_change/done/$ [name='password_change_done'] ^password_reset/$ [name='password_reset'] ^password_reset/done/$ [name='password_reset_done'] ^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm'] ^reset/done/$ [name='password_reset_complete'] ^career_tracker/ The current path, accounts/login/, didn't match any of these. -
why would I need a web framework for my website
I have looked up this question many times and got some answers but they don't seem needed or it looks like PHP can do it any way I would love to learn ruby on rail but I don't know what it is used for in a real website and don't know what its practicalities are and should I use rails or Django thanks for taking time to read this question and answering it if you do btw I am quite new to backend development so please correct me if this makes no sense -
Django test login module can't be verified?
I want test login redirect, but I use client post username and password, Login-authenticate failed, I adjusted for a long time. I don't know why! view: def index(request, **kwargs): username = kwargs.get('username', 'anyone') return render(request, "index.html", {'username': username}) def login(request): """user sign in""" if request.method == "GET": form = LoginForm() return render(request, "login.html", {'uf': form}) else: form = LoginForm(request.POST) if form.is_valid(): username = request.POST.get("username") password = request.POST.get("password") user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) request.session['uid'] = user.id return render(request, 'index.html', {'username': username}) else: return render(request, 'login.html', {'form': form, 'password_is_wrong': True, 'error': 'Pls, Resubmit'}) else: return render(request, 'login.html', {'form': form}) test: def test_login_right(self, username='admin', password='zg123456'): """ POST right username or password """ setup_test_environment() client = Client(enforce_csrf_checks=False) url = '/login/' response = self.client.post(url, data={'username': username, 'password': password}, secure=True, follow=True) status_code = response.status_code self.assertNotIn(str(status_code)[0], ['4', '5']) self.assertIn('Welcome', response.content.decode('utf8')) I find do test, auth.authenticate return None, but I use brower authenticate return not None, I don't know why, a protection mechanism? I must use client.login func ? -
Django admin with many to many choices
I have the following models.py and admin.py files. The intention is to allow for selection of multiple categories for a given product if necessary. models.py class Product(models.Model): organization = models.ForeignKey(Organization) name = models.CharField(max_length=50) brief = models.CharField(max_length=100) descrip = models.TextField(max_length=1300) categories = models.ManyToManyField('Product_Category') class Product_Category(models.Model): cats = {"AUT":"Automation", "PWA":"Personal Wealth Advisory", "BCH":"Blockchain", "LOS":"Loan Origination", "FX":"Foreign Exchange"} choices = tuple((human, c) for human, c in cats.items()) name = models.CharField(max_length=32, choices=choices) admin.py from .models import Product, Product_Feature, Organization, Product_Category class PFeatureInLine(admin.StackedInline): model = Product_Feature extra = 1 class ProductForm(forms.ModelForm): logo_file = forms.ImageField() def save(self, commit=True): logo_file = self.cleaned_data.get("logo_file", None) self.instance.logo = b64encode(logo_file.read()).decode("utf-8") return forms.BaseModelForm.save(self, commit=commit) class Meta(): exclude = ["logo"] model = Product class ProductAdmin(admin.ModelAdmin): form = ProductForm inlines = [PFeatureInLine,] admin.site.register(Product, ProductAdmin) admin.site.register(Organization) This results in the following, when accessing a Products object through admin: -
Jquery function not defined with onclick attribute set inside django forms (forms.py)
I have a django form with onclick attribute set to a jQuery function located inside a .JS file and I want that function to be called whenever the onclick event is triggered . When I click on the form , it says my function is not defined . Maybe the answer is easy and obvious but I'm kind of newbie in both jQuery and Django .I have googled it around but still can't work this out . Any help would be great . forms.py class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'nationality' ) widgets = { 'nationality': forms.TextInput(attrs={'placeholder': 'Your Country Name ...', 'onclick': 'autocompleteCountry()' }), } index.js $(document).ready(function(){ function loadAutocomplete(id, country){ $(function(){ $(id).autocomplete({ source: country }); }); } function autocompleteCountry(country){ loadAutocomplete('#id_nationality', country); } }; index.html <form method="post"> {% csrf_token %} <div class="fieldset"> {% for field in f %} {{ field|as_crispy_field }} {% endfor %} </div> </form> -
convert django template to string contain `extends` tag
I have a template which is contain an extends tag as below: {% extends 'SearchEngine/base.html' %} When I covert the template to string using render_to_string to return as the Ajax response it only converts the extended template. This is while if I remove the extends it will works correctly. Now the question is that how to convert such inherited templates to string properly? -
get_queryset not working for drf RetrieveUpdateDestroyAPIView
I am trying using get_queryset function for my raw sql query in the RetrieveUpdateDestroyAPIView . This is working fine with ListCreateAPIView(). I am new to drf . So could please explain if there is anything doing wrong. views.py class SubnetGatewayDevice(generics.ListCreateAPIView): serializer_class = SubnetDeviceSerializer def get_queryset(self): sql_query = " select sd.hostname,sd.ma_number,sd.datacenter_id, ssd.ip, ssp.subnet_id, " \ " sd.id, ssd.id, ssp.id from subnets_device sd" \ " inner join subnets_subnetdevice as ssd on sd.id = ssd.device_id" \ " inner join subnets_subnetphysical as ssp on ssd.subnet_physical_id = ssp.id" return list(Device.objects.raw(sql_query)) def perform_create(self, serializer): serializer.save(data=self.request.data) class SubnetGatewayDeviceDetail(generics.RetrieveUpdateDestroyAPIView): # parser_classes = (JSONParser,) serializer_class = SubnetDeviceSerializer def get_queryset(self): device_id = "5" sql_query = " select sd.hostname as hostname,sd.ma_number,sd.datacenter_id, ssd.ip, ssp.subnet_id, " \ " sd.id, ssd.id, ssp.id from subnets_device sd" \ " inner join subnets_subnetdevice as ssd on sd.id = ssd.device_id" \ " inner join subnets_subnetphysical as ssp on ssd.subnet_physical_id = ssp.id " \ " where sd.id = "+device_id return Device.objects.raw(sql_query) # def perform_create(self, serializer): # serializer.save(data=self.request.data) Serializer.py class SubnetDeviceSerializer(serializers.ModelSerializer): subnet_id = serializers.IntegerField(required=True) datacenter_id = serializers.IntegerField(required=True) ip = serializers.IPAddressField(protocol='both') class Meta: model = Device fields = ('id','hostname','ma_number','subnet_id','datacenter_id','ip') def create(self, validated_data): subnet_id = validated_data['subnet_id'] ma_number = validated_data['ma_number'] hostname = validated_data['hostname'] data_center_id = validated_data['datacenter_id'] gateway_ip= validated_data['ip'] subnet_physical = SubnetPhysical.objects.get(subnet_id=subnet_id) if subnet_physical: … -
old listviews being evaluated
I am using windows 10, django 1.11 python 3.4 ` http://127.0.0.1:8000/venues/16165/ in url.py url(r'^venues/(?P<pk>\w+)/$', VenueDetailView.as_view()), in views.py class VenueDetailView(ListView): # template_name = 'venues_list.html' queryset = TestVenue.objects.all() when I enter the url I get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/venues/ Using the URLconf defined in bioskop.urls, Django tried these URL patterns, in this order: ^admin/ ^$ ^venues/(?P<pk>\w+)/$ ^about/$ ^contact/$ The current path, venues/, didn't match any of these. if i enter http://127.0.0.1:8000/venues/asdlkfj;akdjf I get a valid web page from an old listview. I've tried clearing cache and using a different browser. I've tried rebooting and restarting server python -B manage.py runserver I'm at a loss why it keeps using old code to render pages. -
Django application not rendering static files
I have been trying to create a django application, but there is a problem with django rendering static files: Here is my setting files static configuration: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") I have placed all the static files in a static folder inside the location where manage.py resides. -
dificulty with managing the error in Django - NoReverseMatch at
I need to make a query after two selection of the parameters. Something is rong is - Error during template rendering - valoare_detail.html and it is writing - NoReverseMatch at /valoare/MICA/ Reverse for 'contract_list' with arguments '()' and keyword arguments '{'valoare': 'MICA', 'tip': 'BUNURI'}' not found. 1 pattern(s) tried: ['valoare/(?P<valoare>[A-Z]{4})/(?P<tip>[A-Z]{8})/$'] I can not manage the selection in template - contract-list.html. Tell me the correct answer in code. models.py class Valoare(models.Model): VALOARE_CHOICES = ( ("MICA","mica"), ("MARE","mare"), ) tip_valoare = models.CharField(max_length=4, choices=VALOARE_CHOICES, default="MICI", verbose_name='valoarea contractului') file_name = models.FileField(null=True, blank=True, upload_to='contracte/templates/contracte/img/', verbose_name='img path') def __str__(self): return self.tip_valoare class Tip(models.Model): TIP_CHOICES = ( ("BUNURI","bunuri"), ("SERVICII","servicii"), ("LUCRARI","lucrari"), ) tip_contract = models.CharField(max_length=8, choices=TIP_CHOICES, default="BUNURI", verbose_name='tipul contractului') file_name = models.FileField(null=True, blank=True, upload_to='contracte/templates/contracte/img/', verbose_name='img path') def __str__(self): return self.tip_contract class Contract(models.Model): valoare = models.ForeignKey('Valoare') tip = models.ForeignKey('Tip') data = models.DateField(blank=True, null=True) file_name = models.FileField(null=True, blank=True, upload_to='pdf/', verbose_name='contract file name') def __str__(self): return str(self.CPV) class Meta: ordering = ["data"] urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.valoare_list, name='valoare_list'), url(r'^valoare/(?P<valoare>[A-Z]{4})/$', views.valoare_detail, name='valoare_detail'), url(r'^valoare/(?P<valoare>[A-Z]{4})/(?P<tip>[A-Z]{8})/$', views.contract_list, name='contract_list'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Valoare, Tip, Contract def valoare_list(request): valoares = Valoare.objects.all() return render(request, 'contracte/valoare_list.html', {'valoares': valoares}) def valoare_detail(request, valoare): valoare = get_object_or_404(Valoare, … -
Django items order form
Imagine simple jquery sortable. I need to create a form in Django made from model field ManyToMany which contains block(Model) elements which are actually the items in this sortable. How to do it the right way? Which type of form field to choose? I imagine that I will call method save on this form and it will change the position property of these blocks. -
Get the latest result from multiple ajax searches
i' ve a django based website where there' s a huge search page with multiple options. Usually an ajax call gets fired on the focusout event. There' s a field where You can search by the greater than and less than attributes for a date. For instance if i select the 1st of February from 2012 as a gt value, fetching the result and the rendering takes more than 30 seconds. If in the meanwhile i select 1st of March from 2012 as a lt value, it' ll be rendered within 2 seconds, so that result will be loaded and will be visible (with like 30 results). The problem is that after ~20 seconds the result of the first call arrives and will be loaded (with like 1000 results) into the DataTable, so overwrights the correct result. This is rather a theoretical question how would You prevent this from happening? So when a newer ajax query is fired, the first should either stop, or at least not loaded. What technologies are there or what principles? For the ajax query itself i' m using something like this: $.get('url?terms', function(data) { valid_data = ...; $('#sth_list').html(valid_data); $('#sth_table').DataTable(); } . -
The message is not sent through (send_message) in fcm_django
from fcm_django.models import FCMDevice token = 'enp-DWGeMIo:APA91bFS2VQahjLcNr7sO8YR4_KtTpKCk.....' device_id = '69fd7ed5a6aef646_samsung_SM-J700H' device = FCMDevice.objects.filter(registration_id=token) data_message = { "to": token, "data": { "id": device_id, "type": "wifi_restart", }, } device.send_message(data=data_message, delay_while_idle=False, time_to_live=86400,api_key='AIzaSyAvBX6J4nalP1UG8Un2lZZCT672v1f0....') -
Upload django app to my host
I have a app like this : tst1 ---- tst1 --------- settings.py --------- urls.py --------- __init__.py --------- wsgi.py -----tst_1 ---------- migrations --------------------- __init__.py ----------models.py ----------views.py It is just part of my directories now i want to upload this app to my host how can i do this ?? I try the way that tis pages says : [http://wiki.helionet.org/Django][1] but i show this error when load site : Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster@snip77.heliohost.org and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. my wesite is : snip77.heliohost.org if you have a way tell me. tnx a lot -
displaying messages for a group of users from external services with django message api
I wonder if there is a way or if it is recommended to use the django message api to display logging output from a management command (run by cron) to a group of users. As I understand, the django message api works with user sessions and cookies and needs a request object to register the messages. Is there an easy way to send this logging messages into the django messages system or should i use a different way (via DB) to save such messages? It would also be interesing to display some notifications for admin users, if anonymous user completed a certain task (of course this could be achived by direct db query also). -
Django, login fail and return a raw html code page, plz
I wrote a login page, of course it contains a form. Then I wrote my LoginView use class like this: class LoginView(View): def get(self, request): return render(request, "login.html") def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return render(request, 'index.html') else: return render(request, 'login.html', {'msg':'账号未激活!'}, {'login_form':login_form}) else: return render(request, 'login.html', {'msg':'用户名不存在!'}, {'login_form':login_form}) else: return render(request, 'login.html', {'msg':'用户名或密码错误!'}, {'login_form':login_form}) Ignore the Chinese you may not know. I tried to input wrong username and password, it should return the same page with error message to allow me to input again, but... It return a page contains all html code, seems like the browser didn't compile the codes? If there's a mistake I made in LoginView? And Thanks for your help.谢谢 -
Retrieve user's created db objects in Django views
I'm trying to retrieve user's created "Instances" db objects in views, I have successfully get and parsed for templates but in views I received complete object but not able to parse it, when I try to access it's models field it through an error as : 'QuerySet' object has no attribute 'name' Here's my code: Instances/models.py class Instance(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, related_name='instances') name = models.CharField(max_length=255, name='name') serverFile = models.TextField(default='', blank=False) jsonPackageFile = models.TextField(default='', blank=False) created_at = models.DateTimeField(default=timezone.now, editable=False) class Meta: ordering = ['-created_at'] Images/views.py class BuildImage(LoginRequiredMixin, CreateView): form_class = BuildImageForm model = Image template_name = 'images/buildImage.html' success_url = 'user/gui' def get(self, request, *args, **kwargs): objectlist = request.user.instances.all() return render(request, 'images/buildImage.html', {'form': forms.BuildImageForm, 'objectlist': objectlist}) def post(self, request, *args, **kwargs): if request.method == 'POST': form = BuildImageForm(request.POST) if form.is_valid(): data = form.cleaned_data form.instance.user = self.request.user form.instance.tagName = data['tagName'].lower() instance_name = data['instance'] form.instance.instance =instance_name # writeFiles(request, name=instance_name) form.save() img = request.user.instances.filter(name=instance_name) print(img) print(img.name) else: print(form.errors) return HttpResponseRedirect(reverse('users:gui')) print(img) display <QuerySet [<Instance: Instance object>]> in console.But print(img.name) throw an error as 'QuerySet' object has no attribute 'name' -
My buttons on JavaScript Modal don't work
plz look at this picture, buttons not working post_detail.html(extends base.html) <!-- Button trigger modal --> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Remove </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Remove</h4> </div> <div class="modal-body"> Are you sure to remove? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Remove</button> </div> </div> </div> </div> base.html <head> <!-- 합쳐지고 최소화된 최신 CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <!-- 합쳐지고 최소화된 최신 자바스크립트 --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> base.html </body> <script> $('#myModal').on('shown.bs.modal', function () { $('#myInput').focus() }) </script> </html> Why are the buttons on the modal not working? I cannot even click them. It's all gray. -
Bad SSL Client after deploying to Convox / AWS
I am trying to check and understanding the complexity of deploying using Convox to AWS. I am using their example project right now, to start it off. But i am unable to deploy it even to local or aws using Convox. Convox uses Docker to deploy and provides a Heroku style deployment for AWS. When I visit the url, it automatically redirects to the https based url and gives a bad SSL client error. ERR_BAD_SSL_CLIENT_AUTH_CERT Example Project Github URL This is the docker-compose.yml file. web: build: . environment: - SECRET_KEY labels: - convox.port.443.protocol=tls - convox.port.443.proxy=true links: - database ports: - 8000:4000 - 443:4001 database: image: convox/postgres ports: - 5432 This is the Docker file. FROM convox/django # replace exampleapp and exampleproject to tailor the image to your project # PROJECT is also used by gunicorn in the convox/django Dockerfile ENV APP exampleapp ENV PROJECT exampleproject # an empty SECRET_KEY during manage.py commands will result in an error ENV SECRET_KEY foo # copy only the files needed for pip install COPY requirements.txt /app/requirements.txt RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt # copy only the files needed for collectstatic COPY ${APP}/static /app/${APP}/static COPY ${PROJECT} /app/${PROJECT} COPY manage.py /app/manage.py RUN … -
how does python some_item|divisiblyby:"2"
Just saw this in a Django tutorial. I'm confused on the syntax here and how this works. Isn't | the bitwise OR? Can someone please explain to me how this works? the code in the Django tutorial is exactly as follows: {% if some_item|divisibleby:"2" %} -
How to access a list by index in django template inside a for statement?
I'm new to python/django. I'm using django 1.11, python 3.5.2. This is the important part of my code in views.py ListaValoresLeidosXML = [] for sec in secciones: print(sec.contenidoxml) treexml = ET(fromstring(sec.contenidoxml)) Lista = [] for child in treexml.findall('caracteristica'): nombre = child.find('nombre').text Lista.append(nombre) ListaValoresLeidosXML.append(Lista) for lista in ListaValoresLeidosXML: for valor in lista: print(valor) print('*****') return render(request, 'editarCatElem.html', { 'elemento': ElemSeg, 'link': tutorial, 'subelementos': subelementos, 'secciones': secciones, 'listaXML' : ListaValoresLeidosXML }) I'm reading a string field in my database, it contents a xml-formatted text, using treexml I can get all the atributtes. Finally I have a list of lists, each list have values of a section, it means if I have "n" sections then I'll have "n" lists inside a list. I'm sending a List called ListaXML to my template. In my template I'm trying to iterate it {% for seccion in secciones %} <div style="display: block" class="form-group"> <div style="display: block" class="form-group"> <label class="control-label col-md-2" for="nombreSeccion">Sección <span class="required">*</span></label> <div class="col-md-2"><input type="text" value='{{ seccion.nombre }}' id="nombreSeccion" name="secciones[][nombreSeccion]" class="form-control col-md-2"></div> <label class="control-label col-md-2" for="descSeccion">Descripción <span class="required">*</span></label> <div class="col-md-2"><input type="text" value='{{ seccion.descripcion }}' id="descSeccion" name="secciones[][descripcionSeccion]" class="form-control col-md-2"></div> </div> <div class="col-md-offset-2 col-md-7"> <div class="form-horizontal form-label-left" style="background:lightblue; padding:8px;"> {% for caracteristica in listaXML %} # <-- Here … -
comparing the datefield to today and changing the integerfield automatically every day
I'm making a website using django. class Member(models.Model): ... end_date = models.DateField(blank=True, default=(datetime.now() + timedelta(days=30))) Membership_status = models.IntegerField(blank=True, null=True, default=1) # 1 = active, 0=deactivate, 2=refund What I want to do is comparing the end_date field to today.date every 1.a.m. and if today's day < end_date, Membership_status field is changed to 0 automatically. I heard I should use django-kronos(https://github.com/jgorset/django-kronos). But I can't understand the using method. Is there anyone can tell me details how I implement what I want? Any help will be very helpful to me, thanks! -
Password Reset View not sending Email (Django 1.11)
i am using Django Build in PasswordResetView class. i am using Django File backend in settings. i tried to reset password of an existing account and django returns a success but still no email is sent. Here is code for reference: settings.py EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = os.path.join(BASE_DIR,'sent_emails') views.py class MyPasswordReset(PasswordResetView): email_template_name = 'email/forgot_password.html' form_class = ForgotPassword from_email = 'admin@crud.com' success_url = reverse_lazy('users:password_reset_done') form.py class ForgotPassword(PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput(attrs= {'class': 'form-control', 'title': 'Enter Email', 'placeholder': 'Email'}), max_length=50, label=False, required=True, ) Password Reset Email Template email/forgot_password.html you forgot your password!! Sample Email Code for Complete reference: https://github.com/deepak1725/basicCrud/tree/dk-signup/users -
Is it possible to send info using javascript to python view through the template
I have a template which is contain a jQuery module called multi-select and I want to find the selected items and send them to the view function. I'm able to do this using Ajax but since I want to do some processes on data and show the results to user I'd like to render a new template which is not possible due to the restrictions of HTTP protocol. I can also redirect the url but since I want to pass data to the template this ain't possible as well. (I tried reverse and kwargs but wasn't successful). Now I want to see is there any way to just send the data through the request. Here is my template: {% extends 'SearchEngine/base.html' %} {% block content %} <h1>Select server</h1> <a href='#' id='select-all'>select all</a> --- <a href='#' id='deselect-all'>deselect all</a> <form id='pre-selected-options' multiple='multiple'>{% csrf_token %} {% for name in servers %} <option value={{name.path}}>{{name}}</option> {% endfor %} </form> <h1>Enter your word here</h1> <div class="post-form"> {{ search_form.as_p }} <button id="submit_search" class="save btn btn-default" onclick="return search_result()">Search</button> </div> {% endblock %} And here is the required JS to retrieve the selected servers: var options = $('#pre-selected-options option:selected'); var selected = {}; for(var i=0;i<options.length;i++){ selected[options[i].text] = options[i].value; }