【问题标题】:Display dynamic data from database in Django在 Django 中显示来自数据库的动态数据
【发布时间】:2018-05-12 11:42:39
【问题描述】:

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

models.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)

views.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() })

forms.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

【问题讨论】:

    标签: python html django postgresql


    【解决方案1】:

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

    此外,您似乎错误地使用了TemplateView。您视图中的 post 方法仅在 POST 请求时调用。当你只是正常查看页面时,模板是正常渲染的,但是由于你只是在POST请求中将数据添加到模板中,所以在正常加载视图时,模板没有收到form参数(因此默认为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).
    

    如你所见,没有必要在你的post方法中检查request.method == '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。

    【讨论】:

    • @Randyr 说“在这里处理其余的请求...”通常会重定向到同一个视图(因此处理了 get 请求):return redirect(reverse('url_pattern_name'))
    猜你喜欢
    • 2016-08-21
    • 2018-06-06
    • 2018-02-08
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2016-01-17
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多