Reputation: 71
I have a Detail
Model which has a ForeignKey of the default User
Model of Django. It works fine, but I want the ForeignKey to be attached to only those users which are neither staff nor superuser.
My Detail
model is below:
class Detail(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50)
skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.")
internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.")
programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of 25.")
mid_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(45)], verbose_name="Mid_Term Marks (of this subject, in numbers)", help_text="Enter the total mid-term marks of this subject, the student obtained out of 45.")
final_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(90)], verbose_name="Final_Term Marks (of this subject, in numbers)", help_text="Enter the total final-term marks of this subject, the student obtained out of 90.")
def __str__(self):
return f'{self.user.username}-{self.subject}'
I want something like below:
user = models.ForeignKey(User, on_delete=models.CASCADE, filter(not user.is_superuser, not user.is_staff))
But it does not work, anyone know how can I accomplish it?
Upvotes: 0
Views: 63
Reputation: 2130
There're multiple solutions, One of them is.
def is_superuser(user):
return user.is_superuser ## customize as needed
class Detail(models.Model):
...
user = models.ForeignKey(User, on_delete=models.CASCADE, validators=[is_superuser])
Upvotes: 1
Reputation: 109
try using "limit_choices_to" argument in the ForeignKey. You can read more about it in the below link. https://kite.com/python/docs/django.db.models.ForeignKey
Hope it helps!!
Upvotes: 1