Django form invalid before rendering with a context processor

Viewed 34

I have a slight issue with my form using 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. Rendering with {{global_rebase_form.get_context}} I get the following message:

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

Suggesting it is invalid? My code is as follows

Settings.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

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

This means that if you would use form.is_valid() it will return False, this is because the form is not bounded. 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.

Related