Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

in this code class EmployeeProfile(MPTTModel): choice = [ ('نعم', 'نعم'), ('لا', 'لا'),…

  1. 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})

  2. Assistant

    To set the parent field to limit choices based on the logged-in user, you can't directly use request.user directly 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 code
    

    Then, in your view or wherever you create the instance of Employee_Profile, you can set the request_user attribute like this:

    employee_profile = Employee_Profile()
    employee_profile.request_user = request.user
    # Rest of the code
    

    Alternatively, 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 code
    

    Then, in your view, pass the user parameter 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.

  3. User

    Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: user>

  4. Assistant

    Apologies for the confusion. The error is occurring because the limit_choices_to argument of the TreeForeignKey expects a dictionary that specifies the filter conditions.

    To limit the choices of the parent field based on the logged-in user, you can modify the limit_choices_to argument 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 code
    

    In this example, the limit_choices_to argument filters the choices based on the username field of the related user model. 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_to based 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 code
    

    Here, the limit_parent_choices function 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.