I'm trying to implement a foreign key at one of my tables, but I keep getting this error all the time:
null value in column "user_id" of relation "application_application" violates not-null constraintDETAIL: Failing row contains (3, 2022-09-09, San Ramon, CA, USA, https://logo.clearbit.com/uber.com, Uber, , Applied, Engineer, null).
I don't know what I'm doing wrong
from django.contrib.auth.models import User
class Application(models.Model):
__tablename__ = "applications"
name = models.CharField(max_length=50, blank=False, null=False)
title = models.CharField(max_length=50, blank=False, null=False)
status = models.CharField(max_length=50, blank=False, null=False)
notes = models.TextField(blank=True, default="Add some notes", null=True)
location = models.CharField(max_length=255, blank=False, null=False)
logo = models.CharField(max_length=255, blank=False, null=False)
date_applied = models.CharField(max_length=255, blank=False, null=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
It looks like you're not passing in the user when you're trying to save. Try this:
app = Application(user=request.user, name='App X', etc)
app.save()
Related
I am working with some custom-made user models in Django. They are the following:
myCustomeUser responsible for the primary identity of a user
Industry is a user that will link with OneToOneField to the myCustomeUser
Employee is another user account, which will FK to the myCustomeUser and FK to Industry
my models.py:
class myCustomeUser(AbstractUser):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=20, unique="True", blank=False)
password = models.CharField(max_length=20, blank=False)
is_Employee = models.BooleanField(default=False)
is_Industry = models.BooleanField(default=False)
class Industry(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user')
name = models.CharField(max_length=200, blank=True)
owner = models.CharField(max_length=200, blank=True)
license = models.IntegerField(null=True, unique=True)
industry_extrafield = models.TextField(blank=True)
Now I need to write the model of Employee. There are some conditions also:
It should contain name, National ID, gmail, rank, employee_varified, named fields
This will inherit the myCustomeUser and Industry both
The Industry account user will primarily entry all the data of Employee in the database, except username and password(which are inherited from myCustomeUser)
Later on, the Employee will search his National ID given by the Industry and finish the registration process by creating his username and password.
I have tried the Employee model like this:
class Employee(models.Model):
user = models.ForeignKey(myCustomeUser,primary_key=True, null=True, on_delete=models.CASCADE)
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
National_ID = models.IntegerField(null=True, blank=False, unique=True)
name = models.CharField(max_length=200, blank=False, null=True)
gmail = models.EmailField(null=True, blank=False, unique=True)
rank = models.CharField(max_length=20, blank=False, null=True)
employee_varified = models.BooleanField(default=False, blank=True, null=True)
But the problem with this model is I cannot create any Employee object without giving user (that means username and password), But the Industry user needs to entry their Employee's data, before complete the Employee's registration.
how can I write my Employee model to solve this problem?
If you can't guarantee that a related object will exist when you create an object, you can make the relationship(s) optional.
So in your case, I'd create your model more like;
class Employee(models.Model):
user = models.ForeignKey(
myCustomeUser,
blank=True,
null=True,
on_delete=models.CASCADE
)
industry = models.ForeignKey(
Industry,
blank=True,
on_delete=models.CASCADE
)
national_id = models.IntegerField(
null=True,
blank=False,
unique=True
)
name = models.CharField(
max_length=200,
blank=False,
null=True
)
# ... etc
You may also benefit from having a look through the following site which might help you learn a thing or two about django
https://www.django-antipatterns.com/
i want create a custom field with AutoField
description:
Code generated by the system is increasing gradually, the code consists of 5 digits, there are no 2 identical codes. For example: 00001, 00002
this is my code :
class Supplier(models.Model):
code = models.AutoField(primary_key=True, max_length=5, blank=False, null=False)
name = models.CharField(max_length=200, blank=False, null=False)
phone = models.CharField(max_length=11, unique=True, validators=[len_phone])
email = models.EmailField(blank=True, null=True, unique=True)
address = models.CharField(max_length=200, blank=False, null=False)
I have created a role model for Employee so that employee will be assigned to control
the overall app based on his/her role. I mean if the role of employee is given can_create_only, then the employee should be able to create inventory, orders, items etc and if employee is given can_create_edit_and_delete, then the employee would be like one of the admin and etc. For this I have designed the model as below but I want to know what is the best way to handle such and why?
Should I go with middleware or decorator way? Can anyone give me an example, please?
class Role(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Meta:
verbose_name = 'Role'
verbose_name_plural = 'Roles'
class Employee(models.Model):
office = models.ForeignKey(
OfficeSetup, blank=False, null=False, on_delete=models.CASCADE)
name = models.CharField(max_length=150, blank=False, null=False)
designation = models.ForeignKey(Designation, blank=False, null=False)
section = models.ForeignKey(DepartmentSetup, blank=True, null=True)
phone_number = models.CharField(max_length=150, blank=True, null=True)
mobile_number = models.CharField(max_length=150, blank=True, null=True)
email = models.EmailField(max_length=150, blank=False, null=False)
gender = models.CharField(
max_length=4, choices=GENDER, blank=True, null=True)
role = models.ForeignKey(Role, blank=True, null=True)
username = models.CharField(max_length=100, blank=False, null=False)
password = models.CharField(max_length=100, blank=False, null=False)
avatar = models.ImageField(
null=True, blank=True, upload_to=upload_employee_image_path)
class Meta:
verbose_name = 'Employee'
verbose_name_plural = 'Employees'
def __str__(self):
return self.name
When creating an employee by admin, the username, password and email, the admin provides will create a new user instance along with the employee
Django comes with Groups and permissions which provides all most everything you are looking for.
This may help you - How do I use Django groups and permissions?
Django documentation - https://docs.djangoproject.com/en/1.11/topics/auth/
I am creating a simple project which is about creating a resume by user. In resume, a user can have multiple experience, educational background and etc. That is why I have created the following table where experience, educational background, skills are foreignkey to the resume table.
class Resume(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name")
slug = models.SlugField(max_length=50, unique=True)
designation = models.CharField(max_length=200, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.name
class Education(models.Model):
resume = models.ForeignKey(Resume, related_name='education')
name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution")
course = models.CharField(max_length=200, blank=False, null=False, help_text="Name of a course")
description = models.CharField(max_length=400, blank=True, null=True)
start_date = models.DateField()
end_date = models.DateField()
class Experience(models.Model):
resume = models.ForeignKey(Resume, related_name='experience')
designation = models.CharField(max_length=100, blank=True, null=True)
company = models.CharField(max_length=100, blank=True, null=True)
description=models.CharField(max_length=400, blank=True, null=True)
start_date = models.DateField()
end_date = models.DateField()
class Skill(models.Model):
resume=models.ForeignKey(Resume, related_name="skills")
name = models.CharField(max_length=100, blank=True, null=True, help_text="Name of the skill")
class Meta:
verbose_name='Skill'
verbose_name_plural='Skills'
def __str__(self):
return self.name
Now for such situation, do I have to create a ResumeForm, EducationForm, ExperienceForm etc and create an Education, Experience and Skill formset or
I have to do something else. I do not have clear idea on how to move forward now for developing form with such
relation where Education, Skill can have multiple instance. Can anyone guide me, please?
Well the question is unclear but following with your idea you have 2 options:
First you can have existing values in Education, Experience, Skill. Then in the view you have a checkbox to add education, experience, skill.
Second you can add education, experience, skill creating a modelForm for each one and then passing the resume, It is not necessary use formset here
In database I have already registered 4 persons but they were registered when model hasn't had relation attributes yet. When I added them I got this model:
class Person(User):
type = models.BooleanField()
avatar = models.ImageField(blank=True)
second_name = models.CharField(max_length=30, blank=True, default='')
birthday = models.DateField(blank=True, default=None)
country = models.CharField(max_length=30, blank=True, default='')
city = models.CharField(max_length=30, blank=True, default='')
school = models.CharField(max_length=60, blank=True, default='')
university = models.CharField(max_length=60, blank=True, default='')
work_place = models.CharField(max_length=60, blank=True, default='')
profession = models.CharField(max_length=60, blank=True, default='')
phone = models.CharField(max_length=30, blank=True, default='')
about = models.TextField(blank=True, default='')
latitude = models.FloatField(blank=True, default=-1)
longitude = models.FloatField(blank=True, default=-1)
friends = models.ForeignKey(
'self',
related_name='+',
)
black_list = models.ForeignKey(
'self',
related_name='+',
)
dialogues = models.ManyToManyField(
'dialogues.Dialogue',
)
news = models.OneToOneField(
'news.NewsList',
)
wall = models.OneToOneField(
'blogs.Blog',
)
But now when this model migrates I have the error: django.db.utils.IntegrityError: UNIQUE constraint failed: persons_person.wall_id.
You should change the relation with Blog model, as one Person can write more than 1 blog, hence its a 1-M relation. So in Blog model you should define a ForeignKey to Person model.
person = models.ForeignKey(
'person.Person',
related_name='walls'
)
And wall field will be removed from Person model, but from person objects you will be able to access blogs using related name walls.
If your have a necessity of having Person to Blog as 1-1 relation, then your will have to remove records from database which don't follow this constraint.