147

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

ajsmart
  • 193
  • 1
  • 11
kspacja
  • 4,648
  • 11
  • 38
  • 41

8 Answers8

161

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
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })
miku
  • 181,842
  • 47
  • 306
  • 310
100

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()
        print form.data['my_field']

        if form.is_valid():

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

            form.save()
            print form.instance.id  # now this one can access id/pk

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

laffuste
  • 16,287
  • 8
  • 84
  • 91
  • 8
    This answer best summarises all the options - accessing raw POST data, unvalidated form fields and finally validated form fields. – NullPumpkinException Jun 30 '17 at 04:12
  • 7
    Maybe I've just been looking at my screen too long today, but it took me an hour to find this very simple solution `form['my_field'].value()` for accessing form values on POST request. Some days :| – ionalchemist May 13 '19 at 23:07
32

You can do this after you validate your data.

if myform.is_valid():
  data = myform.cleaned_data
  field = data['field']

Also, read the django docs. They are perfect.

nerdherd
  • 2,508
  • 2
  • 24
  • 40
ikostia
  • 7,395
  • 6
  • 30
  • 39
  • 13
    what about b4 you clean your data? – Robert Johnstone Mar 10 '14 at 15:11
  • 2
    Before you clean your data all there is only request.POST that is stored with the form instance. Cleaning is what associates the POST data with the form fields. Before cleaning you would have to work with request.POST. – freb Aug 27 '14 at 22:33
  • Is it possible to get the formField's value if it's initial is set? – Fydo Oct 07 '14 at 15:37
15

To retrieve data from form which send post request you can do it like this

def login_view(request):
    if(request.POST):
        login_data = request.POST.dict()
        username = login_data.get("username")
        password = login_data.get("password")
        user_type = login_data.get("user_type")
        print(user_type, username, password)
        return HttpResponse("This is a post request")
    else:
        return render(request, "base.html")
ChandyShot
  • 177
  • 1
  • 3
12

I use django 1.7+ and python 2.7+, the solution above dose not work. And the input value in the form can be got use POST as below (use the same form above):

if form.is_valid():
  data = request.POST.get('my_form_field_name')
  print data

Hope this helps.

zhihong
  • 1,808
  • 2
  • 24
  • 34
  • more secure is to use it with default value e.g. "data = request.POST.get('my_form_field_name', None)", because if there isn't any 'my_form_field_name' in request, then you get a KeyError – noumen Jul 05 '22 at 14:33
  • @noumen, thanks for help to improve/complete the solution. – zhihong Jul 14 '22 at 13:22
4

It is easy if you are using django version 3.1 and above

def login_view(request):
    if(request.POST):
        yourForm= YourForm(request.POST)
        itemValue = yourForm['your_filed_name'].value()
        # Check if you get the value
        return HttpResponse(itemValue )
    else:
        return render(request, "base.html")
Bushra Mustofa
  • 1,075
  • 7
  • 12
  • If the method is "GET", is there a way to set the value of an attribute in yourForm['your_field_name'] 'min' to the value of a variable? I have a form that has a NumberInput widgets field, but I'm trying to set that in my views.py file. When I print the yourForm.fields['form_field'], I can only access the field as a class, where 'min' does not seem to be accessible. Here's what I see in the console: – JackJack Dec 14 '20 at 17:20
  • 1
    This is the best answer especially if you are using the default form sample from the documentation – Joshua Johns Apr 30 '21 at 09:32
1

Cleaned_data converts the submitted form into a dict where the keys represent the attribute name used in form and value is user submitted response. to access a particular value in the views we write:

formname.cleaned_data['fieldname']
Flair
  • 2,609
  • 1
  • 29
  • 41
Pooja
  • 21
  • 4
0

Incase of django viewsets or APIView you can simply get the request.data and if you're sure the data being passed to the view is always form data then

  1. copy the data e.g data = request.data.copy()
  2. form data is returned with key values in lists so data['key'][0] to get the first element of the list which is the value first value and most likely only value if they key only returns a single value of the key.

for example

class EquipmentView(APIView):


    def post(self, request: Request):
        data = request.data.copy()
        author = data.get('author')[0]
        
alvinMemphis
  • 185
  • 2
  • 14