Всем привет! После того как добавил на сайт регистрацию стала появляться ошибка при добавлении товара в корзину
IntegrityError at /add-to-cart/Interior_paints1/
NOT NULL constraint failed: mainapp_cartproduct.user_id
Ошибка появляется именно если пользователь не авторизован на сайте, если авторизоваться, то ошибка сразу же пропадает.
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']
views.py
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)
Объясните пожалуйста, как мне сделать, чтобы можно было добавлять товар в корзину анонимный юзерам.