Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rest-auth :Exlamation mark comes before password
I am using rest-auth for authentication. after registration when I try to login it show { "non_field_errors": [ "Unable to log in with provided credentials." ] } and when I saw the user on admin panel an an '!' mark comed before password for example password ='!72wlGF0RiGRraz69sveb63FUrebNkAW9xmOoL16C' please help -
Display uploaded images in HTML - DJANGO
I am trying to display images that are upload by the user in my HTML. I'd set the following: Settings: MEDIA_URL = '/media/' MEDIAFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, "media") Upload files within the model to directory: class Artikel(models.Model): artikel_pic = models.ImageField(upload_to='assortiment/images/', blank=True, verbose_name="Afbeelding") urls: urlpatterns = [ path(r'', include('main.urls')), path(r'', include('assortiment.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url that is given when i open the image in the admin panel: http://127.0.0.1:8000/media/assortiment/images/choco_ijs.jpg It displays correctly over here. html code that needs to diplay the image: <img class="card-img-top" src="{{MEDIA_URL}}/images/{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> I get a not found (304) error: "GET /media/assortiment/images/choco_ijs.jpg HTTP/1.1" 304 It looks like everything is going fine. Can't figure out what is going wrong though. I tried to change the src within the html file to: <img class="card-img-top" src="{{ artikel_pic }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="/images/{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="{{MEDIA_URL}}{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> Does anyone have some suggestions how to do this correctly? Thank you in advance! Sincerely, Rick P.S. Learned coding by doing, do not have any coding background. Just Stack, Google and Youtube :) -
what is the correct django version of my environment? ( is "python -m django --version" wrong ?)
why python -m django --version shows 3.0 (it may wrong), while django-admin --version show 2.2.5 in my project in setting.py file Generated by 'django-admin startproject' using Django 2.2.5. (django3+) C:\>python -m django --version 3.0 (django3+) C:\>django-admin --version 2.2.5 -
How to retrieve data from an input radio button in Django and send it to a view?
I have made a ToDoList app using Django a few months ago. Now, I want to add another feature called TaskLists. Like shopping lists or something like that. So previously, in my app home page there was one text field (which was a Django form of course) and user could enter a task and then add it. Now, I want to add more buttons to show the user a list of available Lists that they have created. Like if they have "Shopping" list and a "Movies to watch" list, I want to display two radio buttons (using Bootstrap) which a user could click on to indicate that they want this task to be under that list and then add it. I have done all these and got my List radio buttons to work and show up. But the main issue that I have ran into is that how can I pass this data, the list which the user wants this task to be in, to my Django view functions for processing? This is my code: <div class="content section"> <form method="POST" name="add_form"> {% csrf_token %} <fieldset class="form-group dark-mode-assist"> <legend class="border-bottom mb-4">New ToDo!</legend> {{ add_form|crispy }} <div class="form-group"> <div class="btn-group btn-group-toggle" data-toggle="buttons"> … -
I want to use variable in django template ,how can i use it .//
<a href="{% static {{i.pdf}} %}"> </a> i want to use like this ( variable in template tag )but cant please help thank you -
authorize api keys in django
How to verify the api keys in django? im using rapidapi and they have this key and how do i authorize it with the url views.py def thanks(request): url = "https://webknox-trivia-knowledge-facts-v1.p.rapidapi.com/trivia/random" headers = { 'x-rapidapi-host': "webknox-trivia-knowledge-facts-v1.p.rapidapi.com", 'x-rapidapi-key': "2b01c1685cmsh18f385b26cfee59p164749jsn3684ad96eaca" } r = requests.get(url) json_data = json.loads(r.text) print(json_data) return render(request,'portofolio/thankyou.html',headers) The print returns "{'message': 'Missing RapidAPI application key. Go to https://docs.rapidapi.com/docs/keys to learn how to get your API application key.'}" I have a key and how do i authorize it? and use it in my django template! Thanks in advance :) -
Django ContentTypes convert uuid field to integer field
I have a situation where object_id for ForeignKey accepts a PositiveIntegerField but all id's of my models are set as uuid . I looked up the documentation and found that i should use get_prep_value(value) or get_db_prep_value(value, connection, prepared=False)¶ The question is how should i exactly do it? Here is the code of model that contains the foreignRelation target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj', on_delete=models.CASCADE) target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) target = GenericForeignKey('target_ct', 'target_id') created_at = models.DateTimeField(auto_now_add=True, db_index=True) Field from all other models id = models.UUIDField(default=uuid4, primary_key=True, editable=False) -
In the django templating language how to count the number of items of same type
I am trying to build a table that lists items that can be categorized by type. I can list out all the items and their types which are returned from my database in a table with no problems. That is in fact what I would like to do. Since these items can be categorized by type I see no reason to list the same type multiple times. The table is listed in order by category type so all items of the same type are already grouped together. In effect what I have is something along the lines of: /________________/ /|item A | category A|/ /|item B | category A|/ /|item C | category A|/ /|item D | category B|/ /|item E | category B|/ /|item F | category B|/ /------------------------/ what I actually would like see is /________________/ /|item A |```````````````|/ /|item B | category A|/ /|item C |_________|/ /|item D |``````````````|/ /|item E | category B|/ /|item F |_________|/ /-------------------------/ This can be done easily enough with a rowspan in the html. My issue the amount of rows to 'rowspan' is not known ahead. What I have in the Django template is: <table class="table table-sm"> <thead> <tr> <td scope="col">Col … -
Django periodic task celery
I'm a newbie in Django and Celery. Help me please, I can't understand, how it work. I want to see in my console "Hello world" every 1 min. tasks.py from celery import Celery from celery.schedules import crontab from celery.task import periodic_task app = Celery('tasks', broker='pyamqp://guest@localhost//') @periodic_task(run_every=(crontab(hour="*", minute=1)), ignore_result=True) def hello_world(): return "Hello World" celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.settings.local") app = Celery('test') app.config_from_object('celeryconfig') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app celeryconfig.py broker_url = 'redis://localhost:6379' result_backend = 'rpc://' task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] timezone = 'Europe/Oslo' enable_utc = True It's a simple celery settings and code, but doesn't worked =\ celery -A tasks worker -B And nothing happens. Tell me what am I doing wrong? Thank you! -
Incorrect redirect to user profile details
If the user is a staff' member he will see the list of users and their profile details, in addition to his profile details. If not, he will see only his profile details. models.py class UserProfile(AbstractUser): def __str__(self): return self.username def get_absolute_url(self): return reverse("user_details", kwargs={"username":self.username}) views.py def usersList(request): """ The list of all users """ if request.user.is_superuser: users_list = UserProfile.objects.all() elif request.user.is_staff: users_list = UserProfile.objects.filter(is_staff=False) else: raise PermissionDenied template = 'usermanager/users_list.html' context = { 'users': users_list, } return render(request, template, context) def userDetails(request, username): """ User details """ user_details = get_object_or_404(UserProfile, username=username) template = 'usermanager/user_details.html' context = { 'user_details': user_details, } return render(request, template, context) urls.py path('user-list/', views.usersList, name='users'), path('<username>/', views.userDetails, name='user_details'), template.html {% for user in users %} <h1>{{ user.username }}</h1> <p>Name: {{ user.first_name }}</p> <p>Surname: {{ user.last_name }}</p> <p>Email: {{ user.email }}</p> {% if request.user.is_superuser %} {% if user.is_staff %} <button class="btn btn-warning">Staff</button> {% else %} <button class="btn btn-primary">User</button> {% endif %} {% endif %} <a class="btn btn-danger" href="{% url 'user_details' username=userprofile.user.username %}">Details</a> <hr> {% endfor %} I can see correctly the list of all users. Bob is one of my user, if I click on his details I see my personal profile. This happen for all of … -
Security with google maps API key
first post on here. I have a google maps API in a window on my Django site which functions when the API is directly in the script src however for security I have set the API key as an environment variable but I am greatly struggling to set this up into the src link. I have attempted all possible solutions I have found with no luck. Thanks for any suggestion! -
Django REST Framework validation function has different signature than Django models?
I'm developing a reservation system REST api in Django with a relatively simple model that will determine if a user has a valid membership in order for them to reserve a certain item. When creating a reservation, I have a simple validator written like this: def validate_member(value): """ Validator for a user in a reservation. Will throw a ValidationError if the user does not have an updated membership. """ if not valid_membership(value): raise ValidationError("User does not have a valid membership!") This validation is run on the foreign key field in the reservation table, which is written as such: # The gear item in the reservation gear_item = models.ForeignKey(Entry, on_delete=models.SET_NULL, null=True, help_text="The gear item being reserved.", validators=[validate_entry] ) The serializer for this model is written as a ModelSerializer, like such: class ReservationSerializer(serializers.ModelSerializer): class Meta: model = Reservation fields = "__all__" This design works fine for queries in the REST API, but fails for any modifications in the admin console, with the error: 'int' object has no attribute 'rentable' It seems that validating a foreign key in the admin console passes the primary key integer into the value parameter of the validation function, while the REST API passes in the entire object. … -
Django with Vue, detect form validation error
I have a Django ModelForm which is displayed in the template by using using crispy forms. After the user fills out the fields and presses a Submit button, an email is sent at the backend using Django's core send_email. The problem is that the call to send_email is synchronous, so the user has to wait for the next page to load (success/failure page) but in this time the user might press the Submit button again and this generates multiple POSTs, making multiple emails. I want to use Vue.js to make the button inactive once the user presses it but only if it passes Django's form validation. Is there a way to detect this? -
Django syntax error after activated venv and checking python and django version
I've already activated my venv FYP2, and also check my python and django version, they are all compatible, I have no idea why this error keeps coming up. Python = 2.7.16 Django = 1.11 (base) C:\Users\Gary>cd FYP2 (base) C:\Users\Gary\FYP2>activate FYP2 (FYP2) C:\Users\Gary\FYP2>python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax (FYP2) C:\Users\Gary\FYP2>python --version Python 2.7.16 :: Anaconda, Inc. (FYP2) C:\Users\Gary\FYP2>python -m django --version 1.11 (FYP2) C:\Users\Gary\FYP2> -
Form not displaying form instance ChoiceField and DateField
Hello I'm trying to edit my form instance but the ChoiceField or DateField dont use the default value I wrote. I tried with and without Widget Tweaks. The IntegerField instance data is showing up though so I don't understand why arent the other ones working. These are the files: models.py class Venta(models.Model): Empresa=models.ForeignKey(Cuenta,default=None,on_delete=models.CASCADE) Facturacion=models.DateField(blank=True , null=True) Cobro=models.DateField(blank=True , null=True) Monto=models.FloatField() meses=( ('ENERO','ENERO'), ('FEBRERO','FEBRERO'), ('MARZO','MARZO'), ('ABRIL','ABRIL'), ('MAYO','MAYO'), ('JUNIO','JUNIO'), ('JULIO','JULIO'), ('AGOSTO','AGOSTO'), ('SEPTIEMBRE','SEPTIEMBRE'), ('OCTUBRE','OCTUBRE'), ('NOVIEMBRE','NOVIEMBRE'), ('DICIEMBRE','DICIEMBRE') ) espacios=( ('OFICINA A','OFICINA A'), ('OFICINA B','OFICINA B'), ('OFICINA C','OFICINA C'), ('OFICINA D','OFICINA D'), ('ESTUDIO 1','ESTUDIO 1'), ('ESTUDIO 2','ESTUDIO 2'), ('ESTUDIO 3','ESTUDIO 3'), ('AUDITORIO','AUDITORIO'), ('OPEN SPACE','OPEN SPACE') ) medios=( ('EFECTIVO','EFECTIVO'), ('TRANSFERENCIA','TRANSFERENCIA'), ('CHEQUE','CHEQUE'), ('MERCADOPAGO','MERCADOPAGO'), ('TARJ DE CREDITO','TARJ DE CREDITO'), ('TARJ DE DEBITO','TARJ DE DEBITO'), ) Iva=models.FloatField(default=0 ,blank=True) Mes=models.CharField(max_length=30,choices=meses , null=False ) Total=models.FloatField(default=0) Espacio=models.CharField(max_length=30,choices=espacios,default="OFICINA A", null=False ) Medio=models.CharField(max_length=30,choices=medios,default="TRANSFERENCIA", null=False ) def __str__(self): return self.Empresa.Cliente def get_absolute_url(self): return f"{self.id}/" forms.py from django import forms from .models import Cuenta , Venta from .my_choices import respuestas class CuentaForm(forms.ModelForm): class Meta: model=Cuenta fields=['Cliente','Descripcion','Tipo','Estado'] class VentaForm(forms.ModelForm): class Meta: model=Venta fields=['Empresa','Mes','Medio','Monto','Iva','Facturacion','Cobro'] views.py @login_required(login_url='/login/') def venta_edit_view(request,my_idd,my_id): venta=get_object_or_404(Venta,id=my_idd) my_form=VentaForm(request.POST,instance=venta) if my_form.is_valid(): my_form.save() return redirect("../") context={"form" : my_form , "obj":venta} return render(request,"keyaccounts/venta_edit.html",context) venta_edit.html <form action='.' method='POST'>{%csrf_token%} <div id="empresa"> <h3>Empresa</h3> {{form.Empresa}} </div> <div id="mes"> <h3>Mes</h3> {{form.Mes}} </div> <div id="medio"> … -
Why can't i create an inherited model?
Im a newbie in Django and have model inheritance problem. My models: class Interaction(models.Model): nom = models.CharField(max_length=128, unique=True) lieu = models.ForeignKey(Lieu, on_delete=models.CASCADE, blank=True, null=True) description = models.TextField(default='...') acces_libre = models.BooleanField(default=True) class Heros(Interaction): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) ############# Attributs ########## corps = models.IntegerField(default=0) coeur = models.IntegerField(default=0) esprit = models.IntegerField(default=0) def __str__(self): return self.nom class Personnage(Interaction): # Attributs corps = models.IntegerField(default=50) coeur = models.IntegerField(default=50) esprit = models.IntegerField(default=50) def __str__(self): return self.nom My migrations: migrations.CreateModel( name='Interaction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(max_length=128, unique=True)), ('description', models.TextField(default='...')), ('acces_libre', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='Heros', fields=[ ('interaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='aventures.Interaction')), ('corps', models.IntegerField(default=0)), ('coeur', models.IntegerField(default=0)), ('esprit', models.IntegerField(default=0)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], bases=('aventures.interaction',), ), migrations.CreateModel( name='Personnage', fields=[ ('interaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='aventures.Interaction')), ('corps', models.IntegerField(default=50)), ('coeur', models.IntegerField(default=50)), ('esprit', models.IntegerField(default=50)), ], bases=('aventures.interaction',), ), migrations.AddField( model_name='interaction', name='lieu', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aventures.Lieu'), ), If i try to creeate a heros in django admin i have: no such column: aventures_heros.interaction_ptr_id If i try to create a Personnage: no such table: aventures_personnage I tried to delete my migrations but it didn't work. I did delete all my old instance from my old models, it didn't work too... I don't anderstand why it doesn't works can … -
Pass a curly braced data in Ajax in Django
In my Django project the user can add some saved products into a database. I have a view where the saved products are displayed. The user can then delete them if he wants to. To do so I am trying to implement an AJAX call. My HTML: <div class="col-md-1 my-auto mx-auto"> <form id="form_id" method='post'>{% csrf_token %} <button type="submit"><i class='fas fa-trash'></i></button> </form> </div> My AJAX: $("#form_id").on('submit', function(event) { event.preventDefault(); var product_id ='{{ saved.original_product.id }}'; console.log(product_id); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product_id': product_id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) console.log(product_id) } }); }); And my view.py: def delete(request): data = {'success': False} if request.method=='POST': product_id = request.POST.get('product_id') print (product_id) data['success'] = True return JsonResponse(data) My view is not doing much for now but I am a learning Ajax for now and I do it one step at a time. What I want now is my print() and console.log() to display the value of {{ saved.original_product.id }} because for now then don't display it's value but {{ saved.original_product.id }} literal. I think the problem comes from my HTML. How can I pass the curly braced value into AJAX? -
django signals do not send mail
I have a blog and I want to send e-mail my subscribes when I published new post. I used django signals. My problem is that signal is not working. I can send mail when I try django shell. My files following : signals.py -
Django request.FILES gets name, filename but not file (blob)
I'm trying to send an audiofile via a POST request to the server (aws, ec2) and I'm using Django, but my request.FILES doesn't receive the blob file, but it DOES receive the key and the filename. How can I get the file? Main.js: var fd = new FormData(); fd.append('text', speech); fd.append('audio', blob, 'test.wav'); $.ajax({ type: 'POST', enctype: 'multipart/form-data', url: url, data: fd, processData: false, contentType: false, success: function(response) { console.log(response); } }) speech is String, blob in console is Blob {size: 221228, type: "audio/wav"}, so it does exist. Views.py: def get_blob(request): thislist = [] for key in request.POST: thislist.append(request.POST.get(key)) for key in request.FILES: thislist.append(request.FILES.get(key).name) json_stuff = json.dumps({"check": thislist}) return HttpResponse(json_stuff, content_type="application/json") I've tried with and without enctype, doesn't make a difference. I've tried setting contentType to multipart/form-data, doesn't make a difference. The formdata seems to be sent correctly, because I can get the speech correctly (request.POST). And I can get the key from request.FILES ('audio'), and get the filename ('test.wav'). If I try request.FILES['audio'].read(), it says MultiValueDictError. If I try request.FILES.get('audio').read() it says AttributeError, 'NoneType' object has no attribute 'read'. Does anyone know what's going on and/or can help me with the problem? -
Use buttons (not radiobuttons) for Choicefield in Django?
I have a Django form: class Form0(forms.Form): # Do you agree to the terms? CHOICES = [ (1,'Yes'), (0, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect,choices=CHOICES) It is being rendered in my HTML template. I have made a script to enable submitting the form when clicking on a radio button which works perfectly: <form method="POST"> {{ form.as_table }} {% csrf_token %} <script> $("input[type=radio]").on("change", function () { $(this).closest("form").submit(); }); </script> </form> It looks like this: The problem Is it possible to display the 'Yes' and 'No' radioselect as normal buttons? E.g. using bootstrap buttons like: <button class="btn btn-primary" type="submit">Yes</button> <button class="btn btn-primary" type="submit">No</button> -
How do you add form-#-DELETE to form in Django using Javascript?
I'm trying to delete a form from a formset using javascript. In the Django docs it states: ... if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including form-#-DELETE in the POST data. How do I interact with the POST data using javascript? They even provide an example of what they're looking for: data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '2', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'Article #1', 'form-0-pub_date': '2008-05-10', 'form-0-DELETE': 'on', 'form-1-title': 'Article #2', 'form-1-pub_date': '2008-05-11', 'form-1-DELETE': '', 'form-2-title': '', 'form-2-pub_date': '', 'form-2-DELETE': '', } So I want to somehow add something like 'form-0-DELETE': 'on', to the POST data. But this seems to be Python code. I want to manipulate it in the client with js. -
Extending IntegrityError class in Django
I'm trying to handle this error django.db.utils.IntegrityError: duplicate key value.... The problem is I don't want to catch all the integrity errors, just the one that has the message "duplicate key value" in it. For example, this is what I'm doing: try: activity.save() except IntegrityError as e: # if the error is not a key duplication one then throw again if 'duplicate key value' not in e.args[0]: raise e My question is if there is a way to extend the IntegrityError class so that the child class can check the error message of the IntegrityError class? -
Unable to successfully use axios with React Native to make a request (IOS)
I'm unable to make a successful request with Axios. I have tested with Postman to make sure the server is correct and it works without a problem there. The error I'm getting is Network Error - node_modules/axios/lib/core/createError.js:15:17 in createError - node_modules/axios/lib/adapters/xhr.js:80:22 in handleError - node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse - node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0 - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0 * [native code]:null in callFunctionReturnFlushedQueue The way I'm making my call to the backend is const onSubmit = (e) => { axios.get(`https://127.0.0.1:8080/tasks/`).then((res) => {}).catch((e) => console.log(e)); }; Am I doing something wrong in regards to axios? I don't even hit the endpoint since my print("hit")never gets logged through the phone (works with postman though) Thank you for all the help -
Is there a way in Django CBV post function to add information to context
I've got the following code class MusicFileUploadView(TemplateView): template_name = "music_file_upload.html" def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): if 'csv-file' in request.FILES.keys(): csv_file = request.FILES['csv-file'] upload = FileUpload(csv_file=csv_file) if request.user.is_authenticated: upload.user_uploaded = request.user response = upload.save() if response['error']: #add error to context pass else: pass else: pass return super().get(request, *args, **kwargs) where in the post section I save an upload file and parse it, incase of an error I want to include the message in the context so I can display it on the same page. Is there a way to include that in the post function? -
Change query string to allow for multiple values
I have an issue with my query string, the problem is when multiple values are selected my Django search breaks. I get this in the URL ?Query=value1&Query=Value2. In this scenario, it's only the last value that is searched. What I want to happen is that both values are searched (with the equivalent of an AND operator in-between). This is the desired result ?Query=value1+Value2. I've added my search form that uses Select2 and my Django search view below. If you need anything else let me now. Any help would be much appreciated. Search form on the front end <form id="makeitso" role="search" action="" method="get"> <select class="js-example-placeholder-multiple" name="query" multiple="multiple"> <option value="Value 1">Value 1</option> <option value="Value 2">Value 2</option> <option value="Value 3">Value 3</option> </select> <script> $(".js-example-placeholder-multiple").select2({ placeholder: "Search here", }); </script> <div class="form-inline justify-content-center"> <button type="submit" class="btn btn-xlarge">Search</button> </div> </form> views.py def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = TestPage.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = TestPage.objects.none() # Pagination paginator = Paginator(search_results, 3) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, })