1

In my app, I've got 2 types of users: Student and Teacher. I want to store additonal information about each of them in separate table.

class Student(models.Model):
    user = models.ForeignKey(User)
    nr_indeksu = models.BigIntegerField()

    def __unicode__(self):
        return unicode(self.user)

Let's assume i want to register user as student - In that case, i need to expand User registration form, so it will contain fields from Group and Student model, and during registration i want to insert Student.nr_indeksu with Student.user_id(FK) into student table, and Group.name into User_Groups.

I've created StudentForm by using Meta Class and rendered it in template in the same form where UserCreationForm is, but i don't know how to handle saving into database, because UserCreationForm creates user_id that it's supposed to go into Student mode. Any pointers?

1 Answer 1

2

I had a similar issue. Solved it by making the model look a little different:

class Student(User):
nr_indeksu = models.BigIntegerField()

def __unicode__(self):
    return unicode(self.user)

This way, when you define the Django form, all needed fields will be rendered for this model. This is because you are saying The student is a user , as opossed to the former the student has a user

The form could look like:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student

Edit: Use a similar approach for teacher model. If you want to avoid the rendering of some fields, use the fields attribute in the Meta class.

Second Edit: If you want to preserve the validations and checks of the User form, the form should also inherit from UserCreationForm.

3
  • Hey it seems to work, but it's just brand new form that inherits it's fields from User right? Because i cannot call fields like 'password1' or 'password2', and 'password' return a TextField as Default. What should i do to inherit password and other safety methods from UserCreationForm?
    – Malyo
    Sep 26, 2013 at 16:23
  • 2
    I've actualy found the answer to my own comment and i think it's worth pointing out - StudentForm should inherit from UserCreationForm by StudentForm(UserCreationForm)
    – Malyo
    Sep 26, 2013 at 16:26
  • Nice! Sorry for taking so long, I was out eating :P
    – Alvaro
    Sep 26, 2013 at 16:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.