项目的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 %}
登录.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>