Search code examples
pythondjangonullintegrity

django cannot fix integrity error


I've decided to drop a row from a field from a database i'm setting up in django. I've deleted it in models/form and completely re-ran the database (makemigrations, migrate). However, no matter what I do i keep getting an integrity error (NOT NULL constraint failed: index_user.email). I'm not sure why i'm getting this, as the field doesn't even exist anymore and I cant find any trace of it in any files. Anyone know how to solve this error?

models:

from django.db import models

# Create your models here.

class user(models.Model):
    username = models.CharField(max_length=20)
    password = models.CharField(max_length=15)

    def __str__(self):
        return self.username + ' - ' + self.password

views:

def login(request):
    form = LoginForm(request.POST)
    if form.is_valid():
         username = form.cleaned_data["username"]
         password = form.cleaned_data["password"]
         user = authenticate(username=username, password=password)

         if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('loggedin.html')
            else:
                return HttpResponse("Account deleted or disabled")
         else:
            return HttpResponseRedirect('/invalid')

    return render(request, "login_page.html", {'form': form})

form:

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

def clean(self, *args, **kwargs):
    username = self.cleaned_data.get("username")
    password = self.cleaned_data.get("password")
    if username and password:
        user = authenticate(username=username, password=password)
        if not user:
            raise forms.ValidationError("User does not exist.")
        if not user.is_active:
            raise forms.ValidationError("User is no longer active.")
    return super(UserLoginForm, self).clean(*args, **kwargs)

Solution

  • If you are using Mysql as your database backend, then when you delete any field in the django model, even you run makemigrate and migrate, Mysql will still NOT actually delete that field or column inside the database.

    Therefore the column index_user.email, you think have deleted, should still inside the database, that gives you the error.

    You have to get into the mysql console or any mysql cilent to drop that column by yourself, not by django migration.

    If you are using sqlite, unfortunately, you can't drop a column on a table. you can check the reason on the link below:

    https://stackoverflow.com/a/8442173/4151886

    and solution you can find on the link below:

    https://stackoverflow.com/a/5987838/4151886