article

Thursday, July 23, 2020

Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist


Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist


views.py
 
#views.py
from django.shortcuts import render
from myapp.models import City
 
def showlist(request):
    results=City.objects.all
    return render(request, "home.html",{"showcity":results})
models.py
 
#models.py
from django.db import models
  
class City(models.Model):
    name = models.CharField(max_length=30)
   
    def __str__(self):
        return self.name
     
    class Meta:
        db_table = 'myapp_city'
templates/home.html
//templates/home.html
{% extends 'base.html' %}

{% block content %}
    <p>Enter your City:</p>
    <input type="text" list="citylist" Placeholder="Search City.." class="form-control" style="width:300px;">
    <datalist id="citylist">
 {% for results in showcity %}
        <option value="{{ results.name}}">
 {% endfor %}
    </datalist>
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Python Django How to Create a simple Autocomplete Dropdown using HTML5 Datalist</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>

Related Post