logo
down
shadow

How do I add a custom button next to a field in Django admin?


How do I add a custom button next to a field in Django admin?

Content Index :

How do I add a custom button next to a field in Django admin?
Tag : django , By : Verbal
Date : December 01 2020, 04:55 PM


Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to allow sorting in the Django admin by a custom list_display field, which doesn't have a DB field nor annotatable


Tag : django , By : picamiolo
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


Tag : python , By : joshski
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')}),
    )
Related Posts Related QUESTIONS :
  • Queryset Django - according to parameters date in weight compartment
  • how to convert Django 2.0 url() to path()
  • Signal/Method for every executed sql statement
  • How to sum django model fields
  • django template styntex {% if p.category == "help" %} {% endif %} is not work
  • NGINX 502 bad gateway gunicorn timeout
  • How to pass a variable from a template to a view in Django
  • How to force redirect_uri to use HTTPS with python-social-app?
  • How to restrict Django models from using certain foreign key values?
  • Product items is not iterable from models
  • Removing items from celery_beat doesn't remove them from database schedule
  • Column field is not recognized/not defined
  • AttributeError at has no attribute 'objects'
  • how to Validate Expire date is bigger than start date in Django Model Form
  • Django Application
  • How to get my Django app in a real server?
  • How do I run a unit test against the production database?
  • How to browse (no text editor) .rst files?
  • Filter Queryset in Django inlineformset_factory
  • IPN delivery failed. HTTP error code 403: Forbidden
  • integrating django-paypal
  • Django equivalent for latest entry for each user
  • Writing custom Django form fields and widgets
  • Django queryset to find a char value with filtered out spaces?
  • Django i18n: how to not translate the admin site?
  • apache virtual host to work with django
  • Using django-piston, how can I write out HTTP headers in the response?
  • Error in django url.py?
  • Django: getting the list of related records for a list of objects
  • Edit/show Primary Key in Django Admin
  • How do I list all available context variables?
  • Treebeard admin in Django
  • Django and Secure iCalendar Feed
  • Syncing data between devel/live databases in Django
  • What custom themes are there for Django Admin?
  • ChoiceField or CharField in django form
  • Django and ImageField Question
  • Django crash without message
  • Django: do I need to do HttpResponseRedirect to render a simple string after a POST?
  • modelform "object not callable" error
  • Django model forms
  • Django subprocess
  • Writing validators with Django: How to display Validation Error Message?
  • Image upload to the rich text field from vue to amazon s3 via django REST framework
  • Django: overriding predefined save() method - request is not defined
  • Uploading a CSV or Excel file along with json data through React html form to Django
  • unable to specify custom Django Model from nested app as AUTH_USER_MODEL
  • How to restrict access to DetailView depending on user permission AND MODEL ATTRIBUTE VALUE?
  • path function for URL throwing error when we want to capture an integer or slug paramter
  • Celery task not starting at the start time provided
  • How to add username to the filefield?
  • How to make a correct password encryption in django users?
  • How to show an alert on the success url
  • Python Django - Associating a ForeignKey on users. IntegrityError NOT NULL constraint failed
  • Django Heroku deployment URLconf error. Page not found (404)
  • How to create a dropdown menu in django with selections from created model objects?
  • django-rest returning http 301 status code when calling http delete without trailing slash
  • DRF nested serializer not able to updated nested data
  • Django - needs to have a value for field "id" before this many-to-many relationship can be used
  • Allowing only superuser to call template column - Django
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com