Miguel Toledano Miguel Toledano - 1 year ago 78
Python Question

Failed to extends User form in django

The error I get is: extend user to a custom form, the "user_id" field is my custom form is the "property", which is linked to the table "auth_user" is not saved, and I need both tables relate to make use my custom form attributes and shape of the User of django.

my models.py

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models

# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
Matricula = models.CharField(max_length=25)


class SignupForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'Matricula')

#Saving user data
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.Matricula = self.cleaned_data['Matricula']

##Save profile

profile = Profile()
Profile.user = user
profile.Matricula = self.cleaned_data['Matricula']

i tried:

user = models.OneToOneField(User, on_delete=models.CASCADE)

but I get an error:

You believe that ForeignKey can be used or correct use OneToOneField?

Answer Source

You should be careful with your capitalisation. You've assigned the user value to the class, not the instance. It should be:

profile = Profile()
profile.user = user

Or better:

profile = Profile(user=user)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download