P3P5 P3P5 - 6 months ago 7x
Python Question

If statement always returning true in django

I have a problem with my if statement, because it is always returning True.

I have a form where the user can change his profile information. Now I want when he tries to enter an email address that already exists to display an error message, but also when he does not change his current email address, but he changes his name, for example, I want that only the name gets changed. The code I use is:

def profil_update(request, slug=None):

instance = get_object_or_404(Guest, slug=slug)
form = UpdateGuestProfileForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
print (str(request.POST['email'] == instance.email))

if not request.POST['email'] == instance.email and Guest.objects.filter(email = request.POST['email']).exists():
messages.error(request, 'That email address is already taken.', extra_tags='email_exists')
instance = form.save(commit = False)
messages.success(request, "Success", extra_tags='profile_updated')
return HttpResponseRedirect(instance.get_absolute_url())

context = {
"guest": instance,
"form": form

return render(request, "base_profile_guest.html", context)

So, I think that the problem is because "request.POST['email'] == instance.get_email()" is ALWAYS TRUE. I tried everything and it is always true. Even if email addresses are not equal it is always true.


There's no need to do this in your view unless this is simply a learning exercise, you can just set this on the models to enforce unique emails:


      email = models.EmailField(..., unique=True, ...)