I'm particularly new to django and still in the learning process. I have this code where it would have the user input any text into the field and once the user hits the submit button it would grab the text they inputted and look for it in the django database for that item. It's able to do what I want, except when there are no users with that username. I don't know where I would do an if statement, or a work around for that.
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)
CodePudding user response:
I would use an if statement alongside the function 'exists()'. It would look something like this:
username = request.POST['passUsername']
if (User.objects.exists(username = username):
user = User.objects.get(username = username)
else:
# Throw error
Also, be careful with your variable naming :)
CodePudding user response:
you can handle it within the try catch block where get
method will raise exception (DoesNotExist) if then object is not present in the 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')