# Why am I overwriting my inputting user?

**URL:** <https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895>\
**Category:** Using Django\
**Created:** [October 21, 2020, 5:45am UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895 "2020-10-21T05:45:59Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![j-p-d](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/j-p-d/32/1943_2.png) [@j-p-d](https://forum.djangoproject.com/u/j-p-d)\
**Post date:** [October 21, 2020, 5:45am UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/1 "2020-10-21T05:45:59Z")

</div>

Apparently, every time someone adds a new user to my app they seem to be overwriting their information in the User table with the new person’s. Why?

I don’t use a registration page per se; I have a logged in person ‘registering’ others with all this other information that goes in to User, Profile, Location and Human\_notes tables.

I have an input page made of several forms that comprise these several models and here is my view method:

````auto
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        #human_form = HumanForm(request.POST, request.FILES, instance=request.user.profile)
        profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
        location_form = LocationForm(request.POST, request.FILES)
        human_notes_form = HumanNotesForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid() and location_form.is_valid() and human_notes_form.is_valid():
            location_form.save()
            user_form.save()  
            usr_curr = User.objects.last() #latest('id')
            prf = profile_form.save(commit=False)
            prf.user = usr_curr
            prf.intaker = request.user 
            # this is to ID the signed in person who is registering the new user...
            loc_curr = Location.objects.last()
            loc_curr_id = loc_curr.id
            prf.location = loc_curr
            profile_form.save()
            messages.success(request, f"User Profile data was saved successfully.")
            humnote = human_notes_form.save(commit=False)
            humnote.intaker = request.user
            humnote.user = usr_curr
            human_notes_form.save()
            messages.success(request, f"Human data was saved successfully.")
            return redirect('/intake/humans')
        else:
            context = {
                'user_form': user_form,
                'profile_form': profile_form,
                'location_form': location_form,
                'human_notes_form': human_notes_form,
            }
    else:
        context = {
            'user_form': UserForm,
            'profile_form': ProfileForm,
            'location_form': LocationForm,
            'human_notes_form': HumanNotesForm,
        }
    return render(request, 'intake/human-add.html', context)```

My User model is the default one (I just learned too late I should have done a custom one) and I have a Profile Model that has a OneToOne key to User, and 

```class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    intaker = models.ForeignKey(User, default=None, on_delete=models.CASCADE, related_name='profiles', null=True, blank=True,) 
    location = models.OneToOneField('Location', on_delete=models.CASCADE, null=True, related_name='+')
    ...
    @receiver(post_save, sender=User)  
    def create_user_profile(sender, instance, created, **kwargs):
         if created:
             Profile.objects.create(user=instance)

    @receiver(post_save, sender=User) 
    def save_user_profile(sender, instance, **kwargs):
         instance.profile.save()

    def __str__ (self):
        return "%s %s %s" % (self.id, self.user, self.phn1)```
    
Thanks for any guidance!
````

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 21, 2020, 12:51pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/2 "2020-10-21T12:51:11Z")

</div>

Just a note for future reference - when you post code here, please enclose it between lines consisting of only three backtick - ` characters. That means you’ll have one line of ```, then your code, then another line of ```. This preserves the formatting of the code making it a lot easier to read - especially with `if` statements where indentation is critical.

example:

````auto
# The line above this is ```
def function(self):
    return self
# The line after this is ```

````

If you can, please edit your post to put the ``` before and after the code.

Ken

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [October 21, 2020, 1:20pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/3 "2020-10-21T13:20:50Z")

</div>

I suspect the problem is around a lack of understanding with the model form’s save function. You may want to check out the [documentation](https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#the-save-method).

If my assumptions are correct this block of code is the issue:

> [@j-p-d](#):
>
> prf = profile\_form.save(commit=False)  
> prf.user = usr\_curr  
> prf.intaker = request.user  
> loc\_curr = Location.objects.last()  
> loc\_curr\_id = loc\_curr.id  
> prf.location = loc\_curr  
> profile\_form.save()

Rather than using the instance returned by `profile_form.save(commit=False)` in this case, try the following:

```
profile_form.instance.user = usr_curr
profile_form.instance.intaker = request.user
# this is to ID the signed in person who is registering the new user…
loc_curr = Location.objects.last()
loc_curr_id = loc_curr.id
profile_form.instance.location = loc_curr
profile_form.save()

```

If you want to keep with `save(commit=False)` here’s what you need:

```
prf = profile_form.save(commit=False)
prf.user = usr_curr
prf.intaker = request.user
loc_curr = Location.objects.last()
loc_curr_id = loc_curr.id
prf.location = loc_curr
prf.save()
profile_form.save_m2m()

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 21, 2020, 2:13pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/4 "2020-10-21T14:13:48Z")

</div>

In addition to @CodenameTim response above, there’s also this issue:

> [@j-p-d](#):
>
> ```auto
> if request.method == 'POST':
> user_form = UserForm(request.POST, instance=request.user)
> #human_form = HumanForm(request.POST, request.FILES, instance=request.user.profile)
> profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
> 
> ```

You mentioned that you’ve got a person performing the registrations who is _not_ the person being registered.

However, in your UserForm and ProfileForm retrievals above, you’re setting the instance to request.user - which is the person who is actually submitting the form and not the person for whom the request is being submitted. Since you’re setting the variable `profile_form` to the profile for the person using that page, that’s the profile being updated.

Ken

---

<div class="post-metadata">

**Author:** ![j-p-d](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/j-p-d/32/1943_2.png) [@j-p-d](https://forum.djangoproject.com/u/j-p-d)\
**Post date:** [October 21, 2020, 5:43pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/5 "2020-10-21T17:43:53Z")

</div>

Hey, Thanks Ken for the posting guidance… and Tim for the tip. That seems to have worked as I see the new listings in the db with no overwrites!

I was thinking it was maybe using last() to get the last id used…

```auto

```

I am admittedly new to Django and had not seen this syntax:

```auto
profile_form.instance.user

```

Why use .instance?

That save\_m2m() threw me for a second, the docs are not clear, I guess you are supposed to use that with forms even if there is no many to many relation in the models (none are here)?

---

<div class="post-metadata">

**Author:** ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)\
**Post date:** [October 21, 2020, 6:01pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/6 "2020-10-21T18:01:07Z")

</div>

Here’s my opinion:

Using `.instance` will give you access to the model instance that the form is operating on. It’s partially a matter of preference and what you need to do. Your usage isn’t complicated so you have a number of options available to you.

The `save_m2m()` is only required if you have ManyToManyField references on the form that you would need to save after calling `form.save(commit=False)`. If you don’t have any, it’s not necessary. However robust code should be prepared for the future. Using that as a goal I’d recommend against using `.save(commit=False)` and saving the instance afterwards. If you were to use that approach, you’d risk adding a new field to the form and missing that the saves aren’t taking place because of the missing follow-up `save_m2m()` call.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [October 21, 2020, 6:01pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/7 "2020-10-21T18:01:50Z")

</div>

A form is different from a model. A form is an internal representation of what you see in the browser. A model is the internal representation of what’s in your database.

When you’re working with model forms, the `instance` attribute is a reference to the model associated with that instance of the form. Setting `profile_form.user` is overwriting the form field - it doesn’t affect the model. Since you want to change the model, you need the model associated with that form - `profile_form.instance`.

Regarding the save\_m2m - from the [`save()`](https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#the-save-method) docs:

> Calling `save_m2m()` is only required if you use `save(commit=False)` . When you use a `save()` on a form, all data – including many-to-many data – is saved without the need for any additional method calls.

---

<div class="post-metadata">

**Author:** ![j-p-d](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/j-p-d/32/1943_2.png) [@j-p-d](https://forum.djangoproject.com/u/j-p-d)\
**Post date:** [October 21, 2020, 7:23pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/8 "2020-10-21T19:23:30Z")

</div>

Ken, VERY helpful insight - and apparently hard to find…

Thank you!!

---

<div class="post-metadata">

**Author:** ![j-p-d](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/j-p-d/32/1943_2.png) [@j-p-d](https://forum.djangoproject.com/u/j-p-d)\
**Post date:** [October 21, 2020, 7:24pm UTC](https://forum.djangoproject.com/t/why-am-i-overwriting-my-inputting-user/4895/9 "2020-10-21T19:24:08Z")

</div>

Thanks for the guidance!
