How to allow sorting in the Django admin by a custom list_display field, which doesn't have a DB field nor annotatable
Date : March 29 2020, 07:55 AM
will help you The sorting is done at the DB Engine (in an order by clause), so I don't think you will be able to achieve what you want unless you materialize a field in the model. Computed states are not sortable at this point (at least not in the admin interface, if you were using your own interface you could use extra). If the problem were filtering, you could write a custom FilterSpec (which doesn't appear to be documented anywhere, but SO has a good example). class BlahAdmin(admin.ModelAdmin):
... Whatever definitions ...
def queryset(self, request):
return Blah.objects.extra(select={'computed': "count(field_x)"})
|
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further With the help from lazerscience and this post I ended up with the following. The ModelAdmin: class GalleryAdmin(admin.ModelAdmin):
form = GalleryForm
def __init__(self, model, admin_site):
self.form.admin_site = admin_site
super(GalleryAdmin, self).__init__(model, admin_site)
class GalleryForm(ModelForm):
photos = ThumbnailChoiceField(queryset=Photo.objects.all(), label='Photos', widget=MyWidget(), required=False)
def __init__(self, *args, **kwargs):
super(GalleryForm, self).__init__(*args, **kwargs)
rel = ManyToOneRel(self.instance.photos.model, 'id')
self.fields['photos'].widget = RelatedFieldWidgetWrapper(self.fields['photos'].widget, rel, self.admin_site)
|
Custom Filter for Date Field in Django Admin, Django 1.2
Tag : django , By : Mario Tristan
Date : March 29 2020, 07:55 AM
This might help you Now that I have a handle on what I think you want, I'm assuming you have a model that you want to filter by a DateField like: class Position(models.Model):
expiration_date = models.DateField()
...
class Position(models.Model):
expiration_date = models.DateField()
expiration_date.is_expired_filter = True
...
from django.contrib.admin.filterspecs import FilterSpec, DateFieldFilterSpec
from django.utils.translation import ugettext as _
from datetime import datetime, date
class ExpiredFilterSpec(DateFieldFilterSpec):
"""
Adds filtering by future and previous values in the admin
filter sidebar. Set the is_expired_filter filter in the model field
attribute 'is_expired_filter'.
my_model_field.is_expired_filter = True
"""
def __init__(self, f, request, params, model, model_admin, **kwargs):
super(ExpiredFilterSpec, self).__init__(f, request, params, model,
model_admin, **kwargs)
today = date.today()
self.links = (
(_('All'), {}),
(_('Not Expired'), {'%s__lt' % self.field.name: str(today),
}),
(_('Expired'), {'%s__gte' % self.field.name: str(today),
}))
def title(self):
return "Filter By Expiration Date"
# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_expired_filter', False),
ExpiredFilterSpec))
class PositionAdmin(admin.ModelAdmin):
list_filter = ['expiration_date']
|
Django: How to add a custom button to admin change form page that executes an admin action?
Tag : django , By : Amit Battan
Date : March 29 2020, 07:55 AM
may help you . You could take a look at the change_form_template and set it to a custom template of yours and override the response_change method: class MyModelAdmin(admin.ModelAdmin):
# A template for a customized change view:
change_form_template = 'path/to/your/custom_change_form.html'
def response_change(self, request, obj):
opts = self.model._meta
pk_value = obj._get_pk_val()
preserved_filters = self.get_preserved_filters(request)
if "_customaction" in request.POST:
# handle the action on your obj
redirect_url = reverse('admin:%s_%s_change' %
(opts.app_label, opts.model_name),
args=(pk_value,),
current_app=self.admin_site.name)
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
else:
return super(MyModelAdmin, self).response_change(request, obj)
{% if save_on_top %}{% block submit_buttons_top %}{% submit_row %}{% endblock %}{% endif %}
{% if save_on_top %}{% block submit_buttons_top %}{% custom_submit_row %}{% endblock %}{% endif %}
{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}
@register.inclusion_tag('path/to/your/custom_submit_line.html', takes_context=True)
def custom_submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
ctx = {
'opts': opts,
'show_delete_link': (
not is_popup and context['has_delete_permission'] and
change and context.get('show_delete', True)
),
'show_save_as_new': not is_popup and change and save_as,
'show_save_and_add_another': (
context['has_add_permission'] and not is_popup and
(not save_as or context['add'])
),
'show_save_and_continue': not is_popup and context['has_change_permission'],
'is_popup': is_popup,
'show_save': True,
'preserved_filters': context.get('preserved_filters'),
}
if context.get('original') is not None:
ctx['original'] = context['original']
return ctx
{% load i18n admin_urls %}
<div class="submit-row">
{% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %}
{% if show_delete_link %}
{% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %}
<p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p>
{% endif %}
{% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %}
{% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %}
<input type="submit" value="{% trans 'Custom Action' %}" name="_customaction" />
</div>
|
New field of custom AbstractUser not showing up in Django admin despite overriding the default admin
Tag : python , By : Blaise Roth
Date : March 29 2020, 07:55 AM
I wish this helpful for you You need to add introduction field name in fieldsets list of CustomUserAdmin because it is already implemented in the base class which is the reason of not showing the new field in django admin automatically. According to django documentation: from django.utils.translation import gettext, gettext_lazy as _
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['username', 'introduction',]
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'introduction')}),
(_('Permissions'), {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
|