django上下文处理器之messages处理器

django上下文处理器之messages处理器

实现效果:
django上下文处理器之messages处理器_第1张图片

1setting.py中导入messages处理器(默认导入)

'OPTIONS': {
     
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                # messages上下文处理器
                'django.contrib.messages.context_processors.messages',
                'front.context_processors.front_user'
            ],
        },

2.signin.html中设置错误提示框

<form action="" method="post">
        <table>
            <tbody>
                <tr>
                    <td>用户名:td>
                    <td><input type="text" name="username">td>
                tr>
                <tr>
                    <td>密码:td>
                    <td><input type="password" name="password">td>
                tr>
                <tr>
                    <td>td>
                    <td><input type="submit" value="登录">td>
                tr>
                <tr>
                    <td>td>
                    <td>
                        <ul>
                            {% for message in messages %}
                                <li>{
    { message }}li>
                            {% endfor %}
                            
                        ul>
                    td>
                tr>
            tbody>
        table>
    form>

3.views.py中调用messages传入错误信息

class SigninView(View):
    def get(self, request):
        return render(request, 'signin.html')

    def post(self, request):
        form = SigninForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = User.objects.filter(username=username, password=password).first()
            if user:
                request.session['user_id'] = user.id
                return redirect(reverse('index'))
            else:
                '''
                    调用messages上下文处理器向前端传递错误信息
                    参数:request,错误级别,错误信息
                '''
                #方法1
                # messages.add_message(request,messages.INFO,'用户名或密码错误!')
                #方法2
                messages.info(request,'用户名或密码错误!')

                return redirect(reverse('signin'))
        else:
            # errors = form.errors.get_json_data()
            errors = form.get_error()
            for err in errors:
                messages.info(request,err)
            return redirect(reverse('signin'))


你可能感兴趣的:(django上下文处理器之messages处理器)