Search code examples
djangoformsauto-populate

Django - How to auto populate form field from two others fields


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?


Solution

  • 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.