Reputation: 23
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 postBlog 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!!
Upvotes: 0
Views: 961
Reputation: 21
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
Upvotes: 0