Dynamic Foreign Key field

14 views
Skip to first unread message

Andrew Stringfield

unread,
Feb 9, 2022, 3:32:30 PM2/9/22
to Wagtail support
Hello all,

    I have a model that has a foreign key field.  I would like to restrict this field based on the current user.  How can I do this?

-------Here is my Model information:
class base_rucklogs(models.Model):
    date_performed = models.DateField()
    rucker_name = models.CharField(max_length=255)
    ruck_challenge = models.ForeignKey(ChallengePage, on_delete=models.CASCADE, null=True, blank=True)
    miles_rucked = models.DecimalField(max_digits=6, decimal_places=2)

    panels = [
        FieldPanel('date_performed'),
        FieldPanel('rucker_name'),
        FieldPanel('ruck_challenge'),
        FieldPanel('miles_rucked'),
    ]

----------Here is my wagtail_hooks information:
class base_rucklogsAdmin(ModelAdmin):
    model = base_rucklogs
    menu_label = 'Add Ruck Log'  # ditch this to use verbose_name_plural from model
    menu_icon = 'pilcrow'  # change as required
    menu_order = 200  # will put in 3rd place (000 being 1st, 100 2nd)
    add_to_settings_menu = False  # or True to add your model to the Settings sub-menu
    exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view
    list_display = ('date_performed', 'ruck_challenge', 'miles_rucked')
    #list_filter = ('author',)
    #search_fields = ('title', 'author')

# I am fully aware that this shows only the records submitted by the logged in user.
# While I still needed this function, it does not override the Foreign key field.
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        #only show records from the current user
        return qs.filter(rucker_name=request.user)

modeladmin_register(base_rucklogsAdmin)
I do not know where I should override the Foreign key field.
Reply all
Reply to author
Forward
0 new messages