Answer the question
In order to leave comments, you need to log in
How to use custom button in django admin view?
There are several related models.
There is a custom button in the admin panel. I registered the functionality for the button, but at the moment when the button should be displayed correctly according to the plan, it is not displayed. Apparently I'm getting pk for the model (object) incorrectly. Tell me where I made a mistake and how to correctly use the custom button in the admin view.
I'm attaching the code, removed most of the off-topic variables. How it should look like (html code only) and how it is now attached at the end.
class OneRule(model_mixin.OneRule):
is_active = models.BooleanField(default=True)
company = models.ForeignKey(
Company, related_name='variation_rules',
on_delete=models.CASCADE, verbose_name=_('Компания'),)
title_words = models.CharField(
_('My title words'), max_length=250)
city = models.CharField(_('City'), blank=True, max_length=50)
class OneRuleVariation(models.Model):
is_active = models.BooleanField(default=True)
rule = models.ForeignKey(
OneRule, related_name='variations',
on_delete=models.CASCADE, verbose_name=_('One Rule'),)
title_variations = models.CharField(_('Title variations'), max_length=250)
class OneRuleSource(models.Model):
rule_field = models.ForeignKey(
OneRule, related_name='rule_source',
on_delete=models.CASCADE,
verbose_name=_('One Rule source'),)
values = models.CharField(_('Values'), max_length=250)
class OneRuleDestinations(models.Model):
rule_relation = models.ForeignKey(
OneRule, related_name='rule_destinations',
on_delete=models.CASCADE, verbose_name=_('One Rule source'),)
class OneRuleEvents(models.Model):
rule_relation = models.ForeignKey(
OneRule, related_name='rule_events',
on_delete=models.CASCADE, verbose_name=_('One Rule events'),)
count = models.IntegerField()
rollbacked = models.BooleanField(default=False, editable=False)
class OneRuleEventsInline(admin_mixin.OneRuleEventAdmin):
model = OneRuleEvents
extra = 0
readonly_fields = ( 'count',
'rollbacked', '_rollback_button')
@admin.register(OneRule)
class OneRuleAdmin(admin_mixin.OneRuleAdmin):
"""код"""
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path('rollback/<int:pk>', self.rollback_rule, name='rollback_url'),
]
return custom_urls + urls
def rollback_rule(self, request, pk):
rollback_update_rule(pk)
redirect_url = "admin:{}_{}_changelist".format(self.opts.mega_apply, self.opts.OneRule)
return redirect(reverse(redirect_url))
class OneRuleEventAdmin(admin.TabularInline):
def _rollback_button(self, obj):
url = reverse('admin:rollback_url', kwargs={"pk": obj.rule_events.get().pk})
return format_html(
f'<a class="button" href="{url}">Rollback {obj.pk}</a>')
_rollback_button.short_description = _('My button')
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question