admin.py
class authUserMenu(admin.ModelAdmin):
list_display = ["__str__", "user_id", "menu_id","is_active"]
class Meta:
Model = AuthUserMenu
admin.site.register(AuthUserMenu, authUserMenu)
models.py
class AuthUserMenu(models.Model): # USER VS MENU relation
user = models.ForeignKey(AuthUser,on_delete=models.DO_NOTHING,blank=True, null=True)
menu = models.ForeignKey(Menu,on_delete=models.DO_NOTHING,blank=True, null=True)
is_active = models.BooleanField(default=False)
class Meta:
db_table = 'auth_user_menu'
ordering = ['user','menu','is_active']
def __str__(self):
# return self.id
return str([self.user.username,'>>>>>>', self.menu.menu_name])
When filtering with username should only show some menus under some condition... How can I achieve this?
Suppose here for the username 4 menu is showing. But it should show 2 menu. This may obtain by db querying.
This is how A user related to menus
CodePudding user response:
Sorry But the filter's you are applying for admin is only valid for how they are Going to look on the admin panel it won't customize your model properties and in order to achieve that you need to create a filter as eg ...
user = self.get_object()
articles = Article.objects.filter(author_id)
Something like that
CodePudding user response:
You need some JS to call a view asyncronously every time the user
field is updated and change the options in the menu
field with the response. The package django-autocomplete-light
is a popular choice for exactly this, especially updating field values from other fields is relevant
forms.py
class AuthUserMenuForm(forms.ModelForm):
class Meta:
model = AuthUserMenu
fields = '__all__'
widgets = {
'menu': autocomplete.ModelSelect2(
url='menu-autocomplete',
forward=['user']
)
}
views.py
class MenuAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = Menu.objects.all()
user = self.forwarded.get('user', None)
if user:
# Not clear exactly what your filter would be here so left it but you have user available
qs = qs.filter(...)
return qs
urls.py
urlpatterns = [
...
path('menu-autocomplete/', views.MenuAutocomplete.as_view(), name='menu-autocomplete'),
...
]
class AuthUserMenuAdmin(admin.ModelAdmin):
form = AuthUserMenuForm
list_display = ["__str__", "user_id", "menu_id", "is_active"]
admin.site.register(AuthUserMenu, AuthUserMenuAdmin)