Django - Admin: list_display TextField - django

I'm trying to display the first 10 characters of a TextField on a list_display.
Is it possible in the admin interface ?

You can define a callable that returns the first 10 characters of the field, and add that to list_display.
More information see the Django docs for list_display.

myapp/admin.py
from django.contrib import admin
from django.utils.text import Truncator
from django.db import models
from .models import Product
def truncated_name(obj):
name = "%s" % obj.name
return Truncator(name).chars(70)
class ProductAdmin(admin.ModelAdmin):
list_display = ['id', truncated_name, 'category', 'timestamp',]
list_display_links = [truncated_name]
list_filter = ['category']
class Meta:
model = Product
You can also override the fields like so:
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size': '20'})},
models.TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40, 'style': 'height: 1.5em;'})},
}

Related

How I can show the table of all user which role is based on specific values

I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value.
I would like to show all user in Django admin panel which role is couple only.
In admin.py:
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from users.forms import UserChangeForm, UserCreationForm
from users.models import EmailConfirmationToken
User = get_user_model()
#admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
I did manage to solve this problem, by defining a variable in my model.py file
called
#models.py
role_couple = models.CharField(max_length=7, default='couple')
role_vendor = models.CharField(max_length=7, default='vendor')
and then i changed the admin.py file to this
#admin.py
list_display = ('role_couple' , 'N1' , 'N2' , 'N3')
another solution is to add default_filters variable:
for example
#admin.py
list_filters = ('role',)
default_filters = { 'role':'couple'}
am sorry if the first one didn't helped you
BG
I got the solution by customizing the queryset in ModelAdmin Class.
#admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
def get_queryset(self, request):
qs = super(UserAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs.filter(role='couple')
return qs

Django-jet admin- add button for each row

I want to create a button that deletes the selected row in the table (1 button per row)
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export.admin import ImportExportMixin
from .models import Applicant
class ApplicantAdmin(ImportExportModelAdmin, admin.ModelAdmin):
list_display = ('Name', 'DOB', 'PhoneNumber', 'Address', 'Batch',
'created_at', 'updated_at',)
list_filter = ('Name', 'Address', 'Batch', 'created_at', 'updated_at',)
list_per_page = 10
# actions = [transferdata, ]
# Register the admin class with the associated model
admin.site.register(Applicant, ApplicantAdmin)
models.py
from django.db import models
from django.utils import timezone
class Applicant(models.Model):
id = models.CharField(max_length=10).primary_key
Name = models.CharField(max_length=50)
DOB = models.CharField(max_length=10)
PhoneNumber = models.CharField(max_length=20)
Address = models.CharField(max_length=200)
Batch = models.CharField(max_length=200)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.Name
I already know django-jet that provides this facility a drop-down menu, but for the whole table (i.e. not for the each row)
This problem by creating a function inside the required admin class.
admin.py
import django.contrib import admin
import import_export.admin import ImportExportModelAdmin
import import_export.admin import ImportExportMixin
import .models import Applicant
class ApplicantAdmin(ImportExportModelAdmin, admin.ModelAdmin):
list_display = ('Name', 'DOB', 'PhoneNumber', 'Address', 'Batch',
'created_at', 'updated_at',)
list_filter = ('Name', 'Address', 'Batch', 'created_at', 'updated_at',)
list_per_page = 10
# actions = [transferdata, ]
#staticmethod
def action_button(self):
# assuming the url is saved as 'button_url'
# enter the url to be parsed when the button will be clicked and name the button
return format_html('<a class="button" href="%s">(name of the button)</a>' % button_url)
# Register the admin class with the associated model
admin.site.register(Applicant, AdminApplicant)
Create a function of the button in the views.py
In the urls.py enter the url (almost the same as in admin class) in urlpatterns of the app and call the function present in views.py

Add css class to all admin form field

I need to assign a boostrap class to all my user's field in Django admin form, I wrote this code but it does not work.
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'class': 'form-control'})},
models.CharField: {'widget': EmailInput(attrs={'class': 'form-control'})},
models.DateField: {'widget': DateTimeInput(attrs={'type': 'date', 'class': 'form-control'})},
models.EmailField: {'widget': EmailInput(attrs={'class': 'form-control'})},
models.BooleanField: {'widget': CheckboxInput(attrs={'class': 'form-control'})},
}
Can you help me?
Your form
#yourapp/forms.py
class YourForm(forms.ModelForm):
class Meta:
model = YourModel
fields = (field1,field2,field3,)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self._meta.fields:
attrs = {'class':'form-control'}
if self.fields[field].widget.__class__.__name__ == "DateTimeInput":
attrs.update({'type':'date'})
self.fields[field].widget.attrs.update(attrs)
Next, admin.py
#yourapp/admin.py
from django.contrib import admin
from .forms import YourForm
from .models import YourModel
class AdminModel(admin.ModelAdmin):
form = YourForm
admin.site.register(YourModel,AdminModel)
You can learn more from the documentation.
If you want to override some of the Field options for use in the admin, please check this for detail: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides. And the most common use of formfield_overrides is to add a custom widget for a certain type of field.

add my own class in admin field django-cms

Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result.
in my model.py I have this
class Entry(models.Model):
TYPES_CHOICES = (
('none', 'not specified'),
('s', 'Series'),
('mb', 'Multiples Bar'),
('b', 'Bar suggestion'),
)
app_config = AppHookConfigField(HealthConfig)
code = models.CharField(blank=True, default='', max_length=250)
url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" )
health_placeholder = PlaceholderField('health_info')
objects = AppHookConfigManager()
def __unicode__(self):
return self.url
class Meta:
verbose_name_plural = 'entries'
and now in my form.py I have this
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['code'].widget.attrs={
'id': 'my_code',
'class': 'code_class',
}
finally my admin.py is like this
from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from .cms_appconfig import HealthConfig
from .models import Entry
from .forms import EntryForm
from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
class EntryAdmin(ModelAppHookConfig, PlaceholderAdminMixin, admin.ModelAdmin):
# pass
fieldsets = (
('General data', {
'fields':('app_config','chart', 'url',('count', 'code', 'start'))
}),
('Suggestion',{
'classes':('collapse', 'suggestion',),
'fields':('url_suggestion',('key1_suggestion_name','key1_suggestion'),('key2_suggestion_name','key2_suggestion'), 'primary_suggestions')
}),
)
list_display =('app_config' ,'url', 'chart');
list_filter = (
'app_config',
)
form = EntryForm
class Media:
js = ('health/js/admin/healthAdmin.js',)
css = {
'all': ('health/css/admin/admin_area.css',)
}
admin.site.register(Entry, EntryAdmin)
any idea is I missing something, after that, I do a migrate of the component again.
Thanks in advance!
You can specify a custom form for admin using the form attribute of ModelAdmin.
So using the example from the docs linked below, that would look like;
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
So in your admin.py you'd need something like;
from .forms import EntryForm
class EntryAdmin(admin.ModelAdmin):
form = EntryForm

Add descriptive text to the right of field in Django admin

I have a DecimalField in my model that I'd like to show up in the admin interface with a unit to the right of the field, like so:
I think if I add help_text to the field, that will show up below the field. Is there a way to specify it to show up to the right?
You can handle it with help_text from the forms, overwrite your field in the form, such as the css.
from django.db import models
from django.contrib import admin
from django import forms
from your.models import Post
class PostForm(forms.ModelForm):
ethanol = forms.FloatField(
label='This is Ethanol',
max_value=10,
min_value=0,
widget=forms.NumberInput(
attrs={
'class': 'whatever',
'style': 'position:relative'
}
),
help_text='<span style="position:absolute;right:0">g/mL</span>'
)
class Meta:
model = Post
fields = '__all__'
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['ethanol', 'id']
admin.site.register(Post, PostAdmin)