Python高级编程-DJango2
在Python中使用Django框架进行高级编程时,我们可以创建一个简单的用户注册和登录功能。以下是一个简化的示例:
首先,确保你已经安装了Django。如果没有安装,可以使用以下命令安装:
pip install django
- 创建一个新的Django项目:
django-admin startproject myproject
- 进入项目目录并创建一个新的应用:
cd myproject
python manage.py startapp accounts
- 编辑
accounts/views.py
来添加登录和注册视图:
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views import View
from django.forms import Form
from django.forms import fields
class LoginView(View):
form_class = AuthenticationForm
template_name = 'login.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('home')
return render(request, self.template_name, {'form': form})
class RegisterView(View):
form_class = UserCreationForm
template_name = 'register.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(data=request.POST)
if form.is_valid():
user = form.save()
authenticate(request, username=user.username, password=request.POST['password1'])
return redirect('home')
return render(request, self.template_name, {'form': form})
def logout_view(request):
logout(request)
return redirect('home')
- 创建模板
accounts/templates/login.html
和accounts/templates/register.html
来显示表单:
<!-- login.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<!-- register.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
- 在
myproject/myproject/urls.py
中添加路由:
from django.urls import path
from django.contrib.auth import views as auth_views
from accounts.views import LoginView, RegisterView, logout_view
urlpatterns = [
path('login/', LoginView.
评论已关闭