1

Upon signup, I'd like to request the user for:

  • Full name (I want to save it as first and last name though)
  • Company name
  • Email
  • Password

I've read through dozens of similar situations on StackOverflow. In models.py, I extend the User model like so:

# models.py
class UserProfile(models.Model):
  company = models.CharField(max_length = 50)
  user = models.OneToOneField(User)

def create_user_profile(sender, instance, created, **kwargs):
  if created:
    profile, created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_user_profile, sender=User)

Source: Extending the User model with custom fields in Django

I've also added:

# models.py

class SignupForm(UserCreationForm):
  fullname = forms.CharField(label = "Full name")
  company = forms.CharField(max_length = 50)
  email = forms.EmailField(label = "Email")
  password = forms.CharField(widget = forms.PasswordInput)

class Meta:
  model = User
  fields = ("fullname", "company", "email", "password")

def save(self, commit=True):
  user = super(SignupForm, self).save(commit=False)
  first_name, last_name = self.cleaned_data["fullname"].split()
  user.first_name = first_name
  user.last_name = last_name
  user.email = self.cleaned_data["email"]
  if commit:
    user.save()
  return user

And in views.py:

# views.py

@csrf_exempt
def signup(request):
  if request.method == 'POST':
    form = SignupForm(request.POST)
    if form.is_valid():
      new_user = form.save()
      first_name, last_name = request.POST['fullname'].split()
      email = request.POST['email']
      company = request.POST['company'],
      new_user = authenticate(
        username = email,
        password = request.POST['password']
      )
      # Log the user in automatically.
      login(request, new_user)

Right now, it doesn't store the company name. How do I do that?

1 Answer 1

2
user_profile = new_user.get_profile()
user_profile.company = company
user_profile.save()

Don't forget to configure your UserProfile class in settings so Django knows what to return on user.get_profile()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.