Monu Yadav
Monu Yadav

Reputation: 570

Django Field Error cannot resolve keyword 'is_staff

Cannot resolve keyword 'is_staff' into field. Choices are: dob, experience, id,user, user_id

I get the above error when adding trainer as a Foreign Key to the Subscription model and then accessing any record for Subscription model from admin panel

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)

Upvotes: 1

Views: 207

Answers (2)

Greg Kaleka
Greg Kaleka

Reputation: 2000

You're trying to access an attribute is_staff, which does not exist on the TrainerProfile model. is_staff is an attribute of User, which you reference in your TrainerProfile model's user field.

In order to access this property, you need to "traverse" the relationship from Subscription -> TrainerProfile -> User. Django allows you to do this by using double-underscore notation, like this: some_fk_field__fk_field_attribute.

In your example, you need to change your limit_choices_to option on trainer to traverse the relationship to the user, like so:

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'user__is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)

Upvotes: 1

JPG
JPG

Reputation: 88579

You are referencing the nested relationship in wrong way

class Subscription(models.Model):
    # other fields
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
                                on_delete=models.SET_NULL,
                                limit_choices_to={'user__is_staff': True})

That is, it should be user__is_staff instead of is_staff

Upvotes: 1

Related Questions