Hi there I'm trying to achieve the auto slug function via JS in my form, and following is my code.
My model:
class Sponsor(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=150)
My form:
class SponsorForm(ModelForm):
class Meta:
model = Sponsor
fields = ['name', 'slug', 'image', 'phone', 'website', 'address', 'city', 'state', ]
exclude = ('created_by', )
As you can see, I want to show the slug field to the user and he can edit it, but before edit I would like to set my slug automatically based on what he is typing in field "name". In Admin is like that.
Searching on internet, I found that Django core has this file: urlify.js , what is awesome. What I have done so far is:
<script src="{% static "js/urlify.js"%}"></script>
<script type="text/javascript">
$(function() {
$( "#id_name" ).keyup(function() {
$("#id_slug").val(URLify($("#id_name").value, 150));
});
});
</script>
All I get are these erros in console
Error 1:
Uncaught SyntaxError: Invalid regular expression: /�|O|U|o|u|a|?|d|e|p|s|t|f|G|T|S|F|i|I|g|A|c|n|r|C|D|E|N|R|l|z|L|Z|k|K/: Nothing to repeat
Error 2:
Uncaught TypeError: Cannot read property 'replace' of undefined
Any help or ideas will be appreciated.
What this amounts to is trusting the client (i.e. allowing the browser to submit a field over which you have no control), which is never a good idea. This means a malicious user could bypass your code and pass any value in for the slug of your model, which is unlikely to be desired behavior.
Instead, do this on the server: Override the model's save(...)
method to first set the slug on your model based on its name and then continue the normal save method via super
to pass execution back to Django.