Home > Software engineering >  How to retrieve data from MySQL database in Django and display it in html page?
How to retrieve data from MySQL database in Django and display it in html page?

Time:12-24

I am trying to add data from MySQL database and display it in a html page using python.

Here is my view.py:

def show(request):
    data = Persons.objects.all()

    person = {
       "Persons": data
    }
    return render(request, "home.html", person)

models.py:

class Persons(models.Model):   
   PersonID = models.IntegerField()
   LastName = models.CharField(max_length=100)
   FirstName = models.CharField(max_length=100)
   Address = models.CharField(max_length=100)
   City = models.CharField(max_length=100)
   class Meta:
      db_table = "persons"

html:

  <div>
      {% for item in Person %}
          <div >{{ item.LastName }}</div>
       {% endfor %}
  </div> 

But I didnot retrieve anything. Any help will be highly appreciated.

CodePudding user response:

You create a dict key Persons

person = {
   "Persons": data
}

...but you iterate over Person

{% for item in Person %}
  • Related