Home > OS >  How can I get cleaned_data from html form?
How can I get cleaned_data from html form?

Time:08-21

I have django app with class based view and form written in html:

<form method="post" action="{% url 'personal-account' %}">
            {% csrf_token %}
            <div >
              <div >
                <input type="text" placeholder="First name"  name="first_name" size="1" value="{{ data.first_name }}">
                <input type="text" placeholder="Last Name"  name="last_name" size="1" value="{{ data.last_name }}">
              </div>
              <div >
                <input type="text" placeholder="Username"  name="username" size="1" value="{{ data.username }}">
                <input type="text" placeholder="Email"  name="email" size="1" value="{{ data.email }}">
              </div>
              <div >
                <input type="password" placeholder="Password"  name="password" size="1" value="{{ data.password }}">
                <input type="password" placeholder="Confirm"  name="confirm_password" size="1"  value="{{ data.confirm_password }}">
              </div>
              <div >
                <button type="submit" >Submit</button>
              </div>
            </div>
          </form>

View

class PersonalSignup(View):
    def post(self, request):
        
        return render(request, 'authentication/personal_signup.html')
    def get(self, request):
        return render(request, 'authentication/personal_signup.html')

Now I want to get all values from inputs(first_name, last_name...) with cleaned_data.

CodePudding user response:

First, you need to create a form in forms.py. like this:

class PersonalSignupForm(forms.Form):
    first_name=forms.CharField(max_length=255)
    last_name=forms.CharField(max_length=255)
    username=forms.CharField(max_length=255)
    password=forms.CharField(max_length=255)
    confirm_password=forms.CharField(max_length=255)

And then in viwe do like this:

from .forms impory PersonalSignupForm

class PersonalSignup(View):

     def get(self, request):
         form=PersonalSignupForm()
             return render(request, 'authentication/personal_signup.html',context={'form':form})

     def post(self, request):
        form=PersonalSignupForm(request.POST)
        if form.is_valid():
           first_name=form.cleaned_data.get('first_name')
           last_name=form.cleaned_data.get('last_name')
           username=form.cleaned_data.get('username')
           password=form.cleaned_data.get('password')
           return render(request, 'authentication/personal_signup.html')

CodePudding user response:

In your views, you can grab the information from the request.POST(returns a dictionary), like this:

if request.method == 'POST':
    first_name = request.POST['first_name']
  • Related