article

Sunday, July 19, 2020

Python Django Simple Dropdown List Binding Populate Data

Python Django Simple Dropdown List Binding Populate Data


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'
urls.py
 
#urls.py
from django.contrib import admin  
from myapp import views  
from django.conf.urls import url
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('showlist/', views.showlist, name='showlist'),
]
templates/home.html
//templates/home.html
{% extends 'base.html' %}

{% block content %}
  <p><b>City : </b> 
         <select name="city" class="form-control">
   {% for results in showcity %}
            <option value="{{ results.id}}">{{ results.name}}</option>
   {% endfor %}
         </select>
</p>  
{% 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 Simple Dropdown List Binding Populate Data {% 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 Simple Dropdown List Binding Populate Data</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>

Related Post