Object has no attribute 'cleaned_data' after validation in Django view

Viewed 69

I'm trying to make a registration page for my project. Standard model User is not enough for me, so I created another model named Profile:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sex = models.CharField(max_length=1, choices=SEX_CHOICES, default='М',
                       verbose_name='Пол')
    third_name = models.CharField(max_length=30, verbose_name='Отчество')
    grade = models.CharField(max_length=2, choices=GRADE_CHOICES, default='1',
                         verbose_name='Класс обучения')
    age = models.PositiveSmallIntegerField(default=7, verbose_name='Возраст',
                                       validators=[
                                           MaxValueValidator(100),
                                           MinValueValidator(4)
                                       ]
                                       )
    school = models.ForeignKey(School, on_delete=models.PROTECT,
                           verbose_name='Учебное заведение',
                           blank=True, null=True, default=None)
    interest = models.ManyToManyField(OlympiadSubject,
                                  verbose_name='Интересующие предметы')

On both User and Profile I created a ModelForm:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name')


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('third_name', 'sex', 'grade', 'age', 'school', 'interest')

And wrote a view for registration:

def create_profile(request):
if request.method == 'POST':
    user_form = UserForm()
    profile_form = ProfileForm()
    if user_form.is_valid() and profile_form.is_valid():
        User.objects.create(**user_form.cleaned_data)
        Profile.objects.create(**profile_form.cleaned_data, user=User)
        return redirect('/login')
    else:
        profile_form.add_error('__all__', 'Данные введены неверно!')
else:
    user_form = UserForm()
    profile_form = ProfileForm()
return render(request, 'users/profile_create.html', {
    'user_form': user_form,
    'profile_form': profile_form
    })

and of course I have a template for that:

{% extends 'main/layout.html' %}

{% block title %} Some text {% endblock %}

{% block content %}
    <form method="post">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        <button type="submit">Сохранить изменения</button>
    </form>
{% endblock %}

but i get the same error every time: ProfileForm object has no attribute cleaned_data Don't know how to fix it.

This is my first question on stackoverflow. Sorry, if I wrote something incorrect.

2 Answers

When you define the forms in case of POST request, you don't bind the data to the forms. Since the forms you have created are empty, there is no cleaned_data.

Try

if request.method == 'POST':
    user_form = UserForm(request.POST) # the request.POST part binds the data to the form
    profile_form = ProfileForm(request.POST)

You are missing to capture the form data that are coming with the POST request. You may write:

if request.method == 'POST':
    user_form = UserForm(request.POST)
    profile_form = ProfileForm(request.POST)
Related