Manytomany field custom display objects in Django

Viewed 128

I'm developing a site where I can manually add photographers to the Django adminpanel and then upload the images taken by them.

I used the default User system in Django and added a field here that shows this user is a photographer or not :

from django.contrib.auth.models import AbstractUser

# Create your models here.
class User(AbstractUser):
    is_photographer = models.BooleanField(default=True)

Also, in the model that I need to put the images, I used ManyToMany field for photographers (because these photos may have been taken by several people) :

from registration import User

class Photo(models.Model):
    ...
    photographers = models.ManyToManyField(User)

The problem is that when adding a new image to the admin panel, users who are not photographers and the is_photographer is False, is also displayed in the Photographers. I want only users who are photographers to be displayed and not normal users.

3 Answers

In your admin.py file do this:

class PhotoAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        kwargs['queryset'] = Users.objects.filter(is_photographer=True)
        return super().formfield_for_manytomany(db_field, request, **kwargs)

admin.site.register(Photo, PhotoAdmin)

You can use Django formfield. Django has placed these formfields for different types of fields. To use formfields in ManyToMany relationships, you can use formfield_for_manytomany in the model admin_class.

Try putting this function in the Photo model admin class in the admin.py file of the application where the Photo model is located, and if you don't have a class admin, create one like this:

from .models import Photo
from django.contrib import admin
from registration.models import User


class PhotoAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        kwargs["queryset"] = User.objects.filter(is_photographer=True)
        return super(PhotoAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

admin.site.register(Photo, PhotoAdmin)
Related