1

What I have:

The default django User model with an attached Profile model that, amongst others, contains a ForeignKey to an Office model. So every user in my application is tied to a specific office. And in each office there are several Shifts.

models.py:

class Profile(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    office = models.ForeignKey(Office, on_delete=models.RESTRICT)

class Office(models.Model):
    id = models.AutoField(primary_key=True)
    short_name = models.CharField(max_length=3, default='FRA', null=True, unique=True)
    long_name = models.CharField(max_length=10, default='Frankfurt', null=True, unique=True)

class Shift(models.Model):
    id = models.AutoField(primary_key=True)
    office = models.ForeignKey(Office, on_delete=models.RESTRICT)
    short_name = models.CharField(max_length=5, default="")
    long_name = models.CharField(max_length=20, default="")

What I am trying to do:

Now, in my CreateView I want to limit the available choices in the "shift" field to the ones attached to the office of the current logged in user. I thought about using the limit_choices_to option of ForeignKey, but I can't get my head around how to access the user information within a model? Something like

class Shift(models.Model):
    id = models.AutoField(primary_key=True)
    office = models.ForeignKey(Office, on_delete=models.RESTRICT, limit_choices_to={'office': ???})
    short_name = models.CharField(max_length=5, default="")
    long_name = models.CharField(max_length=20, default="")
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Martin K
  • 33
  • 4
  • You can't do this in a model. You would do this in the view. See here for an example: https://stackoverflow.com/a/47224270/8147165 – michjnich Aug 03 '22 at 12:24
  • Hey, you can write `ModelForm`, pass `request` via `get_form_kwargs()` method to the form, and then filter the field based on user or other field. This is probably what you want to accomplish. – Patryk Szczepański Aug 03 '22 at 12:33
  • Thank you both! Got it working in the proposed way of using `get_form_kwargs()`. Sweet! – Martin K Aug 03 '22 at 12:49

0 Answers0