this is my model class EmployeeProfile(MPTTModel): choice = [ ('نعم', 'نعم'), ('لا',…
- User
this is my model class Employee_Profile(MPTTModel): choice = [ ('نعم', 'نعم'), ('لا', 'لا'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) action_creator =models.CharField(max_length=250, null=True, blank=True) rawaf_id = models.IntegerField(null=True, blank=True, unique=True) iqama_no = models.IntegerField(null=True, blank=True, unique=True) full_name = models.CharField(max_length=250, null=True, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') job_name = models.CharField(max_length=250, null=True, blank=True) oc_level = models.IntegerField(null=True, blank=True) levels_nt_show = models.IntegerField(null=True, blank=True, default=0) his_chart = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='hischart') on_work = models.CharField(max_length=250, null=True, blank=True, choices=choice, default='نعم')
def __str__(self): return ", ".join([str(self.job_name), str(self.full_name)]) class MPTTMeta: verbose_name="rawaf_id" ordering = ['rawaf_id']and this is my views @login_required(login_url='login') def orgstructure(request): data = get_user_data(request) no_parent = Employee_Profile.objects.filter(~Q(rawaf_id__in=[0,1,11110000]), parent=None, on_work = 'نعم') no_parent_count = no_parent.count() try: employee_profile = Employee_Profile.objects.all() queryset = employee_profile.get_descendants(include_self=True).filter(~Q(rawaf_id=11110000), ~Q(parent=None), oc_level__lte=4, on_work = 'نعم').order_by('-oc_level','-job_name') # Add the ancestors of each employee to the queryset for employee in queryset: employee.ancestors = employee.get_ancestors() except Employee_Profile.DoesNotExist: # Handle the case when there is no Employee_Profile for the request.user # You can redirect to another view, show an error message, or create a default Employee_Profile return redirect('no_permission') context = { **data, 'employees':queryset, 'no_parent':no_parent, 'no_parent_count':no_parent_count, 'employee_profile':employee_profile, } if request.user.is_staff: return render(request, 'orgstructure/organization_structure.html', context) else: return redirect('no_permission') so i get this error get() returned more than one Employee_Profile -- it returned 2!
- Assistant
The error message "get() returned more than one Employee_Profile -- it returned 2!" occurs because you are using the
get()method in the lineemployee_profile = Employee_Profile.objects.all().get_descendants(include_self=True).filter(~Q(rawaf_id=11110000), ~Q(parent=None), oc_level__lte=4, on_work = 'نعم').order_by('-oc_level','-job_name')to retrieve multiple Employee_Profile instances. However, theget()method can only return a single object and will raise an error if it encounters more than one object.To fix this issue, you should use the
filter()method instead, which will return a queryset containing all matching objects. Update the line to:employee_profile = Employee_Profile.objects.all().filter( ~Q(rawaf_id=11110000), ~Q(parent=None), oc_level__lte=4, on_work='نعم' ).order_by('-oc_level', '-job_name')This will return a queryset instead of a single object, and you can iterate over it in your template.
- User
this is my model class Update_employee_action(models.Model):
user = models.ForeignKey(Employee_Profile, on_delete=models.CASCADE, related_name='Update_employee_action') rawaf_id = models.IntegerField(null=True, blank=True) iqama_no = models.IntegerField(null=True, blank=True) full_name = models.CharField(max_length=250, null=True, blank=True) parent = models.CharField(max_length=250, null=True, blank=True) job_name = models.CharField(max_length=250, null=True, blank=True) oc_level = models.IntegerField(null=True, blank=True) levels_nt_show = models.IntegerField(null=True, blank=True, default=0) his_chart = models.CharField(max_length=250, null=True, blank=True) on_work = models.CharField(max_length=250, null=True, blank=True) action_date = models.DateTimeField(null=True, blank=True, auto_now=True) action_creator =models.CharField(max_length=250, null=True, blank=True) def __str__(self): return str(self.id) class Meta: verbose_name="Update_employee_action"@receiver(post_save, sender=Employee_Profile) def creat_Actions_records(sender, instance, created, **kwargs): if created: Update_employee_action.objects.create( user = instance, rawaf_id=instance.rawaf_id, iqama_no = instance.iqama_no, full_name = instance.full_name, parent = instance.parent, job_name = instance.job_name, oc_level = instance.oc_level, levels_nt_show = instance.levels_nt_show, his_chart = instance.his_chart, on_work = instance.on_work, action_date = datetime.now(), action_creator = instance.action_creator, ) else: Update_employee_action.objects.create( user = instance, rawaf_id=instance.rawaf_id, iqama_no = instance.iqama_no, full_name = instance.full_name, parent = instance.parent, job_name = instance.job_name, oc_level = instance.oc_level, levels_nt_show = instance.levels_nt_show, his_chart = instance.his_chart, on_work = instance.on_work, action_date = datetime.now(), action_creator = instance.action_creator, ) and this is my views @login_required(login_url='login') def update_employee_data(request,id): data = get_user_data(request) cc = Employee_Profile.objects.filter(user=request.user)[0].get_descendants(include_self=True) update_Employee_Profile = cc.get(id=id) old_parent = update_Employee_Profile.parent form = Employee_Profile_Form(instance=update_Employee_Profile) if request.method == 'POST': form = Employee_Profile_Form(request.POST, request.FILES, instance=update_Employee_Profile) if form.is_valid(): instance = form.save(commit=False)
print("Old parent:", old_parent) # save the instance normally instance.save() # check if the parent has changed if instance.parent != old_parent: print("New parent:", instance.parent) # get the children of the instance children = instance.get_children() # update their parent to the old parent for child in children: child.parent = old_parent child.save() Employee_Profile.objects.rebuild() return redirect('orgstructure') context = { **data, 'form':form, } if request.user.is_staff: return render(request, 'orgstructure/update_employee_data.html', context) else: return redirect('no_permission')so i get this error Cannot assign "'56'": "Employee_Profile.user" must be a "User" instance.
- Assistant
The error "Cannot assign '56': 'Employee_Profile.user' must be a 'User' instance." occurs because the
userfield in theUpdate_employee_actionmodel is defined as a foreign key to theEmployee_Profilemodel withon_delete=models.CASCADE.In your view, you are trying to assign the
userfield with theupdate_Employee_Profileinstance, which is aEmployee_Profileobject, not aUserobject.To fix this issue, you need to pass the
Userobject instead of theEmployee_Profileobject when creating theUpdate_employee_actioninstance in your signal handler.Assuming you have a
Userinstance associated with theEmployee_Profileobject, you can update your signal handler code as follows:@receiver(post_save, sender=Employee_Profile) def creat_Actions_records(sender, instance, created, **kwargs): if created: Update_employee_action.objects.create( user=instance.user, # Pass the User object instead of the Employee_Profile object rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, ) else: Update_employee_action.objects.create( user=instance.user, # Pass the User object instead of the Employee_Profile object rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, )Make sure to update the
userfield assignment in bothif createdandelseblocks.Additionally, ensure that the
Employee_Profileobject has a valid associatedUserobject. You may need to modify the code to correctly assign theUserobject based on your application's logic. - User
still not working
- Assistant
I apologize for the confusion. The error message suggests that you're trying to assign a value of "56" to the
userfield, but it should be aUserinstance.To resolve this issue, you need to ensure that you're passing a
Userinstance as the value for theuserfield when creating theUpdate_employee_actionobject.Here's an updated version of your signal handler code that should work correctly:
from django.contrib.auth import get_user_model User = get_user_model() @receiver(post_save, sender=Employee_Profile) def create_Actions_records(sender, instance, created, **kwargs): if created: user = instance.user Update_employee_action.objects.create( user=user, rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, ) else: user = instance.user Update_employee_action.objects.create( user=user, rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, )Make sure to import
get_user_modelfromdjango.contrib.authat the top of your file.This code fetches the associated
Userinstance from theEmployee_Profileobject and assigns it to theuserfield of theUpdate_employee_actionobject.If you're still facing issues, please provide the complete traceback of the error, which will help in diagnosing the problem more accurately.
- User
still not working
- Assistant
I apologize for the inconvenience. To further investigate the issue, we need more information about the specific error you are encountering. Could you please provide the complete traceback of the error message that you are seeing? This will help in understanding the exact cause of the problem and finding an appropriate solution.
- User
Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) File "D:\programming\alrawaf-cms_backup-202307-20 - 2\src\orgstructure\views.py", line 152, in update_employee_data if form.is_valid(): File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 201, in is_valid return self.is_bound and not self.errors File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 196, in errors self.full_clean() File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 435, in full_clean self._post_clean() File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\models.py", line 479, in post_clean self.instance = construct_instance( File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\models.py", line 83, in construct_instance f.save_form_data(instance, cleaned_data[f.name]) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields_init.py", line 1035, in save_form_data setattr(instance, self.name, data) File "C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py", line 266, in set raise ValueError(
Exception Type: ValueError at /orgstructure/update_employee_data/31 Exception Value: Cannot assign "'56'": "Employee_Profile.user" must be a "User" instance.
- Assistant
The error message suggests that you are trying to assign a string value ("'56'") to the
userfield of theEmployee_Profilemodel, which is expecting aUserinstance.Looking at your code, the issue is arising in the
update_employee_dataview where you are trying to save the form data for theEmployee_Profileinstance.The root cause of the issue is likely that the value of
instance.userin yourUpdate_employee_actionsignal handler is not aUserinstance, but a string representation of the user's ID. To resolve this, you need to change how you retrieve the user instance from theEmployee_Profile.To fix this issue, update your signal handler as follows:
@receiver(post_save, sender=Employee_Profile) def create_employee_action_records(sender, instance, created, **kwargs): if created: user = instance.user_id # Use the user's ID Update_employee_action.objects.create( user_id=user, rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, ) else: user = instance.user_id # Use the user's ID Update_employee_action.objects.create( user_id=user, rawaf_id=instance.rawaf_id, iqama_no=instance.iqama_no, full_name=instance.full_name, parent=instance.parent, job_name=instance.job_name, oc_level=instance.oc_level, levels_nt_show=instance.levels_nt_show, his_chart=instance.his_chart, on_work=instance.on_work, action_date=datetime.now(), action_creator=instance.action_creator, )In the code above, we assign
instance.user_idto theuser_idfield of theUpdate_employee_actionmodel instead ofinstance.user. This will pass the user's ID instead of the user instance itself.Make sure to update the field assignment in both the
if createdandelseblocks of your signal handler.Give this modified code a try and see if it resolves the issue for you.
- User
still not working
- Assistant
I apologize for the inconvenience caused. To further troubleshoot the issue, we'll need to examine the complete code and the specific details of where the error is occurring.
Please provide the following details:
- The code for your
Update_employee_actionform (if applicable). - The complete traceback of the error message that you are experiencing.
- Any additional relevant information or code that you think might be causing the issue.
With these details, I'll be able to provide more specific guidance to help resolve the problem.
- The code for your
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.