【问题标题】:Where does the value 'form' in 'form.as_p' in Django template come from?Django模板中'form.as_p'中的值'form'从何而来?
【发布时间】:2020-07-24 07:20:21
【问题描述】:

我知道之前有人问过这个问题,但接受的答案并没有真正回答这个问题: where `form.as_p`in django templates come from?

在 Django 文档中:

示例 myapp/views.py:

from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

myapp/author_form.html 示例:

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

问题是,模板从哪里获取“表单”上下文,因为我们没有在 AuthorCreate 类中显式定义 render() 函数?谢谢。

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    我找到了答案。

    CreateView 继承 ProcessFormView 类的 get 方法和 FormMixin 类的 get_context_data 方法。

    正如您在代码中看到的,get 方法返回一个调用get_context_data 的表达式。

    class ProcessFormView(View):
        """Render a form on GET and processes it on POST."""
        def get(self, request, *args, **kwargs):
            """Handle GET requests: instantiate a blank version of the form."""
            return self.render_to_response(self.get_context_data())
    

    如果**kwargs 中尚不存在form,则get_context_data 会添加一个带有键form 的关键字参数:

    class FormMixin(ContextMixin):
    ...
        def get_context_data(self, **kwargs):
            """Insert the form into the context dict."""
            if 'form' not in kwargs:
                kwargs['form'] = self.get_form()
            return super().get_context_data(**kwargs)
    

    所以CreateView 呈现一个带有上下文的响应,该上下文具有一个“表单”键和一个指向ModelForm 的值。

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2019-07-03
      • 2017-08-18
      • 2020-06-12
      • 2011-12-07
      • 1970-01-01
      • 2011-09-21
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多