For example, you might have a contact form that will trigger sending an email. Char Field(max_length=100, label='Your Name') email = forms. Char Field(max_length=10000) # Arguments on every field: """ required (default=True) By default, all of the fields in your form are required.
Although the form is always empty from a user data perspective, the form can contain data from as part of its initialization sequence(e.g. To perform this kind of Django form initialization you have three options. Textarea) def __init__(self, *args, **kwargs): # Get 'initial' argument if any initial_arguments = kwargs.get('initial', None) updated_initial = if initial_arguments: # We have initial arguments, fetch 'user' placeholder variable if any user = initial_arguments.get('user', None) # Now update the form's initial values if user if user: updated_initial['name'] = getattr(user, 'first_name', None) updated_initial['email'] = getattr(user, 'email', None) # You can also initialize form fields with hardcoded values # or perform complex DB logic here to then perform initialization updated_initial['comment'] = 'Please provide a comment' # Finally update the kwargs initial reference kwargs.update(initial=updated_initial) super(Contact Form, self).__init__(*args, **kwargs) def contact(request): .... else: # GET, generate blank form form = Contact Form(initial=) # Form is now initialized via the form's __init__ method # Reference form instance (bound/unbound) is sent to template for rendering return render(request,'about/contact.html',) These last values are perfectly valid and in other circumstances would be ignored because the Django form does indeed have no fields by these names, but since we'll be manipulating the guts of form initialization process in the method, we can access these placeholder values for indirect initialization purposes.
In some cases, those HTML inputs may involve Java Script and CSS code (a custom date picker, or an auto-complete field for example).
The thing is, Django does very well the server-side part.
POST) # Reference is now a bound instance with user data sent in POST # process data, insert into DB, generate email, redirect to a new URL,etc else: # GET, generate blank form form = Contact Form() # Reference is now an unbound (empty) form # Reference form instance (bound/unbound) is sent to template for rendering return render(request,'about/contact.html',) instance in listing 6-8.
Textarea) def contact(request): if request.method == 'POST': # POST, generate form with data from the request form = Contact Form(request.