[Solved]-How to return the result on same page in django?

24๐Ÿ‘

โœ…

Use return redirect(request.META['HTTP_REFERER']) to redirect to previous url.

๐Ÿ‘คGeo Jacob

1๐Ÿ‘

I think you are looking for user login functionality, you can reffer django user login here And also use django Message framework to display 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('/')
๐Ÿ‘คGeo Jacob

1๐Ÿ‘

You can make use of Django messages.
visit https://docs.djangoproject.com/en/2.1/ref/contrib/messages/
I have given an example of login functionality.

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

In 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>

Hope this can help you.

๐Ÿ‘คpramod jaiswal

0๐Ÿ‘

Here is a simple method you can use:

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

In index.html You can view error message in jinja template

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

   <input type="email">
   <input type="password">
  </body>
</html>
๐Ÿ‘คAbhijith

0๐Ÿ‘

urls.py of project

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

urls.py of accounts module

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>
๐Ÿ‘คsiddhartha jain

Leave a comment