本帖最后由 thepoy 于 2020-7-27 23:40 编辑
你的视图函数里应该对不同的方法进行区分,比较好的是用类视图,拿一个我之前写的例子给你参考一下:
# 这是一个模拟用户登录的类视图
class LoginView(View):
# 前端调用get时,类视图也调用get
def get(self, request):
return render(request, 'user/login.html')
# 前端调用post时,类视图也调用post,函数体内你可以写具体要实现的方法
def post(self, request):
login_form = UserLoginForm(request.POST)
if login_form.is_valid():
email = login_form.cleaned_data['email']
password = login_form.cleaned_data['password']
user = authenticate(username=email, password=password)
if user:
if user.is_start:
login(request, user)
url = request.COOKIES.get('url', '/')
response = redirect(url)
response.delete_cookie('url')
# return redirect(url).delete_cookie('url')
return response
else:
return HttpResponse('请点击邮件中的激活链接激活账号')
else:
return render(request, 'user/login.html', {'err': '邮箱或密码错误'})
else:
return render(request, 'user/login.html', context={'register_form': login_form})
你既然用ajax,我觉得你的使用环境可能是前后端分离,所以如果你用的是restfu的话,可以参考:
class UsersAPIView(CreateAPIView):
serializer_class = UserSerializer
queryset = UserModel.objects.all()
def post(self, request, *args, **kwargs):
# action 是url中的参数
action = request.query_params.get('action')
if action == 'login':
name = request.data.get('name')
password = request.data.get('password')
try:
user = UserModel.objects.get(name=name)
if user.password != password:
raise exceptions.AuthenticationFailed
token = uuid.uuid4().hex
cache.set(token, user.id, timeout=60 * 60 * 24)
data = {
'status': 200,
'msg': '登录成功',
'token': token
}
return Response(data)
except UserModel.DoesNotExist:
raise exceptions.NotFound
elif action == 'register':
return self.create(request, *args, **kwargs)
else:
raise exceptions.ParseError
|