【问题标题】:Django form errors not showing when use id_<field-name>使用 id_<field-name> 时未显示 Django 表单错误
【发布时间】:2021-11-12 06:09:33
【问题描述】:

我是 Django 的初学者,我尝试使用for="id_&lt;field-name&gt;" 方法创建一个注册表单界面,但默认验证如“此字段是必需的”。或“此用户名已存在”未显示。我不想使用{{ form.as_p }},因为我想分隔该字段。如果我输入真实有效的东西,注册仍然有效。

HTML

<form method="POST" class="register-form" id="register-form" enctype="multipart/form-data" >
 {% csrf_token %}

  <div class="form-group">
       <label for="id_username"><i class="zmdi zmdi-account material-icons-name"></i></label>
       <input type="text" name="username" id="username" placeholder="Username"/>
  </div>
                   
  <div class="form-group">
       <label for="id_email"><i class="zmdi zmdi-email"></i></label>
       <input type="email" name="email" id="email" placeholder="Your Email" />

  </div>                  
   
  <div class="form-group">       
       <label for="id_password"><i class="zmdi zmdi-lock"></i></label>
       <input type="password" name="password" id="password" placeholder="Password"/>
  </div>
                    
  <div class="form-group">
       <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
       <label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in  <a href="#" class="term-service">Terms of service</a></label>
 </div>
 
 <div class="form-group form-button">
       <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/>
 </div>
 </form>

views.py

def register(request):

registered = False

if request.method == 'POST':

    # Get info from "both" forms
    # It appears as one form to the user on the .html page
    user_form = UserForm(data=request.POST)
    profile_form = UserProfileInfoForm(data=request.POST)

    # Check to see both forms are valid
    if user_form.is_valid() and profile_form.is_valid():

        # Save User Form to Database
        user = user_form.save()

        # Hash the password
        user.set_password(user.password)

        # Update with Hashed password
        user.save()

        # Now we deal with the extra info!

        # Can't commit yet because we still need to manipulate
        profile = profile_form.save(commit=False)

        # Set One to One relationship between
        # UserForm and UserProfileInfoForm
        profile.user = user

        # Check if they provided a profile picture
        if 'profile_pic' in request.FILES:
            print('found it')
            # If yes, then grab it from the POST form reply
            profile.profile_pic = request.FILES['profile_pic']

        # Now save model
        profile.save()


        # Registration Successful!
        registered = True

    else:
        # One of the forms was invalid if this else gets called.
        print(user_form.errors,profile_form.errors)

else:
    # Was not an HTTP post so we just render the forms as blank.
    user_form = UserForm()
    profile_form = UserProfileInfoForm()

# This is the render and context dictionary to feed
# back to the registration.html file page.
return render(request,'basic_app/registration.html',
                      {'user_form':user_form,
                       'profile_form':profile_form,
                       'registered':registered,
                       })

forms.py

from django import forms
from django.contrib.auth.models import User
from .models import UserProfileInfo, TeaProfileInfo

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
   
    class Meta():
    model = User
    fields = ('username','email','password')

My signup page interface

【问题讨论】:

标签: python django django-templates


【解决方案1】:

通过将以下内容添加到您的form.py 来快速验证您的表单

def clean(self):
    super(UserForm, self).clean()

    username = self.cleaned_data.get('username')
    email = self.cleaned_data.get('email')
    password = self.cleaned_data.get('password')

    if username == "" or email == "" or password  == "":
        raise forms.ValidationError(['This field is required.'])

在您的 HTML 中,确保在每个字段之后/之前添加以下内容

{{ username.errors }}
{{ email.errors }}
{{ password.errors }}

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 2013-09-27
    • 1970-01-01
    • 2017-09-03
    • 2018-03-07
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多