【问题标题】:Django Form, User input fields not rendering in templateDjango Form,用户输入字段未在模板中呈现
【发布时间】:2016-08-15 18:50:39
【问题描述】:

这里是 Django 新手,但我正在学习。

问题陈述

输入字段未在 html 模板中呈现。

在浏览器中输出

是的

|提交按钮 |

相关代码

forms.py
from django import forms
from django.db import models

class PostNotes(forms.Form):
    clientid = models.IntegerField()
    notetext = models.CharField(max_length=1000)

-

views.py
def post_form_notes(request):
    if request.method == 'GET':
        sawit = True
        form = PostNotes(initial={'notetext':'This is a sample note'})
    else:
        sawit = False
        pass
    return render(request, 'clientadmin/post_form_notes.html', {
        'form': form,
        'sawit': sawit,
    })

-

post_form_notes.html
{{ sawit }}
<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

已完成故障排除

  • 我已经撤回了相当多的代码(特别是如果我看到 POST) 来自浏览器的请求。不用找了。
  • 我还包含了一个变量,以确保我看到了 GET 请求,并且模板变量也正常工作。我得到 True 的输出。
  • 尽可能简化表单类。

【问题讨论】:

  • 马特,感谢您的回复,我认为您对正在发生的事情是正确的。我创建一个对象并将其传递给模板。我相信,|as_p 过滤器应该将其转换为对象中的代表对象。但是,由于它不起作用,我当然不确定这是正确的。遵循(或多或少)这个例子。 pythoncentral.io/how-to-use-python-django-forms

标签: python django forms


【解决方案1】:

我修改了 forms.py 以使用我已有的数据库模型。

forms.py:

from django.forms import ModelForm
from clientadmin.models import notes

class PostNotes(ModelForm):
    class Meta:
        model = notes
        fields = ['notedate', 'notetext']

我还修改了 views.py 以不设置初始值,因此该函数使用以下内容而不是所要求的内容。

models.py:

def post_form_notes(request):
    if request.method == 'GET':
        form = PostNotes()
    else:
        pass
    return render(request, 'clientadmin/post_form_notes.html', {
        'form': form,
    })

希望这可以帮助遇到与我相同问题的人......

更多信息请参考以下网址:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2017-05-10
    • 2016-12-04
    • 2019-10-27
    • 2016-06-02
    • 2020-06-15
    • 1970-01-01
    • 2012-04-28
    • 2011-12-30
    相关资源
    最近更新 更多