The goal of efficiency is more slack.

Friday, September 08, 2017

Django Forms

Some common uses of Django Forms.

f = Form(request.POST)
Instantiating a form with data a dictionary, e.g. from POST, creates a form populated with the field-name & field-value pairs in the dictionary.

f.errors
Returns dictionary of errors with keys being field names.

f['field_name'].errors
Returns list of errors for the specified field.

bound_form = self.form_class(request.POST)
return render(request, self.template_name, {'form': bound_form})
In a class-based view, renders a form with data bound from POST. bound_form.is_bound returns True.

model_instance = get_object_or_404(
            self.form_class.Meta.model, slug__iexact=slug)

bound_form = self.form_class(request.POST, instance=model_instance)
As with previous line, renders a form with data bound from POST but also associated with a model instance so that it can be modified with a subsequent:
model_instance = bound_form.save()

form_class(initial={'title': 'Something'})
Creates a form with a field filled in already. However, the form is not bound.

0 comments:

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages

Powered by Blogger.
Scroll To Top