0
votes

I want to create 2 custom user models(profiles) which will have a field with OneToOne mapping to the default Django auth User model.

class StudentProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # several fields here

class TeacherProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # more fields here

I am able to implement it using signals if it was a single User Profile model. I have 2 forms and 2 views, one for each registration.

How do I make only an object of the Profile model to be created when its respective form function is executed?

My views.py file

def student_register(request):
    if request.method == "POST":
        form = StudentRegisterForm(request.POST)
        if form.is_valid(): 
            form.save() 
            return redirect('student-login')
    else:
        form = StudentRegisterForm()
    context = {'form': form}
    return render(request, 'users/student_register.html', context)
1
You can do it in in the form submit view function. - shafik
How do I do that? - Luke Ndatigh
add your view files to your question. - shafik
I have updated so - Luke Ndatigh
Which model you use for StudentRegisterForm - shafik

1 Answers

1
votes

You can simply use a GET param at the end of your posts URL to indicate the type of user registering. For example,

<form class="student-form" method=POST action=register-user?type=student>
...
</form>

# and for the teacher same url just different url GET param
<form class="student-form" method=POST action=register-user?type=teacher>
...
</form>

Then your views, you can check for the sent GET param,

def student_register(request):
   ...
   if request.method == "POST":
      if 'type' in request.GET and request.GET['type'] == 'student':
          # do student stuff
      elif 'type' in request.GET and request.GET['type'] == 'teacher':
          # do teacher stuff
   ...

Should do the job.

Hope this helps!