Django admin field display - django

This is my Device that I registered in admin.py:
#admin.register(Device)
class DeviceAdmin(admin.ModelAdmin):
search_fields = ["device_type","serial_number","in_use_by","brand","model","type_number","mac_address"]
list_display = ("device_type","serial_number","in_use_by","brand","model","type_number","mac_address","invoice",)
list_filter = ("device_type","in_use_by","brand",)
This is my Device model in models.py
class Device(models.Model):
device_type = models.ForeignKey(DeviceType,to_field='device_type')
serial_number = models.CharField(max_length=200,unique=True)
in_use_by = models.ForeignKey(User,to_field='username')
brand = models.CharField(max_length=200,default="-", null=False)
model = models.CharField(max_length=200,default="-", null=False)
type_number = models.CharField(max_length=200,blank=True,null=True, default = None)
mac_address = models.CharField(max_length=200,blank=True,null=True, default = None)
invoice = models.BinaryField(blank=True)
This is my form class from forms.py
class ReturnForm(forms.ModelForm):
class Meta:
model = Device
fields = "__all__"
widgets = {"device_type": forms.Select(attrs={"class":"custom-select col-sm-4"})}
exclude = ("serial_number","in_use_by","brand","mac_address","type_number","model","invoice",)
Now, when I view my admin panel, the invoice gets displayed as a column name in the panel. But, when I view an object in more detail by clicking it, the invoice field is not displayed.
What is the problem that has occured?
How can I resolve this issue?
Requesting immediate help.

BinaryField can not be used in a ModelForm, and thus I suspect it also can't be displayed in the admin's change form. You can consult the documentation on BinaryField here: https://docs.djangoproject.com/en/2.0/ref/models/fields/#binaryfield .
Also note the warning about abusing BinaryField to store files in the database.

Related

Django TabularInline and field from related models

using django admin on an existing database i set up a many to many relation between "Contact" and "Groupe" based on a intermediate model "Contactgroup".
In the "Group" Admin form i add a tabular in line to show all Contactgroup. It's OK but i get on error while adding fields from related Contact.
model.py
class Contact(models.Model):
id = models.IntegerField(primary_key=True)
e_mail = models.TextField()
...
class Contactgroup(models.Model):
id = models.IntegerField(primary_key=True)
id_contact = models.ForeignKey(Contact, on_delete=models.CASCADE,db_column="id_contact",
blank=False, null=False, verbose_name='Contact')
id_groupe = models.ForeignKey(Groupe, on_delete=models.CASCADE,db_column="id_groupe",
blank=False, null=False, verbose_name='Groupe')
admin.py
class MyContactgroupInline(admin.TabularInline):
model = Contactgroup
fields = ['id','id_contact']
MyGroupeModelAdmin.inlines = [MyContactgroupInline,]
Then i try to add the Contact e_mail field :
class MyContactgroupInline(admin.TabularInline):
model = Contactgroup
fields = ['id','id_contact', 'id_contact__e_mail']
MyGroupeModelAdmin.inlines = [MyContactgroupInline,]
I get :
Unknown field(s) (id_contact__e_mail) specified for Contactgroup
i finnaly used a new method in class MyContactgroupInline(admin.TabularInline):
#admin.display(description='E-mail')
def getEmail(self, item):
return item.id_contact.e_mail

How can I customize filtering in DJango Admin?

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])
In my Django admin panel
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
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)
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

DRF ManytoMany filtering on related model, in subquery?

There are two models, a Page model and a Banner model, which are manyToMany related.
The parameters API is twitched, which returns a list of pages and banners for each page. The Banner model has a field is_show by which you need to additionally filter the list of banners, i.e. in the admin panel, the banner can be selected for the model, but if is_show = False, then you do not need to return it to the API.
views
class PagesListView(generics.ListAPIView,
viewsets.GenericViewSet):
queryset = Page.objects.all()
serializer_class = PageSerializer
models
class Banner(models.Model):
title = models.CharField(verbose_name='Заголовок', max_length=255, null=True, blank=True)
is_show = models.BooleanField(verbose_name='Управление отображением', null=False)
pages = models.ManyToManyField(
Page, blank=True, related_name='banners')
class Page(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
serializers
class BannerSerializer(serializers.ModelSerializer):
class Meta:
model = Banner
fields = '__all__'
class PageSerializer(serializers.ModelSerializer):
banners = BannerSerializer(read_only=True, many=True)
class Meta:
model = Page
fields = '__all__'
The question is how to filter Banner by is_show field?
If you just override the queryset for the view like this:
queryset = Page.objects.filters(banners__is_show=True)
then this is not the desired behavior. In this way, I am filtering the Page list, and I need to "wedge" into filtering the Banner list.
You can do it using related_name with prefetch_related
For ex:
queryset = Page.objects.all().prefetch_related(
Prefetch('banners', queryset=Banner.objects.filter(is_show=True)))

Pass request user to modelform in Django

I have a model where is save one of the groups of the user in my model.
Because user can be member of different groups i need to update the Selection field in my Form depending on the request.user.groups.all() queryset.
I tried to pass the initial variable to my form but this was ignored.
Any hint how to deal with this problem?
EDIT:
My view:
form = CoronaEventModelForm(request.POST or None, initial={'group': request.user.groups.all()})
my model:
user = models.ForeignKey(curr_User, default=1, null=True, on_delete=models.SET_DEFAULT, related_name='group')
group = models.ForeignKey(Group, on_delete=models.CASCADE)
my form:
class CoronaEventForm(forms.Form):
user = forms.CharField()
group = forms.CharField()
title = forms.CharField()
description = forms.CharField()
slug = forms.SlugField()
event_date = forms.DateField()
class CoronaEventModelForm(forms.ModelForm):
class Meta:
model = CoronaEvent
fields = ['group', 'title', 'description', 'slug', 'event_date']
it works with normal text fields but not with the group field.
solved it by adding a init function to my form and passing the object during instantiation of the form.

How do you display fields from a related model in admin.py?

I have the following models:
class Property(models.Model):
user = models.ForeignKey(User)
id = models.CharField(max_length=20, null=True)
class Property_Value(models.Model):
id = models.ForeignKey(Property)
amount = models.DecimalField(max_digits = 10, decimal_places
How do I access the Property_Value.amount via Property on the admin page?
I have this so far...
class PropertyAdmin(admin.ModelAdmin):
list_display = ('id', 'user', 'property_value')
def property_value(self, obj):
return obj.id.amount
class Meta:
model = Property
admin.site.register(Property, PropertyAdmin)
You're interacting, in that instance, with a Property object (since you defined that in the Meta) - syntax is the same as elsewhere in Django. So it would be obj.property_value.amount. If you're using PyCharm, you can get autocomplete for the field by telling PyCharm what 'obj' is, like so:
def property_value(self, obj: Property):