Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django- run a script from admin

Tags:

python

django

I would like to write a script that is not activated by a certain URL, but by clicking on a link from the admin interface. How do I do this? Thanks!

like image 475
rawnd Avatar asked Dec 23 '22 12:12

rawnd


1 Answers

But a link has to go to a URL, so I think what you mean is you want to have a view function that is only visible in the admin interface, and that view function runs a script?

If so, override admin/base_site.html template with something this simple:

{% extends "admin/base.html" %}
{% block nav-global %}
  <p><a href="{% url your-named-url %}">Do Something</a></p>
{% endblock %}

This (should) put the link at the top of the admin interface.

Add your url with named pattern to your urls.py

Then just make a normal django view and at the top of the view check to make sure the user is superuser like this:

if not request.user.is_staff:
    return Http404

That will prevent unauthorized people from accessing this view.

Next, in your view after the above code, just run the script.

Do that with Python's subprocess module, for example:

from subprocess import call
retcode = call(["/full/path/myscript.py", "arg1"])
like image 183
Van Gale Avatar answered Jan 08 '23 08:01

Van Gale