python - 在 Django 中显示来自数据库的动态数据

标签 python html django postgresql

我使用 Django 和 Postgresql 作为数据库。我有一个包含两个字段 nameitem 的 HTML 页面。我可以通过单击提交将数据保存在数据库中。但是,我想在 HTML 页面中显示数据库中保存的数据。这意味着,每当我们加载页面时,它应该显示现有的保存数据,并且在提交新数据后,列表应该更新。下面是我的 python 代码。

模型.py

from django.contrib.auth.models import User
from django.db import models

class AllocationPlan(models.Model):

    name = models.CharField(max_length=50)
    item = models.CharField(max_length=4096)

View .py

class HomePageView(TemplateView):
    template_name = "index.html"
    def post(self, request, **kwargs):
        if request.method == 'POST':
            form = AllocationPlanForm(request.POST)
            if form.is_valid():
                form.save()

        return render(request, 'index.html', { 'form': AllocationPlanForm() })

表单.py

from django import forms
from django.forms import ModelForm
from homeapp.models import AllocationPlan   

class AllocationPlanForm(ModelForm):
    class Meta:
        model = AllocationPlan
        fields = "__all__" 

index.html

<html>
<form method="post">{% csrf_token %}
     Name:<br>
  <input type="text" name="name" >
  <br>
  Item:<br>
  <input type="text" name="item" >
  <br><br>
     <input type="submit" value="Submit"/>

 </form>
{% for i in form %}
{{ i.name }}
{{ i.item }}
{% endfor %}
</html>

它正在返回 NONE

最佳答案

Django 中的表单不用于显示数据列表。它仅用于呈现/验证表单(html 中的 <form> 标记)。另见 the forms doc .

此外,您似乎正在使用 TemplateView不正确。 post您 View 中的方法仅在 POST 请求时调用。当您只是正常查看页面时,模板会正常呈现,但由于您只是在 POST 请求中将数据添加到模板,因此模板不会收到 form。正常加载 View 时的参数(因此默认为 None )。

根据 TemplateView documentation ,您可以像这样添加上下文:

class HomePageView(TemplateView):

    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        # Get the allocation plans from database. Limit to last 10. Adjust to your own needs
        context['plans'] = AllocationPlan.objects.all()[:10]
        context['form'] = AllocationPlanForm()
        return context

    def post(self, request, **kwargs):
        form = AllocationPlanForm(request.POST)
        if form.is_valid():
            form.save()
        # Handle rest of request here (for example, return the updated page).

如您所见,无需检查 request.method == 'POST' 是否为在你的post方法,因为 Django 仅在 POST 上调用此方法要求。另见 dispatch in the docs

要呈现数据库中的数据,您现在可以在模板中以 plans 访问它们:

{% for plan in plans %}
{{ plan.name }}
{{ plan.item }}
{% endfor %}

在您的 HTML 中,还有 no need to manually create the form content :

<form method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

这将自动创建表单所需的 HTML。

关于python - 在 Django 中显示来自数据库的动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541363/

相关文章:

python - 过滤多维数组

python - 无法使用 Q-Learning 和函数逼近来学习 MountainCar

javascript - knockout : click other place of the page and hide the element

python - 如何编写动态Django模型?

python - 报告长期运行的 Celery 任务的结果

python - 将分隔的字符串/单元格值拆分为多行

javascript - 使用plotly.js 从 JSON 构建绘图

javascript - 防止导航栏元素折叠

jQuery 隐藏了所有的 <li> 标签

mysql - 通过 SSH 在 AWS RDS MySQL 数据库实例上执行查询