簡體   English   中英

如何從 html 表單中獲取cleaned_data?

[英]How can I get cleaned_data from html form?

我有 django 應用程序,該應用程序帶有基於 class 的視圖和用 html 編寫的表單:

<form method="post" action="{% url 'personal-account' %}">
            {% csrf_token %}
            <div class="page slide-page">
              <div class="field">
                <input type="text" placeholder="First name" class="input_1" name="first_name" size="1" value="{{ data.first_name }}">
                <input type="text" placeholder="Last Name" class="input_2" name="last_name" size="1" value="{{ data.last_name }}">
              </div>
              <div class="middle">
                <input type="text" placeholder="Username" class="input_3" name="username" size="1" value="{{ data.username }}">
                <input type="text" placeholder="Email" class="input_6" name="email" size="1" value="{{ data.email }}">
              </div>
              <div class="last">
                <input type="password" placeholder="Password" class="input_4" name="password" size="1" value="{{ data.password }}">
                <input type="password" placeholder="Confirm" class="input_5" name="confirm_password" size="1"  value="{{ data.confirm_password }}">
              </div>
              <div class="field">
                <button type="submit" class="submit-btn">Submit</button>
              </div>
            </div>
          </form>

看法

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')

現在我想用cleaned_data從輸入(first_name,last_name ...)中獲取所有值。

首先,您需要在 forms.py 中創建一個表單。 像這樣:

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)

然后在 viwe 中這樣做:

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')

在您的視圖中,您可以從 request.POST(返回字典)中獲取信息,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM