【问题标题】:Handling forms from class based view从基于类的视图处理表单
【发布时间】:2022-01-10 09:41:40
【问题描述】:

您好,如何将表单从基于类的视图传递到模板?在 HTML 中,一切都是继承的,我可以在块内容中渲染元素,但我不能渲染表单。这是我的代码。 :

views.py:

class Signup(TemplateView):
   model =  Profile
   template_name = 'home/sign-up.html'
   form_class = UserCreationForm()
   def get_context_data(self, **kwargs):
      context = super().get_context_data(**kwargs)
      context['form'] = UserCreationForm

HTML:

{% extends "home/todo.html" %}
{% block content %}
<form method="POST">
    {{form}}
</form>
    
{% endblock content %}

【问题讨论】:

    标签: python html django


    【解决方案1】:

    试试这个

    context['form'] = self.form_class
    

    应该工作

    但是对于创建用户,你最好使用CreateView而不是TemplateView

    from django.views.generic import CreateView
    
    class Signup(CreateView):
        template_name = 'home/sign-up.html'
        form_class = UserCreationForm()
    

    【讨论】:

    • 它在 CreateView 中有效,但在 TemplateView 中无效。感谢您的帮助
    猜你喜欢
    • 2016-12-05
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2020-12-21
    • 2012-03-29
    • 2021-07-17
    相关资源
    最近更新 更多