Я создал регистрационную форму, разделенную на две части: данные компании и данные представителя.
В начале разработки меня интересуют только данные компании, и в качестве тестов я зарегистрировал пользователей, которые используют стандартную панель администратора Django, как и моя форма.
Теперь я модернизировал модель для регистрации с другими данными.
Когда я отправляю данные, новый пользователь регистрируется только в том случае, если я использую панель администратора Django по умолчанию, но если я использую свою форму, что-то не так, потому что я вижу на терминале сообщение Invalid form. Something was wrong!!
Я не понимаю, где находится ошибка, потому что на терминале нет другого сообщения об ошибке, даже если я удаляю print("Invalid form. Something was wrong!!")
.
form.py
class UserProfileCreationForm(UserCreationForm):
username = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the username',
'class': 'form-control',
}
),
label='Company Username',
help_text='Write the name of your Company',
required=False,
)
password1 = forms.CharField(
label="Password",
widget=forms.PasswordInput(attrs={
'class': 'form-control',
}
),
strip=False,
help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
label="Password confirmation",
widget=forms.PasswordInput(attrs={
'class': 'form-control',
}
),
)
company_name = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the name of your Company',
'class': 'form-control',
}
),
label='Name of Company',
)
company_city = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the name of the city in which there is the registered office of your Company',
'class': 'form-control',
}
),
label='City',
)
company_address = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the address of the registered office',
'class': 'form-control',
}
),
label='Address',
)
company_postcode = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the zip code of the registered office',
'class': 'form-control',
}
),
label='Zip Code',
)
company_country = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the Country in which there is the registered office',
'class': 'form-control',
}
),
label='Country',
)
company_region = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the Region in which there is the registered office',
'class': 'form-control',
}
),
label='Region',
)
company_telephone_number = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the telephone of the registered office',
'class': 'form-control',
}
),
label='Main Company telephone number',
)
company_email = forms.EmailField(
widget=forms.EmailInput(attrs={
'placeholder': 'Write the email of the registered office',
'class': 'form-control',
}
),
label='Main Company email',
)
representative_name = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the name of the person that represent the Company on this platform',
'class': 'form-control',
}
),
label='Representative name',
)
representative_surname = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the surname of the person that represent the Company on this platform',
'class': 'form-control',
}
),
label='Representative surname',
)
representative_role = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the role of the person that represent the Company on this platform',
'class': 'form-control',
}
),
label='Role',
)
representative_telephone = forms.CharField(
widget=forms.TextInput(attrs={
'placeholder': 'Write the telephone of the person that represent the Company on our platform',
'class': 'form-control',
}
),
label='Representative telephone number',
)
representative_email = forms.EmailField(
widget=forms.EmailInput(attrs={
'placeholder': 'Write the email of the person that represent the Company on our platform',
'class': 'form-control',
}
),
label='Representative email',
)
class Meta:
model = User
fields = [
'username', 'password1', 'password2',
'company_name', 'company_address', 'company_city', 'company_postcode', 'company_region', 'company_country', 'company_telephone_number', 'company_email',
'representative_name', 'representative_surname', 'representative_role', 'representative_telephone', 'representative_email',
]
def clean(self):
super().clean()
password1 = self.cleaned_data["password1"]
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return self.cleaned_data
view.py
def createUser(request):
if request.method == "POST":
form = UserProfileCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password1"]
company_name = form.cleaned_data["company_name"]
company_city = form.cleaned_data["company_city"]
company_address = form.cleaned_data["company_address"]
company_postcode = form.cleaned_data["company_postcode"]
company_country = form.cleaned_data["company_country"]
company_region = form.cleaned_data["company_region"]
company_telephone_number = form.cleaned_data["company_telephone_number"]
company_email = form.cleaned_data["company_email"]
representative_name = form.cleaned_data["representative_name"]
representative_surname = form.cleaned_data["representative_surname"]
representative_role = form.cleaned_data["representative_role"]
representative_telephone = form.cleaned_data["representative_telephone"]
representative_email = form.cleaned_data["representative_email"]
UserProfile.objects.create_user(
username=username, password=password,
company_name=company_name, company_city=company_city, company_address=company_address,
company_postcode=company_postcode, company_country=company_country, company_region=company_region,
company_telephone_number=company_telephone_number, company_email=company_email,
representative_name=representative_name, representative_surname=representative_surname, representative_role=representative_role,
representative_telephone=representative_telephone, representative_email=representative_email,
)
print("I'm sending you at the profile!")
return HttpResponseRedirect("/hub/user/")
else:
print("Invalid form. Something was wrong!!")
return HttpResponseRedirect("/")
else:
form = UserProfileCreationForm()
template = 'usermanager/editing/create_user.html'
context = {'form': form}
return render(request, template, context)
templates.html
<form class="" action="" method="POST" novalidate>
{% csrf_token %}
{#{ form.errors }#}
{#{ form.as_p }#}
{% for field in form %}
<div class="form-group">
<div class="row">
<div class="col-sm-3">
<strong>{{ field.label_tag }}</strong>
</div>
<div class="col-sm-9">
{{ field }}
{% if field.errors == True %}
<div class="alert alert-danger" role="alert">
{{ field.errors }}
</div>
{% endif %}
</div>
</div>
</div>
{% endfor %}
<input type="submit" class="btn btn-danger" value="Register">
</form>