Django在数据库中没有相同的用户名



我对django特别陌生,还在学习过程中。我有这段代码,它会让用户输入任何文本到字段,一旦用户点击提交按钮,它会抓住他们输入的文本,并在django数据库中寻找它的项目。它可以做我想做的,除非没有用户使用该用户名。我不知道我应该在哪里写if语句,或者如何解决这个问题。

views.py
from .forms import RequestPasswordResetForm
from django.contrib.auth.models import User
def request_password(request):
next = request.POST.get('next', '/')
if request.method == "POST":
user = request.POST['passUsername']
users = User.objects.get(username=user)
form = RequestPasswordResetForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Request has been sent! Admin will be with you shortly.')
return HttpResponseRedirect(next)

您可以在try catch块中处理它,其中get方法将引发异常(DoesNotExist),如果该对象不存在于DB中。

def request_password(request):
next = request.POST.get('next', '/')
try:
if request.method == "POST":
username = request.POST['passUsername']
user = User.objects.get(username=username)
form = RequestPasswordResetForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Request has been sent! Admin will be with you shortly.')
return HttpResponseRedirect(next)
except User.DoesNotExist:
messages.error(request, 'Invalid Username')

我会在函数'exists()'旁边使用if语句。它看起来像这样:

username = request.POST['passUsername']
if (User.objects.exists(username = username):
user = User.objects.get(username = username)
else:
# Throw error

还要注意变量的命名:)

相关内容

  • 没有找到相关文章

最新更新