# Populate logged on username in a model in a form

**URL:** <https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334>\
**Category:** Forms & APIs\
**Created:** [August 24, 2023, 9:21am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334 "2023-08-24T09:21:38Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 9:21am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/1 "2023-08-24T09:21:38Z")

</div>

Hi there,

I have a very simple requirement to populate a field in a form with a current username.

I am a django beginner hence my code might not look the best.

models.py

```auto
class PII(models.Model):
    username = models.CharField(max_length=128, editable=False)
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)
    created_on = models.DateField(auto_now_add=True)

    def get_absolute_url(self):
        return reverse('page:index')

```

and my views.py

```auto
class PIIView(CreateView):
    model = PII
    fields = ' __all__'

    def get_context_data(self, **kwargs):
        context = super(PIIView, self).get_context_data(**kwargs)
        context['username'] = self.request.user
        return context

```

I have pulled it from SO but it does not populate the username:  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/e/ee6dc8444164747931648beae928b51232628e6c.png)

I have seen a similar topic “assign username to field in models.py” however I am pretty sure it will not work in my case, because the table in question is on a separate database and django does not allow FKs between databases.

Is there a way for django to be aware of which user is logged on and filling in that field for me?

Thanks

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [August 24, 2023, 9:32am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/2 "2023-08-24T09:32:51Z")

</div>

> [@cherkie](#):
>
> `context['username'] = self.request.user`

here self.request.user is a object of user model instance if you want username than use self.request.user.username also you can access any field of user model like self.request.user.first\_name, self.request.user.email, etc.

---

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 9:55am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/3 "2023-08-24T09:55:23Z")

</div>

Thanks, I have changed it to user.username but it did not work. Might it be that there’s something wrong in the class based view?

Just checked and I am logged on as admin.

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [August 24, 2023, 10:10am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/4 "2023-08-24T10:10:44Z")

</div>

Can you share how you are accessing these context data within template

---

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 10:14am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/5 "2023-08-24T10:14:47Z")

</div>

ummm, I am not, I don’t think?

```auto
                    <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        {% include 'app/form-template.html' %}
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-success">Submit</button>
                            </div>
                        </div>
                    </form>

```

and that’s form-template.html

```auto
{% for field in form %}
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <span class="text-danger small">{{ field.errors }}</span>
        </div>
        <label class="control-label col-sm-2">{{ field.label_tag }}</label>
        <div class="col-sm-10">{{ field }}</div>
    </div>
{% endfor %}

```

it looks like this:

![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/c/c5adf28d49be2a3118ab6fc54721b932212c4972.png)

Granted, this is a rough sketch, but I don’t even need the user to be aware of the username being populated, can this work this way?

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [August 24, 2023, 10:23am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/6 "2023-08-24T10:23:06Z")

</div>

> [@cherkie](#):
>
> ```auto
> def get_context_data(self, **kwargs):
> context = super(PIIView, self).get_context_data(**kwargs)
> context['username'] = self.request.user
> return context
> 
> ```

This part here sends the context data to your template i.e if you access {{username}} in template you will get it rendered however it does not effect your form try it.

---

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 10:23am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/7 "2023-08-24T10:23:50Z")

</div>

> [@addwebsolution](#):
>
> however it does not effect your form try it.

I am not sure I understand this bit, how can I try it?

---

<div class="post-metadata">

**Author:** ![addwebsolution](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/addwebsolution/32/23762_2.png) [@addwebsolution](https://forum.djangoproject.com/u/addwebsolution)\
**Post date:** [August 24, 2023, 10:27am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/8 "2023-08-24T10:27:56Z")

</div>

Just put {{username}} in your template save it and reload username will be printed.  
If you want to work around the form you need to override get\_form() method instead of get\_context\_data()

---

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 10:28am UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/9 "2023-08-24T10:28:32Z")

</div>

ok, I will read up on the get\_form() method. thanks

---

<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:** [August 24, 2023, 1:18pm UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/10 "2023-08-24T13:18:48Z")

</div>

The first thing I’d check is to see whether you’re actually logged on to Django when you’re accessing that page. The page is not protected by [`LoginRequiredMixin`](https://docs.djangoproject.com/en/4.2/topics/auth/default/#the-loginrequiredmixin-mixin), so you may be accessing it anonymously.

Also, it may be easier to add a print statement or two in that function to see what the view thinks the situation is at that point. Perhaps adding both `print(self.request.user)` and `print(self.request.user.username)` may provide some insight.

---

<div class="post-metadata">

**Author:** ![cherkie](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cherkie/32/15558_2.png) [@cherkie](https://forum.djangoproject.com/u/cherkie)\
**Post date:** [August 24, 2023, 1:41pm UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/11 "2023-08-24T13:41:18Z")

</div>

Hi Kevin,

Thank you for replying. I have managed to partially solve it by doing the following:

forms.py

```auto
class PIIForm(forms.ModelForm):

    class Meta:
        model = PII
        fields = ' __all__'

```

views.py

```auto
class PIIView(View):
    form_class = PIIForm
    template_name = 'app/pii_form.html'

    def get(self, request):
        form = self.form_class(initial={'username': get_user(request)})
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            f = form.save(commit=False)
            f.save()
            return redirect('warszawa:index')
        return render(request, self.template_name, {'form': form})

```

However one thing I cannot solve which is make the `username` field not editable by the user. When I use `fields.disabled` it does not get passed by POST request, when I use `fields.readonly` it does nothing at all.

However my initial question, which is to populate the logged on username works.

Alternatively I have managed to do it without ModelForm entirely:

```auto
 class PIIView(CreateView):
     model = PII
     fields = ' __all__'

     def get_initial(self):
         return {"username": self.request.user.username}

```

With the same caveats as above re: making the field non editable.

---

<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:** [August 24, 2023, 7:40pm UTC](https://forum.djangoproject.com/t/populate-logged-on-username-in-a-model-in-a-form/23334/12 "2023-08-24T19:40:11Z")

</div>

I’m not sure I understand what the issue is here. If it’s not editable, why should you care if it’s not being returned by the post?
