Skip to content
Advertisement

Unable to save into Foreign key fields in Django with multiple table

I’m working on a project Hr Management System. I have a model with foreign key fields to office & staff. I’m trying to save staff in user & staff role wise with foreign key office name. my view

def post(self, request):
    if request.method != "POST":
        messages.error(request, "Invalid Method ")
    else:
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        address = request.POST.get('address')
        phone = request.POST.get('phone')
        image = "image"
        office_id=request.POST.get("office")
        office=Office.objects.get(id=office_id)
    try:
        user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2)
        user.staffs.address=address
        user.staffs.phone=phone
        user.staffs.image=image
        user.staffs.office_id=office
        user.save()
        messages.success(request, "Staff Added Successfully!")
        return render(request, 'admin_template/add_staff.html')

My models

class Staffs(models.Model):
    id = models.AutoField(primary_key=True)
    admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
    address  = models.CharField(max_length=255, blank=True)
    phone = models.CharField(blank=True,max_length=20)
    image = models.ImageField(upload_to='uploads/user/',blank=True)
    office_id = models.ForeignKey(Office,on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = models.Manager()

@receiver(post_save,sender=CustomUser)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.user_type == 1:
            AdminHOD.objects.create(admin=instance)
        if instance.user_type == 2:
            Staffs.objects.create(admin=instance)
@receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance,**kwargs):
    if instance.user_type == 1:
        instance.adminhod.save()
    if instance.user_type == 2:
        instance.staffs.save()

Advertisement

Answer

  1. We can remove (id) from Models since it auto-implemented
  2. office = models.ForeignKey(Office,on_delete=models.DO_NOTHING)
  3. Assign user staffs office to office like this
user.staffs.office = office
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement