Dmitry Belaventsev
Dmitry Belaventsev

Reputation: 6657

Cleaned value of the field not shown in the form's input (only old value is displayed)

I have the following form:

class SourceForm(forms.ModelForm):
    class Meta:
        model = Source
        widgets = {
            'category_re': forms.TextInput(),
            'thumb_re': forms.TextInput(),
            'movie_re': forms.TextInput()
        }

    def clean_url(self):
        data = self.cleaned_data['url']
        return helpers.url_fix(data)

and the following view:

def source_form(request, id):
    source = get_object_or_404(Source, pk=id)
    form = SourceForm(request.POST or None, instance=source)

    if form.is_valid():
        form.save()

    return render_to_response('source/form.html', {'form': form, 'source': source},
        context_instance=RequestContext(request))

And I have the problem. Cleaned value of url field don't shown in the form. I see only old, not modified value, but then I try to add {{ form.cleaned_data }} in the template - it shows right value. Why it happened so? How can I fix it?

TIA!

Upvotes: 0

Views: 69

Answers (1)

mVChr
mVChr

Reputation: 50205

It's because your form is using the request.POST data and not the cleaned_data. Try reassigning your form variable after your save():

def source_form(request, id):
    source = get_object_or_404(Source, pk=id)
    form = SourceForm(request.POST or None, instance=source)

    if form.is_valid():
        source = form.save()
        form = SourceForm(instance=source)

    return render_to_response('source/form.html', {'form': form, 'source': source},
        context_instance=RequestContext(request))

Upvotes: 2

Related Questions