DEV Community

Cover image for Django - User Profile

Django - User Profile

Hana Belay on September 07, 2021

In Today's part of the series, we are going to create profile for a user by including additional information such as profile picture, and bio. ...
Collapse
 
sultanovasadbek profile image
Asadbek.

It was a very cool tutorial. I had such a problem, I added new 21 fields to the Profile model. I can't save this data to the db. Where did I make a mistake? Please tell me.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    last_name = models.CharField(
        _("Фамилия"),
        max_length=30,
        null=True,
        validators=[
            RegexValidator(
                regex=r"^[a-zA-Z]+$",
                message=_("Введите латинские буквы!"),
                code="invalid_last_name",
            )
        ],
    )
    first_name = models.CharField(
        _("Имя"),
        max_length=40,
        null=True,
        validators=[
            RegexValidator(
                regex=r"^[a-zA-Z]+$",
                message=_("Введите латинские буквы!"),
                code="invalid_first_name",
            )
        ],
    )
    father_name = models.CharField(
        _("Отчество"),
        max_length=50,
        null=True,
        validators=[
            RegexValidator(
                regex=r"^[a-zA-Z]+$",
                message=_("Введите латинские буквы!"),
                code="invalid_father_name",
            )
        ],
    )
    birthday = models.DateField(_("Дата рождения"), null=True,)
    sex = models.CharField(_("Пол"), max_length=3, choices=Sex.choices, default=Sex.M, null=True)
    passport_series = models.CharField(
        _("Серия паспорта"),
        null=True,
        max_length=2,
        validators=[
            RegexValidator(
                regex=r"^[A-Z]+$",
                message=_("Введите латинские заглавные буквы!"),
                code="invalid_passport_series",
            )
        ],
    )
    passport_number = models.CharField(_("Паспорт номер"), max_length=7, null=True,)
    issed_by = models.CharField(_("Кем выдан"), max_length=20, null=True,)
    date_of_issue = models.DateField(_("Дата выдачи"), null=True,)
    iden_number = models.CharField(
        _("Номер идентификатор"),
        null=True,
        max_length=15,
        validators=[
            RegexValidator(
                regex=r"^[A-Z0-9]+$",
                message=_("Введите латинские заглавные буквы и цифры!"),
                code="invalid_iden_number",
            )
        ],
    )
    place_of_birth = models.CharField(
        _("Место рождения"),
        null=True,
        max_length=70,
    )

    city_of_residence = models.CharField(
        _("Город проживания"), max_length=9, choices=CityResidence.choices, null=True,
    )
    residential_address = models.CharField(_("Адрес факт. проживания"), max_length=65, null=True)
    home_phone_number = models.CharField(
        _("Домашний телефон номер"),
        null=True,
        blank=True,
        max_length=10,
    )
    phone_number = models.CharField(
        _("Мобильный телефон номер"),
        null=True,
        blank=True,
        max_length=10,
    )
    family_status = models.CharField(
        _("Семейное положение"), null=True, max_length=40, choices=FamilyStatus.choices
    )

    citizenship = models.CharField(
        _("Гражданство"), max_length=15, null=True, choices=Citizenship.choices
    )
    disability = models.CharField(
        _("Инвалидность"), max_length=40, null=True, choices=Disability.choices
    )
    pensioner = models.BooleanField(_("Пенсионер"), default=False)
    monthly_income = models.DecimalField(
        _("Ежемесячный доход"),
        blank=True,
        null=True,
        max_digits=7,
        decimal_places=0,
    )
    liable_for_military_service = models.BooleanField(
        _("Военнообязанный"), default=True, null=True
    )

    def __str__(self):
        return self.user.username
Enter fullscreen mode Exit fullscreen mode

forms.py

class UpdateProfileForm(forms.ModelForm):
    # avatar = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control-file'}))

    class Meta:
        model = Profile
        fields = '__all__'

        widgets = {
            "last_name": forms.TextInput(
                attrs={"placeholder": "Фамилия", "class": "myfield"},
            ),
            "first_name": forms.TextInput(
                attrs={"placeholder": "Имя", "class": "myfield"}
            ),
            "father_name": forms.TextInput(
                attrs={"placeholder": "Отчество", "class": "myfield"}
            ),
            "birthday": forms.DateInput(
                attrs={
                    "placeholder": "Дата рождение",
                    "type": "date",
                    "class": "myfield",
                    "onfocus": "(this.type='date')",
                    "onblur": "(this.type='text')",
                }
            ),
            "sex": forms.RadioSelect(
                attrs={"label": "Пол", "type": "radio", "class": "RadioButton"}
            ),
            "passport_series": forms.TextInput(
                attrs={"placeholder": "Серия паспорта", "class": "myfield"}
            ),
            "passport_number": forms.NumberInput(
                attrs={"placeholder": "Паспорт номер", "class": "myfield"}
            ),
            "issed_by": forms.TextInput(
                attrs={"placeholder": "Кем выдан", "class": "myfield"}
            ),
            "date_of_issue": forms.DateInput(
                attrs={
                    "placeholder": "Дата выдачи",
                    "type": "date",
                    "class": "myfield",
                    "onfocus": "(this.type='date')",
                    "onblur": "(this.type='text')",
                }
            ),
            "iden_number": forms.TextInput(
                attrs={"placeholder": "Номер идентификатор", "class": "myfield"}
            ),
            "place_of_birth": forms.TextInput(
                attrs={"placeholder": "Место рождение", "class": "myfield"}
            ),
            "city_of_residence": forms.Select(
                attrs={"placeholder": "Город факт. проживания", "class": "myfield"}
            ),
            "residential_address": forms.TextInput(
                attrs={"placeholder": "Адрес факт. проживания", "class": "myfield"}
            ),
            "home_phone_number": forms.TextInput(
                attrs={"placeholder": "Домашний телефон номер", "class": "myfield"}
            ),
            "phone_number": forms.TextInput(
                attrs={"placeholder": "Мобильный телефон номер", "class": "myfield"}
            ),
            "family_status": forms.Select(
                attrs={"placeholder": "Семейное положение", "class": "myfield"}
            ),
            "citizenship": forms.Select(
                attrs={"placeholder": "Гражданство", "class": "myfield"}
            ),
            "disability": forms.Select(
                attrs={"placeholder": "Инвалидность", "class": "myfield"}
            ),
            "pensioner": forms.CheckboxInput(
                attrs={"placeholder": "Пенсионер", "class": ""}
            ),
            "monthly_income": forms.NumberInput(
                attrs={"placeholder": "Ежемесячный доход", "class": "myfield"}
            ),
            "liable_for_military_service": forms.CheckboxInput(
                attrs={"placeholder": "Военнообязанный", "class": ""}
            ),
        }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
earthcomfy profile image
Hana Belay

Thanks, can you tell me what error you are getting?

Collapse
 
sultanovasadbek profile image
Asadbek. • Edited

The data received from form 21 is not being entered into the database. With one word, the profile does not expand.

Thread Thread
 
earthcomfy profile image
Hana Belay

Line numbers are not shown in the code. Can you be more descriptive please. And also send me a screenshot of the error. Thanks.

Thread Thread
 
isalameh95 profile image
Israa Salameh

I have the same issue, no errors in the application at all, but I have check the user_profile table in the database and I have notice that the added fields have null values, even I entered them in register.
I think you should do profile.save() in the register view.

Collapse
 
akhilesh_thapliyal_4c8ea5 profile image
Akhilesh Thapliyal • Edited

Please move to iommi forms, you don't have to write such a big form and it is easy to save. Less code and configuration :)

Collapse
 
davidroberthoare profile image
davidroberthoare

thank you!!!

Collapse
 
earthcomfy profile image
Hana Belay

My pleasure.

Collapse
 
hootjhiang profile image
HT Han

This is a really great tutorial.
I jumped over to your Password Reset Tutorial (dev.to/earthcomfy/django-reset-pas...) and ran into a series of issues, but eventually figured it out using SendGrid.
Thanks for creating these tutorials.

Collapse
 
earthcomfy profile image
Hana Belay

Hi, thanks for the kind feedback.

The issues might have been caused if you used the less secure apps setting to allow your app to send email. That setting is no longer available. If you want to send emails from your Google account, you should rather enable 2FA for your Google account and create app password.

Collapse
 
daku2 profile image
khukhar daku

smt. is not wroking is there any other way that i can send email verification to user.

Collapse
 
ilkhan1901 profile image
ilkhan1901

Nice tutorial, like it :)

Collapse
 
earthcomfy profile image
Hana Belay

Thanks, glad you enjoyed it.