【问题标题】:Django Forms Not Rendering In HTMLDjango 表单不在 HTML 中呈现
【发布时间】:2019-09-02 09:30:50
【问题描述】:

我发现很难在 html 模板中显示 django 表单。 django 表单无法在模板中呈现。我正在使用类基础视图,下面是我的 views.py、urls.py、models.py 和 html 模板的代码:

views.py

class Home(CreateView):
     models = Blog
     queryset = Blog.objects.filter(publish = True)
     template_name='index.html'
     fields = '__all__'

urls.py

urlpatterns=[
    path('', Home.as_view(), name='index'),
]

models.py

Continent = (
     ('select continent', 'Select Continent'),
     ('africa', 'Africa'),
     ('europe', 'Europe'),
     ('north america', 'North America'),
     ('south america', 'South America'),
     ('asia', 'Asia'),
     ('australia', 'Australia'),
     ('Antarctica', 'Antarctica'),   
)

 class Blog(models.Model):
     name= models.CharField(max_length = 200)
     company= models.CharField(max_length = 200)
     post = models.CharField(max_length = 200)
     author= models.ForeignKey('auth.User', on_delete = models.PROTECT)
     mantra= models.CharField(max_length = 200, help_text='make it short 
                              and precise')
     continent = models.CharField(choices= Continent, default= 'select 
                               continent', 
                               help_text='help us to know you even more', 
                               max_length=50)
     publish = models.BooleanField(default =True)


    def __str__(self):
        return self.name

    def get_absolute_url(self): # new
       return reverse('post_detail')

index.html

{% extends "base.html" %}
{% load static %}

{% block content %}
 <body class="loading">
    <div id="wrapper">
        <div id="bg"></div>
        <div id="overlay"></div>
        <div id="main">

             {{form.as_p}}

             {% include "partials/_footer.html" %}
        </div>
      </div>
  </body>
{% endblock %}

我们将不胜感激。谢谢。

【问题讨论】:

  • 这是model = Blog 不是models = Blog
  • @dirkgroten:我有点惊讶 Django 没有从queryset 派生模型。因为可以使用some_queryset.model 访问它。
  • @WillemVanOnsem 是真的。刚刚也意识到了这一点。它应该,因为model is None 能够从queryset 获得它。所以问题出在其他地方。
  • 您能在浏览器中查看您网页的源代码吗?你真的看到&lt;div id="main"&gt;了吗?
  • 感谢大家的及时回复。我确实按照 dirkgroten 的建议将模型更改为模型;但问题仍然相同。我也可以在我的浏览器源代码中看到

标签: django django-forms


【解决方案1】:

您需要将 csrf 令牌添加到您的模板中

{% extends "base.html" %}
{% load static %}

{% block content %}
 <body class="loading">
    <div id="wrapper">
        <div id="bg"></div>
        <div id="overlay"></div>
        <div id="main">
             {% csrf_token %}
             {{form.as_p}}

             {% include "partials/_footer.html" %}
        </div>
      </div>
  </body>
{% endblock %}

【讨论】:

  • 感谢@Vikrant_Chauhan 的留言。我按说添加了它,但仍然是相同的请求。谢谢。
  • 它没有显示错误。 django 表单不仅会在模板中呈现。但我可以在浏览器源代码中看到表单。这是它的快照:filesharing24.com/d/DmQ
  • 链接处的文件打不开,你有没有为模型制作modelform? forms.py 在哪里?
  • 深深感谢@Vikrant Chauhan。该问题现已解决。 CSS 类是罪魁祸首。谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2018-08-31
  • 2019-04-25
  • 1970-01-01
  • 2019-11-17
  • 2012-04-01
  • 1970-01-01
相关资源
最近更新 更多