Django duplicate entry 1062 - python

I ran python manage.py migrate accounts zero then i faced an error,
I checked my models multiple times it seems everything is ok but...!?
This is the error:
django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'accounts_post_user_id_ecf3e197_uniq'")
User model:
class User(AbstractBaseUser):
id = models.BigAutoField(primary_key=True)
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(max_length=191, unique=True)
email_verified = models.BooleanField(default=False)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
objects = UserManager()
USERNAME_FIELD = 'username'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
Post model:
class Post(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
channel = models.ForeignKey(Channel, on_delete=models.CASCADE, null=True, blank=True)
hashed_id = models.CharField(max_length=191)
text = models.TextField(max_length=270)
visits = models.IntegerField(default=0)
comment_status = models.BooleanField(default=True)
edited = models.BooleanField(default=False)
signature = models.CharField(max_length=191)
deleted_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
There was 1 user with 2 posts.

I added unique=False to ForeignKey fields and it solved the problem.
I hope if this error occurs in your app this answer gives you a hand.

Related

How to get logged in user in django from custom users model

I want to get username from custom users model
My Custom Users model:
class Account(AbstractBaseUser, PermissionsMixin):
nickname = models.CharField(max_length=150, unique=True)
name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
phone = models.CharField(max_length=50, unique=True)
date_of_birth = models.DateField(blank=True, null=True)
picture = models.ImageField(blank=True, null=True)
is_staff = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
last_login = models.DateTimeField(null=True)
admin_of_company = models.ForeignKey('companies.company', on_delete=models.CASCADE, default=None, blank=True,
null=True)
objects = AccountManager()
USERNAME_FIELD = 'nickname'
REQUIRED_FIELDS = ['name', 'last_name', 'phone']
def get_full_name(self):
return self.name, self.last_name
def get_short_name(self):
return self.name.split()[0]
and products model:
class products(models.Model):
name = models.CharField(max_length=150)
about = models.TextField()
price = models.IntegerField()
picture = models.ImageField(default=None)
admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
in products.admin I want to set default logged in user
but I don't know how to get this data from custom users model
If you would like to get a current account in your view use this
current_user_id = self.request.user.id
current_account = Account.objects.get(pk=current_user_id)
current_account_nickname = current_account.nickname
Your model Account doesn't have "username" field.
You have to add it if you would like to use "username".
class Account(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=150, unique=True)

Django add to cart as a guest without logging in

I'm working on a ecom website project and I follow Dennis Ivy's course about cart functionality. I want to add to cart whether the person is logged in or not. I place my code down below, where products are added to the cart as a order when you're logged in and everything's fine but when user is not logged in nothing happen even though I created the device key inside cookies.
models:
class User(AbstractBaseUser):
email = models.EmailField(verbose_name='email',max_length=255, unique=True)
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
username = models.CharField(max_length=50, default=None, unique=False, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name','last_name']
objects = UserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
class Guest(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
device = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
if self.name:
name = self.name
else:
name = self.device
return str(name)
class Order(models.Model):
klient = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
gosc = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True, blank=True)
data_zamowienia = models.DateTimeField(auto_now_add=True)
dostarczona = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
produkt = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
ilosc = models.IntegerField(default=0, null=True, blank=True)
data_dodania = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
def order_set(self):
pass
views:
def updateItem(request):
data = json.loads(request.body)
productId = data['productId']
action = data['action']
product = Product.objects.get(id=productId)
try:
user = request.user
order, created = Order.objects.get_or_create(klient=user, produkt=product, dostarczona=False)
except:
device = request.COOKIES['device']
customer, created = Guest.objects.get_or_create(device=device)
order, created = Order.objects.get_or_create(gosc=customer, produkt=product, dostarczona=False)
if action == 'add':
order.ilosc = (order.ilosc + 1)
elif action == 'remove':
order.ilosc = (order.ilosc - 1)
order.save()
if order.ilosc <= 0:
order.delete()
return JsonResponse('Item was added', safe=False)
I just did a quick test with the following view.
def myview(request):
print(request.user)
return HttpResponse("hello")
In an unauthenticated session, request.user isn't empty or None by the looks of it.
System check identified no issues (0 silenced).
January 09, 2021 - 21:45:29
Django version 3.1.5, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
AnonymousUser
[09/Jan/2021 21:45:33] "GET /test/ HTTP/1.1" 200 5
So if you're just doing a truthy check on request.user it's always going to be true.
You could perhaps do the following:
def myview(request):
if request.user != 'AnonymousUser':
# insert logged in user code here
else:
# insert your device related code here

How fetch username of staff user in django forms

I am using a custom User model. And I have another Customer model. I want the user field will only show the staff user no other type of user in the field will show in the registration form. In my case, it is showing all types of users whether it is staff or customer or a service user.
Models.py
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True)
name = models.CharField(max_length=254, null=True)
email = models.EmailField(max_length=254, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_Customer = models.BooleanField(default=False)
is_Service_Provider = models.BooleanField(default=False)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'username'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % self.pk
def get_username(self):
return self.username
class Customer(models.Model):
user = models.OneToOneField('accounts.User', on_delete=models.SET_NULL, null=True)
email = models.EmailField(max_length=254, null=False)
date_Of_Birth = models.DateField(null=False)
country = models.ForeignKey('accounts.Country', null=True, on_delete=models.SET_NULL, related_name='Country')
state = models.ForeignKey('accounts.State', null=True, on_delete=models.SET_NULL, related_name='State')
city = models.ForeignKey('accounts.City', null=True, on_delete=models.SET_NULL, related_name='city')
address = models.CharField(max_length=254, null=False)
refernce_by_person_name = models.CharField(max_length=254, null=True)
refernce_by_person_contact_no = models.IntegerField(null=True)
phone_no = models.IntegerField(null=False)
alternate_no = models.IntegerField(null=False)
hobbies = models.CharField(max_length=254)
def __str__(self):
return self.user.username
views.py
def form(request):
forms = CustomerRegistrationForm()
if request.method == "POST":
forms = CustomerRegistrationForm(request.POST)
if forms.is_valid():
forms.save()
return redirect('/customer/show')
context = {
'forms' : forms,
}
return render(request,'customer/form.html', context)
forms.py
class CustomerRegistrationForm(forms.ModelForm):
class Meta:
model = Customer
fields = '__all__'
You can filter the staff users in the form like this.
class CustomerRegistrationForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True))
class Meta:
model = Customer
fields = ['user','email','date_of_birth',...]

Django-rest-framework : create serializer for registration of two diferent user-type foreignkey relation with one custom user model

I want to create two user registration using one custom user.
Here is my
MODELS.PY:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True )
phone_number = PhoneNumberField(_("Phone number"),unique=True, blank=True, null=True)
username = models.CharField(_("Username"),max_length=254,unique=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(auto_now=True)
date_joined = models.DateTimeField(auto_now_add=True)
full_name = models.CharField(_("Full Name"), max_length=50, null=True)
date_of_birth = models.DateField(_("Birth date"), auto_now=False, auto_now_add=False, null=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
class Aesthete(models.Model):
basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_verified = models.BooleanField(_("Verified"), default=False)
class Artist(models.Model):
basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_verified = models.BooleanField(_("Verified"), default=True)
debutsong = AudioField(upload_to='songsfile', blank=True,
ext_whitelist=(".mp3", ".wav", ".ogg"),
help_text=("Allowed type - .mp3, .wav, .ogg"))
How can I create registration serializer and view? Please help. Thank you.

Unexpected outcome from model inheritance in Django

I've built a custom user model called "Administrator" for superuser purpose, and the other model called "Customer" for normal user purpose.
I intended to separate them into two different tables, it partly worked but not perfectly. The problem is that when I created an instance for Customer, the instance will be automatically added into the Administrators table, this isn't what I want.
Administrator model on Django admin site
Customer model on Django admin site
Administrator model shown below:
class Administrator(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
join_date = models.DateField(auto_now_add=True, editable=False)
objects = AdministratorManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.get_full_name()
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
Customer model shown below:
class Customer(Administrator):
first_name = models.CharField(max_length=255, default='', blank=False)
last_name = models.CharField(max_length=255, default='', blank=False)
DOB = models.DateField()
security_question1 = models.CharField(max_length=500, default='', blank=False)
security_question2 = models.CharField(max_length=500, default='', blank=False)
security_question_answer1 = models.CharField(max_length=500, default='', blank=False)
security_question_answer2 = models.CharField(max_length=500, default='', blank=False)
# REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'DOB', 'security_question1', 'security_question2']
is_active = True
is_admin = False
You are wrongly inherited the Customer model. It should be inherited from AbstractBaseUser as
class Customer(AbstractBaseUser):
#Your code
UPDATE-1
You can use Abstract class for inheriting.
Define a base class as Abstract and inherit from that class might help you
class BaseClass(PermissionsMixin, AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
join_date = models.DateField(auto_now_add=True, editable=False)
objects = AdministratorManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.get_full_name()
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
class Meta:
abstract = True
class Administrator(BaseClass):
pass
class Customer(BaseClass):
first_name = models.CharField(max_length=255, default='', blank=False)
last_name = models.CharField(max_length=255, default='', blank=False)
DOB = models.DateField()
security_question1 = models.CharField(max_length=500, default='', blank=False)
security_question2 = models.CharField(max_length=500, default='', blank=False)
security_question_answer1 = models.CharField(max_length=500, default='', blank=False)
security_question_answer2 = models.CharField(max_length=500, default='', blank=False)
# REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'DOB', 'security_question1', 'security_question2']
is_active = True
is_admin = False

Categories