How is possible to get initial value from the view? What parameter should I use in form?
views.py
def cadastro_usuario(request):
if request.method == 'POST':
form = cadastroForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/")
else:
form = cadastroForm()
return render_to_response("registration/registration.html", {
'form': form, 'tipo_cadastro': 'PF',})
forms.py
class cadastroForm(UserCreationForm):
tipo_cadastro = forms.CharField(XXXXX)
Ok, based on your comment in response to @J. Lnadgrave, let's assume you have a "user_type" property on your UserProfile model that can be set to your "normal" user or "company" user...
#your_app.constants
NORMAL_USER = 0
COMPANY_USER = 1
USER_TYPE_CHOICES = (
(NORMAL_USER, "Normal"),
(COMPANY_USER, "Company"),
)
#your_app.models
from django.contrib.auth.models import User
from your_app.constants import USER_TYPE_CHOICES
class UserProfile(models.Model):
user = models.OneToOne(User)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
#your_app.forms
from your_app.models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta():
model = UserProfile
user_type = forms.IntegerField(widget=forms.HiddenInput)
#your_app.views
form django.http import HttpResponseRedirect
from django.shortcuts import render
from your_app.constants import NORMAL_USER, COMPANY_USER
from your_app.forms import UserProfileForm
from your_app.models import UserProfile
def normal_user_registration(request):
user_profile_form = UserProfileForm(request.POST or None,
initial={'user_type' : NORMAL_USER})
if request.method == 'POST':
user_profile_form.save()
return HttpResponseRedirect('/')
return render(request, 'registration/registration.html',
{'user_profile_form' : user_profile_form})
def company_user_registration(request):
user_profile_form = UserProfileForm(request.POST or None,
initial={'user_type' : COMPANY_USER})
if request.method == 'POST':
user_profile_form.save()
return HttpResponseRedirect('/')
return render(request, 'registration/registration.html',
{'user_profile_form' : user_profile_form})
This is a pretty long-winded way to approach this, but I thought it made it pretty evident how to pass that initial value to your form. Hope that helps you out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With