简体   繁体   English

在使用上下文处理器渲染之前,Django 表单无效

[英]Django form invalid before rendering with a context processor

I have a slight issue with my form using Django.我对使用 Django 的表单有一点小问题。 On my website I have a 'settings' box on every page (rendered with an 'include') in base.html - each settings box has a form which I am rendering with a 'context processor' however when rendering the form in the template nothing shows.在我的网站上,我在 base.html 中的每个页面上都有一个“设置”框(使用“包含”渲染) - 每个设置框都有一个表单,我使用“上下文处理器”渲染该表单,但是在模板中渲染表单时什么都没有显示。 Rendering with {{global_rebase_form.get_context}} I get the following message:使用{{global_rebase_form.get_context}}渲染我收到以下消息:

{'form': <global_rebase_form bound=False, valid=False, fields=()>, 'fields': [], 'hidden_fields': [], 'errors': []}

Suggesting it is invalid?提示无效? My code is as follows我的代码如下

Settings.py设置.py

'OPTIONS': {
            'context_processors': [
                'apps.home.views.global_rebase_context',
                 ...
            ],

context processor:上下文处理器:

def global_rebase_context(request):
    form = global_rebase_form()
    return {
        'global_rebase_form': form
    }

template模板

<form method="POST" name="time" id="rebase-form">
{% csrf_token %}
{{global_rebase_form.as_p}}
</form>

form.py表格.py

class global_rebase_form(forms.Form):
class Meta:
    model = profile
    fields = ['location_rebase', 'time_rebase']

This means that if you would use form.is_valid() it will return False , this is because the form is not bounded .这意味着如果您使用form.is_valid()它将返回False ,这是因为表单是无的。 Bounded means that you passed data to it.有界意味着您将数据传递给它。 So a form:所以一个表格:

global_rebase_form(request.POST, request.FILES)  # bounded

is bounded, whereas a form without data:是有界的,而没有数据的形式:

global_rebase_form()  # not bounded and thus not valid

is not bounded and therefore not valid.是无界的,因此无效。 But here you each time construct an empty form.但是在这里你每次都构造一个表单。 It is only if the user submits data, that you will construct a new form object with the data, and then validate it.只有当用户提交数据时,您才会用数据构造一个新的表单对象,然后对其进行验证。

Hence this is not a problem .因此这不是问题

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

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