Answer the question
In order to leave comments, you need to log in
How to solve "NOT NULL constraint failed: mainapp_cartproduct.user_id" error?
Hello! After I added registration to the site, an error began to appear when adding goods to the cart
IntegrityError at /add-to-cart/Interior_paints1/
NOT NULL constraint failed: mainapp_cartproduct.user_id
The error appears exactly if the user is not authorized on the site, if you log in, then the error immediately same disappears.
forms.py
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Логин'
self.fields['password'].label = 'Пароль'
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
if not User.objects.filter(username=username).exists():
raise forms.ValidationError(f'Пользователь с логином "{username} не найден в системе')
user = User.objects.filter(username=username).first()
if user:
if not user.check_password(password):
raise forms.ValidationError("Неверный пароль")
return self.cleaned_data
class RegistrationForm(forms.ModelForm):
confirm_password = forms.CharField(widget=forms.PasswordInput)
password = forms.CharField(widget=forms.PasswordInput)
phone = forms.CharField(required=False)
address = forms.CharField(required=False)
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Логин'
self.fields['password'].label = 'Пароль'
self.fields['confirm_password'].label = 'Подтвердите пароль'
self.fields['phone'].label = 'Номер телефона'
self.fields['first_name'].label = 'Имя'
self.fields['last_name'].label = 'Фамилия'
self.fields['address'].label = 'Адрес'
self.fields['email'].label = 'Электронная почта'
def clean_email(self):
email = self.cleaned_data['email']
domain = email.split('.')[-1]
if domain in ['com', 'net']:
raise forms.ValidationError(
f'Регистрация для домена {domain} невозможна'
)
if User.objects.filter(email=email).exists():
raise forms.ValidationError(
f'Данный почтовый адрес уже зарегистрирован в системе'
)
return email
def clean_username(self):
username = self.cleaned_data['username']
if User.objects.filter(username=username).exists():
raise forms.ValidationError(
f'Имя {username} занято'
)
return username
def clean(self):
password = self.cleaned_data['password']
confirm_password = self.cleaned_data['confirm_password']
if password != confirm_password:
raise forms.ValidationError('Пароли не совпадают')
return self.cleaned_data
class Meta:
model = User
fields = ['username', 'password', 'confirm_password', 'first_name', 'last_name', 'address', 'phone', 'email']
class LoginView(CartMixin, View):
def get(self, request, *args, **kwargs):
form = LoginForm(request.POST or None)
categories = Category.objects.all()
context = {
'form': form,
'categories': categories,
'cart': self.cart
}
return render(request, 'login.html', context)
def post(self, request, *args, **kwargs):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(
username=username, password=password
)
if user:
login(request, user)
return HttpResponseRedirect('/')
categories = Category.objects.all()
context = {
'form': form,
'cart': self.cart,
'categories': categories
}
return render(request, 'login.html', context)
class RegistrationView(CartMixin, View):
def get(self, request, *args, **kwargs):
form = RegistrationForm(request.POST or None)
categories = Category.objects.all()
context = {
'form': form,
'categories': categories,
'cart': self.cart
}
return render(request, 'registration.html', context)
def post(self, request, *args, **kwargs):
form = RegistrationForm(request.POST or None)
if form.is_valid():
new_user = form.save(commit=False)
new_user.username = form.cleaned_data['username']
new_user.email = form.cleaned_data['email']
new_user.first_name = form.cleaned_data['first_name']
new_user.last_name = form.cleaned_data['last_name']
new_user.save()
new_user.set_password(form.cleaned_data['password'])
new_user.save()
Customer.objects.create(
user=new_user,
phone=form.cleaned_data['phone'],
address=form.cleaned_data['address']
)
user = authenticate(
username=new_user.username, password=form.cleaned_data['password']
)
login(request, user)
return HttpResponseRedirect('/')
categories = Category.objects.all()
context = {
'form': form,
'categories': categories,
'cart': self.cart
}
return render(request, 'registration.html', context)
Answer the question
In order to leave comments, you need to log in
Where is the mainapp_cartproduct model?
If I understand correctly, then the model in the user field cannot have a NULL value, but it tries to be installed there for unauthorized people
. According to your problem:
https://ru.stackoverflow.com/questions/803293/%D0%...
https: //stackoverflow.com/questions/42960271/not-n...
https://stackoverflow.com/questions/46512639/not-n...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question