in this code class EmployeeProfile(MPTTModel): choice = [ ('نعم', 'نعم'), ('لا', 'لا'),…
- User
in this code 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', limit_choices_to=lambda: {'user': User.objects.get(username='admin').pk}) 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','parent','oc_level']need to make parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', limit_choices_to=lambda: {'user': request.user})
- Assistant
To set the
parentfield to limit choices based on the logged-in user, you can't directly userequest.userdirectly in the model definition because the model is unaware of the request object. However, you can achieve this by using a custom model manager or overriding the form logic.Here's an example of using a custom model manager:
from django.db import models from mptt.models import TreeForeignKey, MPTTModel class EmployeeProfileManager(models.Manager): def get_queryset(self): queryset = super().get_queryset() user = getattr(self.model, 'request_user', None) if user: queryset = queryset.filter(user=user) return queryset class Employee_Profile(MPTTModel): # Other fields here objects = EmployeeProfileManager() parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', limit_choices_to={'user': user} # assuming 'user' is the related field to User model ) # Rest of the codeThen, in your view or wherever you create the instance of
Employee_Profile, you can set therequest_userattribute like this:employee_profile = Employee_Profile() employee_profile.request_user = request.user # Rest of the codeAlternatively, you can limit the choices using a form. Here's an example:
from django import forms from django.db import models from mptt.models import TreeForeignKey, MPTTModel class EmployeeProfileForm(forms.ModelForm): class Meta: model = Employee_Profile fields = '__all__' def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if user: self.fields['parent'].queryset = Employee_Profile.objects.filter(user=user) class Employee_Profile(MPTTModel): # Other fields here parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) # Rest of the codeThen, in your view, pass the
userparameter to the form when initializing:employee_profile_form = EmployeeProfileForm(user=request.user)Note that you need to adjust the code to match your specific requirements and relationships.
- User
Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: user>
- Assistant
Apologies for the confusion. The error is occurring because the
limit_choices_toargument of theTreeForeignKeyexpects a dictionary that specifies the filter conditions.To limit the choices of the
parentfield based on the logged-in user, you can modify thelimit_choices_toargument as follows:from django.db import models from mptt.models import TreeForeignKey, MPTTModel class Employee_Profile(MPTTModel): # Other fields here parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', limit_choices_to={'user__username': 'admin'} # replace 'admin' with the desired username ) # Rest of the codeIn this example, the
limit_choices_toargument filters the choices based on theusernamefield of the relatedusermodel. Replace'admin'with the appropriate username you want to use for the filter.Make sure to replace
'admin'with the actual username you want to filter by.Additionally, if you want to dynamically set the
limit_choices_tobased on the logged-in user, you can use a function instead of a lambda expression:from django.db import models from mptt.models import TreeForeignKey, MPTTModel from django.contrib.auth.models import User def limit_parent_choices(): return {'user__username': 'admin'} # replace 'admin' with the desired username class Employee_Profile(MPTTModel): # Other fields here parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', limit_choices_to=limit_parent_choices ) # Rest of the codeHere, the
limit_parent_choicesfunction returns the filter conditions based on the logged-in user. You can modify the function to return the appropriate filter based on your specific requirements.