FOREIGN KEY constraint failed in signals - django

I tried to insert data into the table Account, but I keep getting this error message.
I delete all my migrations and make migrations again but I keep getting this error.
Here is my models.
class Student(models.Model):
user = models.OneToOneField(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
section = models.ForeignKey(Section, on_delete=models.CASCADE, default=1)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
batch = models.CharField(max_length=15, null=True, blank=True)
USN = models.CharField(primary_key='True', max_length=100)
DOB = models.DateField(default='1998-01-01')
profile_image = models.ImageField(upload_to='student/profile_images/%Y/%m/%d/', blank=True, null=True)
address = models.CharField(max_length=300, null=True, blank=True)
nationality = models.CharField(max_length=100, null=True, blank=True)
guardian_name = models.CharField(max_length=200, null=True, blank=True)
guardian_number = models.CharField(max_length=15, null=True, blank=True)
guardian_address = models.CharField(max_length=300, null=True, blank=True)
blood_group = models.CharField(max_length=3, null=True, blank=True)
exam_name = models.CharField(max_length=300, null=True, blank=True)
background = models.CharField(max_length=300, null=True, blank=True)
passing_year = models.CharField(max_length=8, null=True, blank=True)
score = models.CharField(max_length=10, null=True, blank=True)
school_name = models.CharField(max_length=300, null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
certificate = models.FileField(upload_to='certificates/%Y/%m/%d/', null=True, blank=True)
Here is Account model.
class Account(AbstractBaseUser, PermissionsMixin):
unid = models.CharField(max_length=20, unique=True, null=True, blank=True)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True, blank=True)
user_permissions = models.ManyToManyField(
Permission,
verbose_name=_('user permissions'),
blank=True,
null=True,
help_text=_('Specific permissions for this user.'),
related_name="user_set",
related_query_name="user",
)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
registered = models.BooleanField(default=False)
so what I did is that when I create account if the is_student is True I create a signals that going to create student model for that account instance automatically.
here is the signals
def create_student_or_teacher(sender, created, instance, **kwargs):
if created:
if instance.is_student:
Student.objects.create(
user=instance,
USN=instance.unid,
)
elif instance.is_teacher:
Teacher.objects.create(
user=instance,
id=instance.unid,
)
So when I create the account for student the tracker will highlight in the signals Student.objects.create(...)
If you have any idea I hope it would help me.
UPDATED:
When I'm creating teacher it is working find.
here is the teacher model
class Teacher(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=15, blank=True, null=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True)
salary = models.IntegerField(default=1)
school = models.ForeignKey(School, blank=True, null=True, on_delete=models.CASCADE)
section = models.ForeignKey(Section, blank=True, null=True, on_delete=models.CASCADE)
user = models.OneToOneField(Account, on_delete=models.CASCADE, null=True)
id = models.CharField(primary_key=True, max_length=100)
dept = models.ForeignKey(Dept, on_delete=models.CASCADE, blank=True, null=True)
DOB = models.DateField(default='1980-01-01')
profile_image = models.ImageField(upload_to='teacher/profile_images/%Y/%m/%d/', blank=True, null=True)
nationality = models.CharField(max_length=300, null=True, blank=True)
address = models.CharField(max_length=300, null=True, blank=True)

Finally after few hours I solved my error it was simple
in the section I set default value which was not exist
so I just change the value to an exist one and that was it.

Related

It is not possible to migrate a new user element to the django table

I am faced with the problem that it is not possible to migrate the new user value to the database table. At first there were errors on related_name, but I fixed it, and now that this value cannot be zero, at the same time, if I write that null=True, then the user cannot be displayed in the records in the future.
class Writehelp(models.Model):
users = models.ForeignKey(User,on_delete = models.CASCADE,related_name='helpedman',null=False,verbose_name='Автор')
titles = models.CharField(max_length=200, verbose_name='Заголовок', blank=True)
descriptions = models.TextField(blank=True, verbose_name='Описание')
createdtimes = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания')
prices = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена')
course = models.IntegerField(null=True, blank=True, verbose_name='Курс')
semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр')
subjects = models.CharField(max_length=200, null=True, blank=True, verbose_name='Предмет')
institutes = models.CharField(max_length=200, null=True, blank=True, verbose_name='Институт')
However, when I migrated this model, there were no problems:
class UploadFile(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор')
title = models.CharField(max_length=200, verbose_name='Заголовок',blank=True)
# uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл')
description = models.TextField(blank=True, verbose_name='Описание')
createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания')
price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена')
number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс')
number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр')
subjectt = models.CharField(max_length=200, null=True,blank=True,verbose_name='Предмет')
type_materials = models.CharField(max_length=200,null=True,blank=True, verbose_name='Тип работы')
institute = models.CharField(max_length=200, null=True,blank=True, verbose_name='Институт')
Add defult=None to uploadedfile field in your UploadFile model.

How to get user object in template?

model.py
class User(AbstractUser):
is_agree = models.CharField(max_length=1, blank=True)
is_verify = models.CharField(max_length=1, blank=True)
type = models.CharField(max_length=1, blank=True)
name = models.CharField(max_length=255, blank=True)
address1 = models.CharField(max_length=255, blank=True)
address2 = models.CharField(max_length=255, blank=True)
bank_account = models.CharField(max_length=255, blank=True)
phone_number = models.CharField(max_length=255, blank=True)
I want to get users type in template.
I tried {{ user.type }}. but was not worked

How to implement switch accounts option in Django

Consider an application where there is a company account and employee account. I want to add employees as admin of the company. Then the admin should be able to switch account with the company. Is it possible to do the switch account option?
I am a beginner in Django. Can anyone help me with this problem?
I am adding my user model here:
# Custom user
class CustomUser(AbstractUser):
""" Custom user model"""
email = models.EmailField(unique=True, validators=[EmailValidator])
is_company = models.BooleanField(default=True)
is_employee = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
slug = AutoSlugField(populate_from='username')
def __str__(self):
return f"{self.username}"
# Company user
class CompanyAccount(TimeStampedModel):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='company')
name = models.CharField(max_length=50, null=True, blank=True)
description = models.TextField(null=True, blank=True)
email = models.EmailField(null=True, blank=True)
website_url = models.URLField(null=True, blank=True)
industry = models.CharField(max_length=50, null=True, blank=True)
founded_year = models.PositiveSmallIntegerField(blank=True, null=True)
headquarters = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return f"{self.name}"
# Employee user
class Employee(TimeStampedModel):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="profile")
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
job_title = models.CharField(max_length=100, null=True, blank=True)
company = models.ForeignKey(CompanyAccount, on_delete=models.CASCADE, related_name="employee")
def __str__(self):
return f"{self.user.username}"

What am I missing in this Django model relationship

I have a CustomUser model, and a Blog model.
CustomUser model:
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=20, default="", blank=True)
last_name = models.CharField(max_length=20, default="", blank=True)
address = models.CharField(max_length=150, default="", blank=True)
city = models.CharField(max_length=20, default="", blank=True)
zip_code = models.CharField(max_length=20, default="", blank=True)
country = models.CharField( max_length=50, default="", blank=True, choices=settings.COUNTRIES_LIST)
about_me = models.TextField(max_length=225, default="", blank=True)
photo_url = models.TextField(null=True)
is_active = models.BooleanField(default=True) # can login
Blog model:
class Blog(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, verbose_name=_('user'), related_name="%(class)s_blogs", on_delete=models.SET_NULL)
blog_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)
blog_title = models.CharField(max_length=150, null=False)
blog_description = models.TextField(max_length=300, null=True, blank=True)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
blog = FroalaField()
dynamic_link = models.CharField(max_length=225, null=False, default="")
blog_type = models.CharField( max_length=50, null=False, choices=BLOGSTYPE_LIST)
blog_status = models.CharField(max_length=150, null=False, default="unapproved")
is_active = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
My understanding is that I could use the related_name to get all blogs by a user.
>>> from users.models import CustomerUser
>>> user = CustomUser.objects.get(pk=1)
>>> user.blog_blogs.all()
<BlogQuerySet []>
As you must have seen, this turns to always return but an empty queryset, even though there are blog entries by that user.
So is it am not understanding here?
Thank you.

Make a query to django models

How is "translation" for following query to django queryset?
SELECT guid FROM feedme_feeditem
WHERE feed_id IN
(SELECT id FROM feedme_feed WHERE country_id IN
(SELECT id FROM feedme_country WHERE name='NL'))
models.py
class Country(models.Model):
name = models.CharField(max_length=250, blank=True)
class Category(models.Model):
name = models.CharField(max_length=250, blank=True)
slug = models.SlugField(blank=True, null=True, editable=False)
user = models.ForeignKey(User, blank=True, null=True)
country = models.ForeignKey(Country, blank=True, null=True)
class Feed(models.Model):
link = models.CharField(blank=True, max_length=450)
url = models.CharField(blank=True, max_length=450)
title = models.CharField(blank=True, null=True, max_length=250)
category = models.ForeignKey(Category, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
last_update = models.DateField(blank=True, null=True, editable=False)
country = models.ForeignKey(Country, blank=True, null=True)
class FeedItem(models.Model):
title = models.CharField(max_length=350, blank=True)
link = models.URLField(blank=True)
content = models.TextField(blank=True)
feed = models.ForeignKey(Feed, blank=True, null=True)
read = models.BooleanField(default=False)
guid = models.CharField(max_length=255)
pub_date = models.DateTimeField()
To make more simple I already tried add country = models.ForeignKey(Country, blank=True, null=True) to FeedItem class but does't work how i expected.
guids = FeedItem.objects.filter(feed__country__name = 'NL')