display django model data in custom template


February 2019


3.9k time


I have django models such as this

class District(models.Model):

name = models.CharField(max_length=30,unique=True)
number = models.PositiveIntegerField(null=True,blank=True)
def __unicode__(self):
    return "District (%s,%s)" % (self.name,self.number)
class Meta:
    db_table = 'districts'

And i can be able to enter district names along with their number. What i would like to be able to do is to view these districts that have been entered in a custom template that i have created. Currently the template has a dropdown option using the select tag. How can i be able to pull the data thats entered using the django model and display it in the template that i have created. This is the current code snippet of what is in the html template

  <label for="district"> District</label>
    <select  id="district" name="district">
      <option id="kampala" value="k">Kampala</option>
      <option id="mbale" value="m">Mbale</option>

1 answers


In your view, pass the District objects to the view's context like this :

districts = Districts.objects.all()
return render_to_response('mytemplate.html',{'districts': districts})

and then in your template (mytemplate.html) do like this:

<label for="district"> District</label>
<select  id="district" name="district">
  {% for dist in districts %}
  <option id="{{ dist.name }}" value="{{ dist.number }}">{{ dist.name }} </option>
  {% endfor %}

I hope it helps !