7

is there a way to get the same results of using pre-populated fields in django's admin site for slug fields in a standard modelform

Llanilek
  • 3,386
  • 5
  • 39
  • 65

2 Answers2

10

Well django is open source, so if you want to replicate certain behaviour you can read the code and pick and chose what you like. For instance, you can see that contrib.admin uses a script called urlify.js to do the dynamic slugging, with usage something like this:

<script type="text/javascript" src="/admin-media/js/urlify.js"></script>
<script type="text/javascript">
document.getElementById("id_title").onkeyup = function() {
    var e = document.getElementById("id_slug");
    if (!e._changed) { e.value = URLify(document.getElementById("id_title").value, 50); }
}
</script>

... depending of course on where your admin media is served from (mine is from "/admin-media/")

Or if you're happy to do your slugifying in your view, you can use the function that's used in django.template as the slugify filter: django.template.defaultfilters.slugify.

ozan
  • 9,285
  • 4
  • 30
  • 27
  • 1
    To bring up-to-date: * Path for the admin javascript is `/static/admin/js/urlify.js` or in the template with the static template tag `{% static 'admin/js/urlify.js' %}` * `URLify(s, num_chars, allowUnicode)` now allows for Unicode, so you need to add `true`/`false` to the URLify function call. – Chad Feb 28 '18 at 14:27
  • 1
    Also, will need to include an additional script `/static/admin/js/vendor/xregexp/xregexp.min.js` – Chad Feb 28 '18 at 19:29
-1
<script type="text/javascript" src="/media/js/urlify.js"></script>

 

var slug = document.getElementById("id_slug").value;

document.getElementById("id_name").onkeyup = function() {
    if (slug == '') {
        document.getElementById("id_slug").value = URLify(document.getElementById("id_name").value, 50);
    }
}
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123