Filter a foreignkey field based on logged in user in Django Admin Dashboard

Hello, in this post I am going to be sharing with you the process of filtering  forignkey fields based on current logged in user in django admin dashboard using a basic tutorial Academy project.

Lets say for example we have a basic tutorial academy project with many authors that  are capable of logging into django's admin dashboard to create different tutorials and topics.

The relationship between tutorials and topics is such that a tutorial can have many topcs but each topic can have ony one tutorial assigned to it. The aim is to filter the foreingnkey field of the topics to tutorial model to only show the tutorials created by the logged in user.

Below is the basic structure of the tutorials and topics models.

from django.contrib.auth.models import User
from django.db import models

# Create your models here.


class Tutorials(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=400)
    body = models.TextField()
    publish = models.BooleanField(default=False)
    published_date = models.DateField()
    updated_date = models.DateField(auto_now=True)

    def __str__(self):
        return str(self.title)


class Topics(models.Model):
    tutorial = models.ForeignKey(Tutorials,related_name='tutorial_topic', on_delete=models.CASCADE)
    parent_topic = models.ForeignKey(
        'self',
        verbose_name="Parent topic",
        blank=True,
        null=True,
        on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    date_created = models.DateField(auto_now_add=True)
    body = models.TextField()

    def __str__(self):
        return str(self.name)


Also below is the current settings in admin.py that registers our model to the admin dashboard.

from django.contrib import admin
# Register your models here.
from .models import *


admin.site.register(Tutorials)
admin.site.register(Topics)

To begin, lets set our user field in tutorials model to be automatically assigned on saving to the current logged in user(check my Django admin auto assign field on model save to learn how its done).


To filter the tutorials foreignkey field of topics all you hae to do is follow the steps below

  •  In your admin.py create a new class called TopicsAdmin and specify its model as shown below
class TopicsAdmin(admin.ModelAdmin):
    model = Topics
    extra = 0

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'tutorial':
            kwargs["queryset"] = Tutorials.objects.filter(user = request.user)
            return super().formfield_for_foreignkey(db_field, request, **kwargs)

Formfield_for_foreignkey method sets the tutorial field to be filtered based on the tutorials created by the curent logged in user.

  •  Next step is to register the admin class we just created with our topics admin as shown below
admin.site.register(Topics, TopicsAdmin)

And thats it, now if a user logs in to the admin dashboard and attempt to create a topic the tutorials foreignkey field choices will only contain the previous tutorials created by that specify user.

Conclusion

In conclusion, through this post I have been able to explain with the aid of a basic example how one can filter a foreignkeyfield based on the logged in user in django. As always thanks for reading and you can leave a comment on the post down below if you have any and I will reply you as soon as I can.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
message profile
Ayobami
2023-07-07
thanks a lot for the explanation. it really helped me a lot. keep up the good work
message profile
admin
2023-07-08
You're welcome! I'm glad that my post was helpful to you.

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.