1、新建一个APP,accounts

python manage.py startapp accounts

2、修改文件settings.py,添加配置 ‘accounts.apps.AccountsConfig’,

INSTALLED_APPS = [
 
    'accounts.apps.AccountsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

3、新建2个页面,login.html,register.html

4、配置URL

urls.py:

from django.conf.urls import url
from . import views
from django.urls import path

urlpatterns = [
    path('login/',views.login,name='login'),
    path('register/',views.register,name='register'),
    path('logout/',views.logout,name='logout'),
    path('dashboard/',views.dashboard,name='dashboard'),
];

5、注册页面和登陆页面需要写一下HTML

登陆页面 login.html:

<section id="login" class="bg-light py-5">
    <div class="container">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="card">
            <div class="card-header  text-white">
              <h4>
                <i class="fas fa-sign-in-alt"></i> 登录</h4>
            </div>
            <div class="card-body">
              <!-- Alerts -->
              {% include 'partials/_alerts.html' %}
                <form action="{% url 'login' %}" method="POST">
                  {% csrf_token %}
                <div class="form-group">
                  <label for="username">登录名</label>
                  <input type="text" name="username" class="form-control" required>
                </div>

                <div class="form-group">
                  <label for="password2">密码</label>
                  <input type="password" name="password" class="form-control" required>
                </div>

                <input type="submit" value="Login" class="btn btn-secondary btn-block">
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>

注册页面 register.html

<section id="register" class="bg-light py-5">
    <div class="container">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <div class="card">
            <div class="card-header  text-white">
              <h4>
                <i class="fas fa-user-plus"></i> 用户注册</h4>
            </div>
            <div class="card-body">
              <!-- Alerts -->
              {% include 'partials/_alerts.html' %}

              <form action="{% url 'register' %}" method="POST">
                  {% csrf_token %}
                  <div class="form-group">
                      <label for="first_name">昵称</label>
                      <input type="text" name="first_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                      <label for="last_name">姓氏</label>
                      <input type="text" name="last_name" class="form-control" required>
                    </div>
                <div class="form-group">
                  <label for="username">登录账号</label>
                  <input type="text" name="username" class="form-control" required>
                </div>
                <div class="form-group">
                  <label for="email">Email</label>
                  <input type="email" name="email" class="form-control" required>
                </div>
                <div class="form-group">
                  <label for="password2">密码</label>
                  <input type="password" name="password" class="form-control" required>
                </div>
                <div class="form-group">
                  <label for="password">再次确认密码</label>
                  <input type="password" name="password2" class="form-control" required>
                </div>
                <input type="submit" value="Register" class="btn btn-secondary btn-block">
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>

6、修改views.py

导入User,User是django自带的用户注册的类

from django.contrib.auth.models import User

注册函数register:

def register(request):
  if request.method == 'POST':
    # Get form values
    first_name = request.POST['first_name']
    last_name = request.POST['last_name']
    username = request.POST['username']
    email = request.POST['email']
    password = request.POST['password']
    password2 = request.POST['password2']

    # Check if passwords match
    if password == password2:
      # Check username
      if User.objects.filter(username=username).exists():
        messages.error(request, '已注册')
        return redirect('register')
      else:
        if User.objects.filter(email=email).exists():
          messages.error(request, 'email已注册')
          return redirect('register')
        else:
          # Looks good
          user = User.objects.create_user(username=username, password=password,email=email, first_name=first_name, last_name=last_name)
          # Login after register
          # auth.login(request, user)
          # messages.success(request, 'You are now logged in')
          # return redirect('index')
          user.save()
          messages.success(request, '注册成功,请登录')
          return redirect('login')
    else:
      messages.error(request, '密码错误')
      return redirect('register')
  else:
    return render(request, 'accounts/register.html')

注册成功后跳转到登陆页面

login函数:

def login(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)
      messages.success(request, '已登录')
      return redirect('dashboard')
    else:
      messages.error(request, '密码错误')
      return redirect('login')
  else:
    return render(request, 'accounts/login.html')

退出登陆,logout函数是最简单的。

logout函数:

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        messages.success(request, '已退出')
        return redirect('login')


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!



2 条评论

如何在django admin 的user中添加额外属性,扩容用户信息 - Christopher · 2019年12月30日 下午7:30

[…] django如何注册用户 […]

django 如何利用forms更新用户信息 - Christopher · 2019年12月30日 下午8:52

[…] 怎么注册、登陆用户 […]

发表评论

电子邮件地址不会被公开。 必填项已用*标注