stackyyflow
stackyyflow

Reputation: 763

Django save multiple user types

I am new to Django and would like to do a registration page for my web application. Currently, I need two types of Users (Student and Instructor). I have a checkbox for the user to select if they are student or instructor in my RegistrationForm. I would like to know that under my RegistrationForm, how do I save them into Student or Instructor table respectively under the save() method?

register.py

class RegistrationForm(forms.ModelForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), label='')
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}), label='')
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), label='')
    INSTRUCTOR = "INS"
    STUDENT = "STU"
    roles_choices = [(INSTRUCTOR, "Instructor"), (STUDENT, "Student")]
    role = forms.ChoiceField(choices=roles_choices, widget=forms.RadioSelect(), label='')

    class Meta:
        model = User
        fields = ['email', 'password1', 'password2']

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.set_role(self.cleaned_data['role'])
        if commit:
            user.save()
        return user

models.py

class User(AbstractBaseUser):
    role = models.CharField(max_length=3)

    email = models.EmailField(max_length=100, primary_key=True)
    first_name = models.CharField(max_length=30, null=False)
    last_name = models.CharField(max_length=30, null=False)
    password = models.CharField(max_length=100, null=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    class Meta:
        abstract = True

     def get_absolute_url(self):
        return "/%s/%s/" % (self.role, urlquote(self.email))

    def set_role(self, role):
        self.role = role

    def get_role(self):
        return self.role

    def get_short_name(self):
        pass

    def get_full_name(self):
        pass


class Instructor(User):
    pass

class Student(User):    
    matric_id = models.CharField(max_length=10, blank=False, null=False)

Upvotes: 0

Views: 287

Answers (1)

Jimmar
Jimmar

Reputation: 4459

I'd have the Students and Instructors fields as a separate model with a user one to one field, with this you can even have the option to have the same user work as an Instructor and as a student if that works for your case.

As for your form, you can have 3 forms view on the same page (one is for the regular registration and the other 2 differ according to what the user picks, instructor or student).

The saving part can be done in the views.py since you can extract 2 forms and save + link both instances.

If you need more clarifications just ask and I'll gladly include some code snippets.

Upvotes: 1

Related Questions