'Getting the error: This field is required when update user

I'm trying to update a user profile using two forms the problem is that when I click to update I get the following error:

“<ul class="errorlist">
<li>username<ul class="errorlist"><li>This field is required.</li>
</ul>
 ”

My model module is the following:

# user.models
from django.contrib.auth.models import AbstractUser
from django.db import models

from model_utils.models import TimeStampedModel
from localflavor.br.models import BRPostalCodeField, BRStateField, BRCNPJField, BRCPFField


class User(AbstractUser):
    class Roles(models.IntegerChoices):
        SUPER = 0
        COMPANY = 1
        UNITY = 2
        STAFF = 3

    picture = models.ImageField(blank=True, null=True)
    role = models.IntegerField(choices=Roles.choices, default=Roles.STAFF)


class Staff(TimeStampedModel):
    user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    unity = models.ForeignKey(Unity, related_name="staff", on_delete=models.CASCADE)
    cpf = BRCPFField("CPF")

    class Meta:
        verbose_name: str = 'Staff'
        verbose_name_plural: str = 'Staff'
        ordering = ("-created",)

    def __str__(self):
        if f"{self.user.first_name} {self.user.last_name}".strip():
            return f"{self.user.first_name} {self.user.last_name}"
        return str(self.user.username)

And my user forms looks like:

#user.forms

class UserModelForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'is_active']


class StaffModelForm(forms.ModelForm):
    class Meta:
        model = Staff
        fields = ['cpf', 'unity']
        widget = {
            'cpf': forms.TextInput(attrs={'class': "form-control", 'placeholder': 'Primeiro Nome', }),
            'unity': forms.EmailInput(attrs={'class': "form-control", 'placeholder': '[email protected]', }),
        }

with the following view:

#views
…
def update_staff(request: HttpRequest, pk: int) -> HttpResponse:
    instance: Staff = get_object_or_404(Staff, pk=pk)  # get staff instance
    template_name = 'pages/staff_update_form.html'  # use this template
    if request.method == "POST":
        profile_form = user_forms.StaffModelForm(request.POST, instance=instance)
        user_form = user_forms.UserModelForm(request.POST, request.FILES, instance=instance.user)

        print(user_form.is_valid())
        print(user_form.errors)
        print(profile_form.is_valid())
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, 'Your profile is updated successfully')
            return redirect(to='pages:dashboard')

    context = dict(profile_form=user_forms.StaffModelForm(instance=instance),
                   user_form=user_forms.UserModelForm(instance=instance.user))
    return render(request, template_name=template_name, context=context)

Print output:

False
<ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul
></li></ul>
True

and HTML:


{% load crispy_forms_tags %}
{% if user_form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
    <div id="form_errors">
        {% for key, value in user_form.errors.items %}
        <strong>{{ value }}</strong>
        {% endfor %}
    </div>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
{% endif %}
<div class="py-5 text-center">
    <span class="material-icons" style="height: 48px; width: auto; font-size: 48px;">people_alt</span>
    <h1 class="h3 mb-3 fw-normal">Atualize aqui os dados do usuário!</h1>
</div>
<form class="form-signin" method="POST" enctype="multipart/form-data">

    <div class="form-group">
        <div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
            <div class="col-md-8 col-lg-12">
                {% crispy profile_form %}
            </div>
        </div>
        <div class="row g-8 my-auto mx-auto" style="padding-left: 12%; padding-right: 12%;">
            <div class="col-md-8 col-lg-12">
                {% crispy user_form %}
            </div>
        </div>
        <div class="col-md-12 col-lg-12">
            <br>
            <div class="modal-footer">

                <a href="{% url 'pages:dashboard' %}" class="btn btn-warning mb-2 type='button'">Cancel</a>
                <button class="btn btn-primary mb-2" type="submit">Update</button>
            </div>
        </div>


    </div>

</form>

<div class="py-5 text-center">
    <p class="mt-5 mb-3 text-muted">&copy; 2022-2023</p>
</div>

So I have no idea what the source of this problem is. Everything seems fine to me, can anyone help me?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source