首页 > 解决方案 > 如何从 mysql 中检索数据并使用 django 将其显示在视图中

问题描述

这是我的模型:

  from django.db import models

    # Create your models here.
    class Contact(models.Model):
        name = models.CharField(max_length=125, null=True)
        email = models.EmailField()
        address = models.CharField(max_length=255)
        city = models.CharField(max_length=150)
        zipcode = models.CharField(max_length=15)

我正在尝试在视图中显示数据:

<div class="row d-block">
    <table class="table table-responsive">



  <thead>
            <tr>
                <th>Name:</th>
                <th>Email:</th>
                <th>Address:</th>
                <th>City:</th>
                <th>Zipcode:</th>
            </tr>

        </thead>
    <tbody>
        {% for row in rows%}
        <tr>
            <th>{{rows.name}}</th>
            <th>{{rows.emai}}</th>
            <th>{{rows.address}}</th>
            <th>{{rows.city}}</th>
            <th>{{rows.zipcode}}</th>
        </tr>
        {%endfor%}
    </tbody>
</table>

这是我在数据库中发送数据的函数。我的下一步是从 db 中检索数据并将其显示在 html 中:

 from django.shortcuts import render
    from django.http import HttpResponse
    from pages.models import Contact
    # from django.views import View
    # Create your views here.
    def home(request):
      return render(request, 'index.html', {'title':'Home Page'})
    def contact(request):

      if(request.method == 'POST'):
        data = Contact(
          name = request.POST['name'],
          email = request.POST['email'], 
          address = request.POST['address'],
          city = request.POST['city'],
          zipcode = request.POST['zipcode'],  

        )
        data.save()

        dbdata = Contact.objects.all()
        print(dbdata)
      return render(request, 'contact.html',  {'title':'Contact Page','row':dbdata})

当我尝试从 db 中检索数据时,出现以下错误:

UnboundLocalError at /pages/contact/
local variable 'dbdata' referenced before assignment

如何检索和显示我的数据?

标签: pythondjango

解决方案


传递上下文时出错..您在上下文中使用键。但是您在 for loop.change 键中调用。将键行更改为。并保持原样循环。

这里改变了传递上下文字典键

return render(request, 'contact.html',  {'title':'Contact Page','rows':dbdata})

请让我知道它是否有效..


推荐阅读