首页 > 解决方案 > Django 和 Python 的新手,基于自定义类的视图——我这样做对吗?

问题描述

我正在尝试通过自学 Django(因为它本身就是一头野兽)和 Python(仅用于编码 <3)与 nginx、postgresql 和 gunicorn 相结合——我对 PHP 的经验有限。

经过短暂的努力,我设法让所有东西都启动并运行(足够的教程)。

基本上我现在正在做的是尝试自定义 Django 身份验证系统,特别是从登录部分开始并为用户添加“记住我”选项,我得到了一切以我喜欢的方式工作,但我想知道我是否是否以“正确”(或方便)的方式做所有事情?(我从自定义用户模型开始,所以你可能会遇到一些与此相关的点点滴滴。)所以我可以使用一些我可以做得更好或改进的指针。

在我的项目目录中:

设置.py

SESSION_EXPIRE_AT_BROWSER_CLOSE = True

我添加了上面的行,以便默认情况下创建的任何会话在浏览器关闭时过期(是的,这在 Chrome 中可能并不总是有效)。

在我的 APP 目录中进行用户身份验证:

表格.py

from django import forms
from django.contrib.auth.forms import AuthenticationForm

class CustomAuthenticationForm(AuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Username','required': True,'autofocus' : True}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True}))
    remember_me = forms.BooleanField(required=False)

如您所见,我正在使用引导类来设置输入字段的样式。

视图.py

from django.shortcuts import render

# Create your views here.

from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
from django.contrib.auth import login

from .forms import CustomAuthenticationForm

class Login(LoginView):

    authentication_form = CustomAuthenticationForm

    form_class = CustomAuthenticationForm

    template_name = 'login.html'

    def form_valid(self, form):

        remember_me = form.cleaned_data['remember_me']

        login(self.request, form.get_user())

        if remember_me:

            self.request.session.set_expiry(1209600)

        return super(LoginView, self).form_valid(form)

为了使“记住我”选项起作用,我试图读出已在表单中发布的模板的“记住我”复选框。根据是否设置,它将会话到期设置为两周。

这就是我的 urls.py 在我的“用户”应用程序中的样子:

网址.py

from django.urls import path
from . import views
from .forms import CustomAuthenticationForm

urlpatterns = [
    path('login/', views.Login.as_view(), name='login')
]

最丑陋和最少的 django/python 必须是我的模板(例如标签,因为我试图避免使用完整的“生成”形式)。我绝对确信这一点和 forms.py 可以改进很多。

两个模板:

base.html

<!doctype html>

<html lang="en">
  
  <head>

    <meta charset="utf-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

	{% block head %}

	{% load static %}

        <link rel="stylesheet" href="{% static '/main/css/style.css' %}" type="text/css">	

        <title>My Python Website</title>

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

	{% block body %}
	
	{% endblock %}

	<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    
	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

  </body>

</html>

在这里,我加载了引导 css/js 文件和一个自定义 css 文件。

登录.html

{% extends 'base.html' %}

{% block head %}

{% load static %}

    <link rel="stylesheet" href="{% static '/users/css/style.css' %}" type="text/css">	

    <title>My Python Login</title>

{% endblock %}


{% block body %}

<div class="container text-center">

    <form class="form-signin" method="post" action="{% url 'login' %}"> 

	{% csrf_token %}

        <img class="mb-4" src="{% static 'main/images/placeholder_logo.png' %}" width="114" height="100" alt="">

        <h1 class="h3 mb-3 font-weight-normal">Please Sign in</h1>

        <label for="id_username" class="sr-only">Username</label>

        {{ form.username }}

        <label for="id_password" class="sr-only">Password</label>

        {{ form.password }}

        <div class="checkbox mb-3">
      
          <label for="id_remember_me">

              {{ form.remember_me }} Remember me

          </label>

      </div>

        {% if form.errors %}
        
        <p  class="alert alert-danger" role="alert">
           
            Your username and password didn't match.
            Please try again.

        </p>
        
        {% endif %}

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

        <p class="mt-5 mb-3 text-muted">&copy; My First Python Website 2017-2018</p>

    </form>

</div>

{% endblock %}

那么现在,这看起来如何?我怎样才能提高我的新手?
目前让我感到困惑的事情,例如模板和表单的 CSS 样式方法。由于一半的 class/id 分配发生在模板中,另一半发生在forms.py中。我该如何改进这一点,一般的工作方式或推荐的工作方式是什么?

标签: pythondjango

解决方案


推荐阅读