[Fixed]-If statement always returning true in django

1👍

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:

 Guest(models.Model):

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

0👍

I solved it, thanks to Slayer. Here is what I did:

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():
        instance = form.save(commit = False)
        instance.save()
        messages.success(request, "Success", extra_tags='profile_updated')
        return HttpResponseRedirect(instance.get_absolute_url())
    else:
        messages.error(request, 'Email address alredy exists.', extra_tags='email_exists')
    context = {
        "guest": instance,
        "form": form
    }

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

So, I added “unique = True” to my model data, as Slayer said. And if form is not valid, I just write a error message. The answer was there all the time I just could not is it, my mistake.

👤P3P5

Leave a comment