views:

771

answers:

4

Hi.

I have a model, called Student, which has some fields, and a OneToOne relationship with user (django.contrib.auth.User).

class Student(models.Model):

    phone = models.CharField(max_length = 25 )
    birthdate = models.DateField(null=True) 
    gender = models.CharField(max_length=1,choices = GENDER_CHOICES) 
    city = models.CharField(max_length = 50)
    personalInfo = models.TextField()
    user = models.OneToOneField(User,unique=True)

Then, I have a ModelForm for that model

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

Using the fields attribute in class Meta, i've managed to show only some fields in a template. However, can I indicate which user fields to show?

Something as:

   fields =('personalInfo','user.username')

is currently not showing anything. Works with only StudentFields though/

Thanks in advance.

+1  A: 

It doesn't work like that. You'll need to use an inline formset.

Daniel Roseman
+1  A: 

I'm not sure this is what you want, but you can take a look at the documentation for Inline Formsets

Flávio Amieiro
+1  A: 

Both answers are correct: Inline Formsets make doing this easy.

Be aware, however, that the inline can only go one way: from the model that has the foreign key in it. Without having primary keys in both (bad, since you could then have A -> B and then B -> A2), you cannot have the inline formset in the related_to model.

For instance, if you have a UserProfile class, and want to be able to have these, when shown, have the User object that is related shown as in inline, you will be out of luck.

You can have custom fields on a ModelForm, and use this as a more flexible way, but be aware that it is no longer 'automatic' like a standard ModelForm/inline formset.

Matthew Schinckel
A: 

Subclass django.contrib.auth.User and you will likely be much happier.

class Student(User):
    user = models.OneToOneField(User, unique=True, parent_link=True)
    phone = models.CharField(max_length=25)
    birth_date = models.DateField(null=True) 
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES) 
    city = models.CharField(max_length=50)
    personal_info = models.TextField()

then you can simply do:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ('personal_info', 'username')
Collin Anderson
Subclassing `User` raises a lot of issues. Creating profiles is the preferred way for storing additional information about users. See http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
Török Gábor
What sort of issues does subclassing `User` raise? I agree creating profiles is the way to go. In my case, I would set `AUTH_PROFILE_MODULE = 'app.Student'`. Then, `student = user.get_profile()`.
Collin Anderson