Django modal Bootstrap 表单的错误处理

Posted

技术标签:

【中文标题】Django modal Bootstrap 表单的错误处理【英文标题】:Error handling of Django modal Bootstrap form 【发布时间】:2016-06-08 16:08:32 【问题描述】:

我在 Django 中创建了两种表单:一种用于注册新用户,另一种用于登录用户。 它们工作正常,但我想实现一个 Ajax 控件:如果出现错误,页面不会重新加载,而是模式窗口停留在那里并显示错误。

这是我的观点

def register(request):
    registered = False

    if request.method == 'POST':
        user_form = CustomUserCreationForm(request.POST)

        if user_form.is_valid():
            user = user_form.save()

            registered = True

            return render(request, 'blog/registered.html')

        else:
            print user_form.errors
    else:
        user_form = CustomUserCreationForm()

    return render(request, 'blog/post_list.html', 'user_form': user_form)

def login(request):
    if request.method == 'POST':
        login_form = CustomLoginForm(request.POST)
        email = request.POST.get('email')
        password = request.POST.get('password2')

        user = authenticate(email=email, password=password)

        if user:
            if user.is_active:
                auth_login(request, user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse("Your Pin a Voyage account is disabled.")
        else:
            print "Invalid login details: 0, 1".format(email, password)
            return HttpResponse("Invalid login details supplied. Get back to the <a href=\"/\">homepage</a>.")
    else:
        login_form = CustomLoginForm()

    return render(request, 'blog/post_list.html', 'login_form': login_form)

表格

@parsleyfy
class CustomUserCreationForm(UserCreationForm):
    """
    A form that creates a user, with no privileges, from the given email and password.
    """

    email = forms.EmailField(label='', required=True, widget = forms.TextInput(
        attrs = 
            'placeholder': 'E-Mail',
            'class': 'form-control'
        
    ))

    first_name = forms.CharField(label='', required=True, widget = forms.TextInput(
        attrs = 
            'placeholder': 'First name',
            'class': 'form-control'
        
    ))

    second_name = forms.CharField(label='', required=True, widget = forms.TextInput(
        attrs = 
            'placeholder': 'Last name',
            'class': 'form-control'
        
    ))

    password1 = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs = 
            'placeholder': 'Password',
            'class': 'form-control'
        ))

    password2 = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs = 
            'placeholder': 'Password confirmation (enter the same password as above, for verification)',
            'equalto': "new_password1",
            'error-message': "Your passwords do not match.",
            'class': 'form-control'
        ))

    class Meta:
        model = CustomUser
        fields = ("email", "first_name", "second_name",)

    def save(self, commit=True):
        user = super(CustomUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password2'])
        if commit:
            user.save()
        return user


@parsleyfy
class CustomLoginForm(forms.ModelForm):
    """
    A form that login a user.
    """

    email = forms.EmailField(label='', required=True, widget = forms.TextInput(
        attrs = 
            'placeholder': 'E-Mail',
            'class': 'form-control'
        
    ))

    password2 = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs = 
            'placeholder': 'Password',
            'class': 'form-control'
        ))

    class Meta:
        model = CustomUser
        fields = ('email',)

这是模板

    <!-- Trigger the modal with a button -->
    <a id="login_btn" class="btn_sub_log top-menu"><span class="glyphicon glyphicon-lock"></span></a>
    <!-- Modal -->
    <div class="modal fade" id="login_modal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3 class="modal-title" id="sign-up">Login with Pin a Voyage</h3>
                </div>
            <div class="modal-body">
                <form data-parsley-validate method="post" action="/login/" enctype="multipart/form-data">

                    % csrf_token %
                    % if next %
                        <input type="hidden" name="next" value=" next " />
                    % endif %

                     login_form.as_p 

                    <input type="submit" class="btn btn-info submit" name="submit" value="Login" />
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
            </div>
        </div>
    </div>

    <!-- Trigger the modal with a button -->
    <a id="subscribe_btn" class="btn_sub_log"><h2 class="top-menu sign-up">Sign up!</h2></a>
    <!-- Modal -->
    <div class="modal fade" id="subscribe_modal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3 class="modal-title" id="sign-up">Register with Pin a Voyage</h3>
                </div>
            <div class="modal-body">
                <form data-parsley-validate id="user_form" method="post" action="/register/" enctype="multipart/form-data">

                    % csrf_token %

                     user_form.as_p 

                    <input type="submit" class="btn btn-info submit" name="submit" value="Register" />
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
            </div>
        </div>
    </div>

这样做的最佳做法是什么?

【问题讨论】:

【参考方案1】:

为此,您需要使用 javascript 在表单发送到服务器之前对其进行验证。我推荐Parsley 库;您可以使用widget attrs 将正确的类和属性添加到表单中,然后包含欧芹脚本,这是我认为根据您当前的代码将验证添加到前端的最简单方法。

【讨论】:

以上是关于Django modal Bootstrap 表单的错误处理的主要内容,如果未能解决你的问题,请参考以下文章

一个Django插件,用于在Bootstrap模式中创建AJAX驱动的表单。

python测试开发django-187.Bootstrap模态框(modal)如何在关闭时触发事件

bootstrap种modal怎么关闭

html BootStrap Modal对象中的MVC表单。

python测试开发django-123.bootstrap模态框(modal)垂直居中显示

将 Django 和 Bootstrap 5 Modal 与 Ajax 结合使用