How to get value from form field in django framework?

前端 未结 5 1874
一生所求
一生所求 2020-11-28 05:08

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

相关标签:
5条回答
  • 2020-11-28 05:47

    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")
    
    0 讨论(0)
  • 2020-11-28 05:51

    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.

    0 讨论(0)
  • 2020-11-28 05:52

    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.

    0 讨论(0)
  • 2020-11-28 05:58

    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,
        })
    
    0 讨论(0)
  • 2020-11-28 06:09

    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.

    0 讨论(0)
提交回复
热议问题