简体   繁体   English

Django默认上下文变量

[英]django default context variable

I'm new to Django web dev, managed to setup a toy project following this tutorial . 我是Django Web开发人员的新手,根据本教程设法建立了一个玩具项目。

However I found the Django official documentation as well as this tutorial are quite confusing, hard for me to follow, especially the template context variables . 但是,我发现Django官方文档以及本教程非常混乱,我很难遵循,尤其是模板上下文变量

For example, in xxapp/views.py we defined a few views as follows, 例如,在xxapp/views.py我们定义了以下几个视图,

from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy

from catalog.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = '__all__'
    initial = {'date_of_death': '05/01/2018'}

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('authors')

Then in templates, we have this 然后在模板中,我们有

{% extends "base_generic.html" %}

{% block content %}
  <form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }} <!-- WHERE IS THIS "FORM" FROM? -->
    </table>
    <input type="submit" value="Submit">
  </form>
{% endblock %}

I understand this template file, except for one thing, where is the form.as_table from, and what is it?? 我了解此模板文件,除了一件事之外, form.as_table来源是什么,它是什么?

I'm aware that, if we use some built-in class views or models, we might have some context data for free, but where do I lookup them, I searched on Django but found nothing. 我知道,如果我们使用一些内置的类视图或模型,则可能会免费获得一些上下文数据,但是在哪里查找它们,我在Django上进行了搜索,但一无所获。

"form" is a variable you need to pass from your view to your template. “ form”是您需要从视图传递到模板的变量。

You should create a forms.py file to set up all of your forms. 您应该创建一个forms.py文件来设置所有表单。

In this file you would create a simple form like so: 在此文件中,您将创建一个简单的表单,如下所示:

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

And then in your view you should import the form and then set the "form" variable as such: 然后在您看来,您应该导入表单,然后将“ form”变量设置为:

form = NameForm()

Or if you have posted data: 或者,如果您已发布数据:

form = NameForm(request.POST)

So once you have passed this variable to the template, you can either call the entire form as you have using "form.as_table" 因此,一旦将此变量传递给模板,就可以像使用“ form.as_table”一样调用整个表单。

Or you can call individual form fields, such as: 或者,您可以调用单个表单字段,例如:

{{ form.your_name.label }}
{{ form.your_name }}
{{ form.your_name.errors }}

See this help doc on the Django site for more information: https://docs.djangoproject.com/en/2.1/topics/forms/#the-form-class 有关更多信息,请参见Django网站上的此帮助文档: https : //docs.djangoproject.com/en/2.1/topics/forms/#the-form-class

You're using generic class-based views, which come with a lot of functionality baked in. The best source to look them up is this one . 您使用的是基于类的通用视图,其中包含许多功能。查找它们的最佳来源是视图。

If you look at the CreateView for example (Edit -> CreateView), you'll see that the get() method, which is the first method called when you just fetch the page using GET, just calls render_to_response() with context data fetched from get_context_data() . 如果以CreateView为例(编辑-> CreateView),您会看到get()方法(这是您仅使用GET来获取页面时调用的第一个方法render_to_response() ,只是调用了render_to_response()并获取了上下文数据来自get_context_data()

And inside get_context_data() , we add a form context variable to the context, which is assigned to get_form() . get_context_data()内部,我们向上下文添加一个form上下文变量,该变量分配给get_form() etc... 等等...

Same with the post() method, where first the form is fetched, checked for validity and if not valid, the form_invalid() method renders the template with the form in its context. post()方法相同,在post()方法中,首先获取form ,检查其有效性,如果无效,则form_invalid()方法在其上下文中呈现带有form的模板。

You can follow the same with UpdateView and DeleteView , they are very similar. 您可以使用UpdateViewDeleteView进行相同UpdateView ,它们非常相似。 Most of the form handling code actually comes from the FormMixin class. 实际上,大多数表单处理代码都来自FormMixin类。

When creating your own views, subclassing Django's generic views, you'll find that sometimes you can't use a view, but you can use the mixins (eg FormMixin or ModelFormMixin ). 创建自己的视图并继承Django的通用视图时,您会发现有时无法使用视图,但可以使用混合包(例如FormMixinModelFormMixin )。

So form in your template is the ModelForm for the Author model you specified in your generic views. 因此,模板中的form就是您在常规视图中指定的Author模型的ModelForm The view is auto-generating that form from the model using a modelform_factory , with the fields you specified with fields . 该视图正在使用modelform_factory从模型中自动生成该表单,并使用fields指定了fields Since it's added as 'form' key to the context used to render the template, you can access it with {{ form }} . 由于已将其作为'form'键添加到用于渲染模板的上下文中,因此您可以使用{{ form }}访问它。 {{ form.as_table }} will render the HTML for this form in a <table> , as described here . {{ form.as_table }}将呈现在这种形式的HTML <table>如所描述这里

If you don't like how the form looks like and want to customise some of the fields (and can't do that by just changing the template), you would need to create your own form, tell your view about it by setting the form_class attribute and removing the fields attribute (the fields would be specified in your form), as described by @drew in his response. 如果您不喜欢表单的外观并想要自定义某些字段(并且不能仅通过更改模板来做到这一点),则需要创建自己的表单,并通过设置form_class属性并删除fields属性(字段将在您的表单中指定),如@drew在其响应中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM