I created extended User model in models.py as below:
class Employee(models.Model):
user = models.OneToOneField(User)
customfield1 = models.CharField(max_length=100)
customfield2 = models.CharField(max_length=100)
and I want to add these fields to registration form. I analyzed this topic. This is the right solution but i can't apply into my site. I designed registration form but i can't register user. Codes i am using that is here: forms.py(This is my original form but this doesn't save Employee data into db):
class AdvancedRegistrationForm(UserCreationForm):
customfield = forms.CharField(max_length=100,label="Address")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'customfield1', 'customfield2')
def save(self, commit=True):
user = super(AdvancedRegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.username = self.cleaned_data['username']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
views.py:
def register(request):
if request.method == 'POST':
form = AdvancedRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/../login")
else:
form = AdvancedRegistrationForm()
return render_to_response("register.html", {
"form": form,
}, RequestContext(request))
forms.py(This is the form that i create according to this solution but it doesn't register/save anything):
class AdvancedRegistrationForm(forms.ModelForm):
def __init__(self, instance=None, *args, **kwargs):
_fields = ('first_name', 'last_name', 'username', 'email', )
_initial = forms.model_to_dict(instance.user, _fields) if instance is not None else {}
super(AdvancedRegistrationForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
self.fields.update(forms.fields_for_model(User, _fields))
class Meta:
model = Employee
exclude = ('user',)
def save(self, *args, **kwargs):
u = self.instance.user
u.first_name = self.cleaned_data['first_name']
u.last_name = self.cleaned_data['last_name']
u.username = self.cleaned_data['username']
u.email = self.cleaned_data['email']
u.save()
profile = super(AdvancedRegistrationForm, self).save(*args,**kwargs)
profile.user = u
profile.customfield = self.cleaned_data['customfield']
return profile