How to get value from form field in django framework?


How do I get values from form fields in the django framework? I want to do this in views, not in templates...

9/21/2018 4:20:59 PM

Accepted Answer

Using a form in a view pretty much explains it.

The standard pattern for processing a form in a view looks like this:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            print form.cleaned_data['my_form_field_name']

            return HttpResponseRedirect('/thanks/') # Redirect after POST
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
1/16/2011 3:44:23 PM

Take your pick:

def my_view(request):

    if request.method == 'POST':
        print request.POST.get('my_field')

        form = MyForm(request.POST)

        print form['my_field'].value()

        if form.is_valid():

            print form.cleaned_data['my_field']
            print form.instance.my_field

            print  # now this one can access id/pk

Note: the field is accessed as soon as it's available.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow