2

Here's what I'm looking for. In my form I have three fields, all CharFields. Those are Name, Surname and Username. Username should be set as a sum of Name and Surname, so for Name = Joe, Surname = Black, Username = Joe Black.

As the form is displayed, all fields all empty. I'd like it to auto-populate the Username while i'm writing data to a Name or a Surname. The reason of this is that I don't have to fill the Username field, but when I'd like to, I will be able to set it different than Name + Surname.

Is it possible without using jQuery? If so, is there any good tutorial on this?

Gandi
  • 3,522
  • 2
  • 21
  • 31
  • If you want to do it on client-side you should use JavaScript, with or without jQuery. – DrTyrsa Jun 10 '11 at 09:18
  • That's what I was trying to ommit. I remember in some tutorial, I saw about a year ago, there was a way to auto-populate a SlugField, but I somehow can't find it now. – Gandi Jun 10 '11 at 09:27

1 Answers1

6

javascript

<script type="text/javascript" charset="utf-8">

    function updateUsername(){
        first = document.getElementById("first").value;
        last = document.getElementById("last").value;
        document.getElementById("username").value = first+" "+last;
    }

</script>

then you need to give your 3 input fields IDs.

Here's a example

<input type="text" name="some_name" value="" id="first" onkeyup="updateUsername();">
<input type="text" name="some_name" value="" id="last" onkeyup="updateUsername();">
<input type="text" name="some_name" value="" id="username">

Basically when the #first and #last field are typed into it runs the updateUsername() function which gets their values and changes the value of #username to them.

EDIT

If you want to do this with django, edit your model and overwrite the save method.

def save(self):
    if not self.id:
        self.username = self.first + self.last
    super(MODLE_NAME, self).save()

What that'll do is when you use the save() method, it'll take it's first and last properties and update the username value and save it.

dotty
  • 40,405
  • 66
  • 150
  • 195
  • 1
    Actually I've searched for a pure, django solution, with no js. But... this one is so simple, I can clearly give +1. If there won't be any better answer (without using js), I'll accept this one. – Gandi Jun 10 '11 at 10:45
  • You can't do this without javascript. The closest other way to do this the django way, would be to save the model, then auto-generate the username from the first and last names. But that wouldn't give you a "live typing" feel to it. – dotty Jun 10 '11 at 10:53
  • I think, that's pretty all on this topic. Thanks. – Gandi Jun 10 '11 at 11:16
  • 1
    Just a note, when overriding the `save` method, you should pass args like this: `save(self, *args, **kwargs)` and `super(MODEL_NAME, self).save(*args, **kwargs)`. – Etienne Jun 10 '11 at 13:40