如何在django中返回同一页面上的结果?

时间:2014-11-07 10:01:47

标签: django django-views django-templates

如何在django中的同一页面上获取特定查询的结果? 例如,如果我的“index.html”有一个包含两个字段的表单,一个用于用户名和密码。 在views.py中,我检查值是否与db中的字段匹配。 我想返回一个字符串“Login successfull”或“Login Failed”同一页面。 请为views.py和index.html建议必要的代码。 目前我检查值并呈现一个新页面。请建议如何在同一页面上返回它。 提前谢谢!

def index(request):
    return render(request, "index.html")
def stage2(request):
    if Verify.objects.filter(usr=request.POST['us'],password=request.POST['pass']) 
         request.session['usr']=request.POST['us']      
         a=request.session['usr']
         dict1={'u':a}          
         return render(request,"success.html",dict1)

     else:
         return render(request,"failed.html")

我想在同一页面上显示结果,即“index.html”

5 个答案:

答案 0 :(得分:9)

使用return redirect(request.META['HTTP_REFERER'])重定向到上一个网址。

答案 1 :(得分:1)

我认为您正在寻找用户登录功能,您可以使用django用户登录here并使用django Message框架来显示messages

from django.contrib.auth import authenticate, login
from django.shortcuts import redirect

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Return a 'disabled account' error message
            return redirect('/')
        else:
            # Return a 'disabled account' error message
            return redirect('/')
    else:
        # Return an 'invalid login' error message.
        return redirect('/')

答案 2 :(得分:1)

您可以使用Django消息。 造访https://docs.djangoproject.com/en/2.1/ref/contrib/messages/ 我以登录功能为例。

在views.py

class LoginView(View):
    def post(self, request,*args, **kwargs):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                messages.success(request, 'woahh!! logged in..')
                return redirect('home')
            else:
                return HttpResponse('please! verify your Email first')
        else:
            messages.error(request, 'username or password not correct')
            return redirect('login')

在templates / login.html

        <form method="post"v action="{% url 'login' %}">
           {% csrf_token %}
           <input type="text" name="username" placeholder="Username">
           <input type="password" name="password" placeholder="Password">

            {% for error in messages %}
            <p>{{ error }}</p><br>
            {% endfor %}
            <button type="submit" >Login</button>
        </form>

希望这可以为您提供帮助。

答案 3 :(得分:0)

这是您可以使用的简单方法:

def index(request):
    return render(request, "index.html")

def stage2(request):
    if Verify.objects.filter(usr=request.POST['us'],password=request.POST['pass']) 
         request.session['usr']=request.POST['us']      
         a=request.session['usr']
         dict1={'u':a}          
         return render(request,"success.html",dict1)

     else:
         error = "Username or Password is Incorrect"
         return render(request,"index.html",{'error':error})

#Instead of rendering failed.html you can load index.html and pass error message to html page

index.html 中,您可以在jinja模板中查看错误消息

<html>
  <body>
        {% if error %}
        {{ error }}
        {% endif %}

   <input type="email">
   <input type="password">
  </body>
</html>

答案 4 :(得分:0)

项目的urls.py

urlpatterns = [
    path('', include('accounts.urls')),
    path('admin/', admin.site.urls)
]

帐户模块的urls.py

urlpatterns = [
    path('', views.userlogin, name='home'),
    path('accounts/login', views.userlogin, name='login'),
    path('accounts/add', views.add, name='add')
               ]

views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.models import User, auth

def userlogin(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request, user)
            return render(request, 'home.html', {'name': username})
        else:
            messages.info(request, 'Invalid Credentials')
            # Going back to previous URL
            return redirect(request.META['HTTP_REFERER'])
    else:
        return render(request, 'login.html')

def add(request):
    n1 = int(request.POST["num1"])
    n2 = int(request.POST["num2"])
    res = n1 + n2
    return render(request, 'result.html', {'result': res})

master.html

<!doctype html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
</head>
<body bgcolor="#ff1493">
{% block content %}

{% endblock %}
</body>
</html>

home.html

{% extends 'master.html' %}

{% block content %}
<b> Hello {{name}} </b>
    <form action="add" method="post">
        {% csrf_token %}
        <table>
            <tr>
                <td>
                    Enter First Number :</td>
                <td>
                    <input type="number" name="num1">
                </td>
            </tr>
            <tr>
                <td>
                    Enter Second Number :
                </td>
                <td>
                    <input type="number" name="num2">
                </td>
            </tr>
            <tr>
                <td></td>
                <td> <input type="submit">  </td>
            </tr>

        </table>
    </form>
{% endblock %}

login.html

{% load static %}
<html>
<head>
    <title> Analytics-login </title>
    <link rel="stylesheet" type="text/css" href="{% static 'styles/style.css' %}">
    <script src="{% static 'js/jquery.min.js' %}" charset="utf-8"></script>
    <script type="text/javascript" src="{% static 'js/login.js' %}" charset="utf-8"></script>
</head>
    <body>
    <div class="login-box">
    <img src="{% static 'images/avatar.png'  %}" class="avatar">
        <h1>Login</h1>
        <div>
           {% if messages %}
                <ul class="messages">
                    {% for message in messages %}
                    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
                        {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
                        {{ message }}
                    </li>
                    {% endfor %}
                </ul>
           {% endif %}
        </div>
            <form action="accounts/login" method="post">
                {% csrf_token %}
                <div class="txtb">
                  <input type="text" name="username">
                  <span data-placeholder="Username" ></span>
                </div>
                <div class="txtb">
                    <input type="password" name="password">
                    <span data-placeholder="Password"></span>
                </div>
                <div >
                    <input type="submit" name="submit" value="Login">
                </div>
                <div class="bottom-text">
                    <a href="#" >Forget Password</a>
                    <a>|</a>
                    <a href="accounts/register" >Register</a>
                </div>
            </form>
        </div>
    </body>
</html>