so i recently changed my project user form to abstract base user and well my users can not add products or view their profile i know its problem in views.py and forms.py but whatever i change it in to is still has some problems beside the error in the title.
views.py
rom django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserChangeForm
from django.utils.text import slugify
from django.shortcuts import render, redirect
from .models import NewUser
from products.models import Product
from .forms import ProductForm
from .forms import UserCreationForm
# Create your views here.
def become_vendor(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
vendor = NewUser.objects.create(user_name=user.first_name)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'vendor/become_vendor.html', {'form': form})
@login_required
def vendor_admin(request):
context = {
'user':request.user
}
vendor = request.user.user_name
return render(request,'vendor/vendor_admin.html',{'vendor': vendor ,'context':context})
@login_required
def add_house(request):
if request.method == 'POST':
form = ProductForm (request.POST, request.FILES)
if form.is_valid():
product = form.save(commit=False)
NewUser.user_name = request.user.user_name
product.slug = slugify(product.عنوان)
product.save()
return redirect('vendor_admin')
else:
form = ProductForm()
return render(request,'vendor/add_house.html',{'form': form})
class UserEditView(generic.UpdateView):
models = NewUser
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
seccess_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
forms.py
rom django.forms import ModelForm
from products.models import Product
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from .models import NewUser
class ProductForm(ModelForm):
class Meta:
model = Product
fields =['نوع_قرارداد','عنوان','تصاویر','قیمت','توضیحات']
class RegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = NewUser
fields = ( 'user_name', 'email','phone','password')
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password"])
if commit:
user.save()
return user
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='رمزعبور', widget=forms.PasswordInput)
password2 = forms.CharField(label='تایید رمزعبور', widget=forms.PasswordInput)
class Meta:
model = NewUser
fields = ('user_name', 'email' ,'phone', 'profile_pic',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("گذرواژه ها مطابقت ندارند")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = NewUser
fields = ( 'user_name','email','phone', 'about', 'profile_pic',)
def clean_password(self):
return self.initial["password"]
i dont know if the models might be the problem or not but i add them anyways
models.py
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, user_name, first_name, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, user_name, first_name, password, **other_fields)
def create_user(self, email, user_name, first_name, password, **other_fields):
if not email:
raise ValueError(_('لطفا یک ادرس ایمیل بدهید'))
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name,
first_name=first_name, **other_fields)
user.set_password(password)
user.save()
return user
def get_profile_image_filepath(self,filename):
return f'uploads/{self.pk}/{"profile.png"}'
def get_default_profile_image():
return "uploads/profiled.png"
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.CharField(_('ایمیل'),max_length=255 ,unique=True)
user_name= models.CharField(_('نام کاربری'),max_length=255, unique=True)
first_name = models.CharField(_('نام مسکن'),max_length=255 , blank=True)
phone = models.CharField(_('شماره همراه'),max_length=50, blank=True)
تاریخ_ثبت_نام = models.DateTimeField(verbose_name='تاریخ_ثبت_نام', auto_now_add=True)
اخرین_ورود = models.DateTimeField(verbose_name='اخرین_ورود', auto_now=True)
about = models.TextField(_(
'درباره شما'), max_length=500, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
profile_pic = models.ImageField(_('عکس پروفایل'),max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['user_name', 'first_name']
def __str__(self):
return self.user_name
def get_profile_image_filenames(self):
return str(self.profile_pic)[str(self.profile_pic).index(f'uploads/{self.pk})/'):]
please consider the fact that iam new in django i really appericate any help for my project and if anyother mistake has been made please inform me i really appericate it.
and here is the traceback
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: products_product.vendor_id) was the direct cause of the following exception:
File "C:\Program Files\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Program Files\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Program Files\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "X:\website\vendor\views.py", line 59, in add_house
product.save()
File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 743, in save
self.save_base(using=using, force_insert=force_insert,
File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 780, in save_base
updated = self._save_table(
File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 885, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 923, in _do_insert
return manager._insert(
File "C:\Program Files\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Program Files\Python310\lib\site-packages\django\db\models\query.py", line 1301, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Program Files\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1441, in execute_sql
cursor.execute(sql, params)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 99, in execute
return super().execute(sql, params)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 80, in _execute
with self.db.wrap_database_errors:
File "C:\Program Files\Python310\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Program Files\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute
return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /add_house/
Exception Value: NOT NULL constraint failed: products_product.vendor_id
product app models.py
from io import BytesIO
from PIL import Image
from django.core.files import File
from django.db import models
from vendor.models import NewUser
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
ordering = models.IntegerField(default=0)
class Meta:
ordering =['ordering']
def __str__(self):
return self.title
class Product(models.Model):
نوع_قرارداد= models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
vendor = models.ForeignKey(NewUser, related_name='products',null=True, on_delete=models.CASCADE)
عنوان = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
توضیحات = models.TextField(blank=True, null=True)
قیمت = models.DecimalField(max_digits=10 , decimal_places=4)
date_added =models.DateTimeField(auto_now_add=True)
تصاویر = models.ImageField(upload_to='uploads/',)
thumbnail = models.ImageField(upload_to='uploads/',)
class Meta:
ordering =['-date_added']
def __str__(self):
return self.title
def get_thumbnail(self):
if self.thumbnail:
return self.thumbnail.url
else:
if self.تصاویر:
self.thumbnail = self.make_thumbnail(self.تصاویر)
self.save
return self.thumbnail.url
else:
return 'http://placehold.jp/240x180.png'
def make_thumbnail(self,تصاویر, size=(300 , 200)) :
img =Image.open(تصاویر)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG',quality=90)
thumbnail = File(thumb_io, name=تصاویر.name)
return thumbnail