简体   繁体   中英

Custom button in Django Admin page, that when clicked, will change the field of the model to True

I have a sample model in my Django App:

class CustomerInformation(models.Model):
    # CustomerInformation Schema
    name=models.CharField(max_length=200, verbose_name="Name",default="Default Name")
    login_url=models.URLField(max_length=200, verbose_name="Login URL",default="")
    is_test=models.BooleanField(default=False,verbose_name="Test")

I have to create a button on the Django Admin page for each entry of the model (which I have) that says "Test Integration", like this: [Screenshot of admin page

Now once I click the button, the 'is_test' value for that specific CustomerInformation model, should be True. I haven't been able to do that so far. Here's what I have tried so far, thanks to Haki Benita's blog post Blog here :

# admin.py

class CustomerAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        'username',
        'account_actions'
    )

    def get_urls(self):
        urls = super().get_urls()

        custom_urls = [
            url(
                r'^(?P<account_id>.+)/test_integration/$',
                self.admin_site.admin_view(self.test_integration),
                name='test-integration',
            )
        ]
        return custom_urls + urls

    def test_integration(self, request, account_id, *args, **kwargs):
        return self.process_action(
            request=request,
            account_id=account_id
        )

    def process_action(self,request,account_id):
        pass


    def account_actions(self, obj):
        return format_html(
            '<a class="button" href={}>Test Integration</a>',
            reverse('admin:test-integration', args=[obj.pk]),
        )
    account_actions.short_description = 'Account Actions'
    account_actions.allow_tags = True

I realize that I have to do something with the process_action and test_integration methods in this class to execute what I am wanting to do, but as a Django Beginner, I'm kinda lost. Any suggestions?

Thank you so much!!

in your process_action function do a setattr(self, 'is_test_result', True) then override get_form like so

def get_form(self, *arg, **kwargs):
    form = super().get_form(*arg, **kwargs)
    if arg[1] and hasattr(self, 'is_test_result'):
        if self.is_test_result is not None:
            arg[1].is_test = self.is_test_result

            self.is_test_result = None



    return form

in arg[1], is your admin template, you can do an arg[1].save() or let the user click the usual Save or Save and Continue button at the bottom right

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM