Opened 2 years ago

Closed 2 years ago

Last modified 2 years ago

#20703 closed Uncategorized (invalid)

Why django form.as_p call form.clean method when template renders?

Reported by: max.kharandziuk@… Owned by: nobody
Component: Template system Version: 1.5
Severity: Normal Keywords: as_p clean templates
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I have this sample of django code:

    def test_view(request):
        form = TestForm(
            request.POST or { 'text': 'some text'},
        data = {
            'form': form,
        print 'before rendering'
        return render(request, 'test.html', data)
    class TestForm(forms.Form):
        text = forms.CharField()
        def __init__(self, *args, **kwargs):
            print 'init'
            super(TestForm, self).__init__(*args, **kwargs)
        def clean(self):
            print 'in clean'

and this template:

    <form id='test-form' method="post" action="some url" enctype="multipart/form-data">
        {{ form.as_p }}
        <input type="submit" value="Save"/>

when i send get request to this file i have this output in console:

before rendering
in clean

when I write {{ form.text }} instead of {{ form.as_p }} I have only:

before rendering

It seams to me that as_p method calls clean() internally in process of rendering template.
Is it a bug or some undocumented feature?
Should this side effect avoided?

Version of Django==1.5.1

Change History (3)

comment:1 Changed 2 years ago by timo

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

I think you want to use initial={'text': 'some text'} when initializing TestForm rather than request.POST or {'text': 'some text'}, but this ticket tracker isn't the place to get help with this, thanks!

comment:2 Changed 2 years ago by max.kharandziuk@…

I don`t ask a help with this code I just mentioned that as_p method has some side effect(calls clean()) that not described in documentation. Maybe this effect is a bug

comment:3 Changed 2 years ago by timo

as_p will output error rows (if any) as well as non-field errors. Naturally, this requires calling clean. Since you are passing data to the form on GET, the form is validated and clean is called.

Note: See TracTickets for help on using tickets.
Back to Top