Django admin - Extended User model

720 views Asked by At

My requirement is to create 2 types of user in Django.
1. Student
2. Faculty

I have extended the Django user model by creating a MyProfile model:

class MyProfile(models.Model):  
    user       = models.OneToOneField(User, on_delete=models.CASCADE)

    #Profile Information
    photo = FilerImageField(
        blank = True,
        help_text = 'Profile Pic',
        null = True,
        on_delete = models.SET_NULL
    )

    #Student Information
    enrollment = models.CharField('Enrollment',
        blank = True,
        default = '',
        help_text = 'Student Enrollment Number',
        max_length = 20,
    )
    admission_date = models.DateField('Admission Date',
        blank = True,
        default = None,
        null = True,
        help_text = 'Date when student joined the college',
    )

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

Now if I create a user then
For Student:- Fields likes 'enrollment', 'admission_date' are mandatory BUT
For Faculty:- these fields are not required.

Now in the admin.py file, I did below:

class ProfileInline(admin.StackedInline):
    model = MyProfile
    fieldsets = (
        ('Profile Information', {
            'classes': ('collapse',),
            'fields': ('photo')     
        }),
        ('Student Information', {
            'classes': ('collapse',),
            'fields': (
                ('enrollment', 'admission_date'),
        }).
    )

@admin.register(User)
class MyUserAdmin(admin.ModelAdmin):
    list_display = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active',)
    search_fields = ('username', 'first_name', 'last_name', 'email',)
    list_filter = ('is_staff', 'is_active',)
    inlines = [
        ProfileInline,
    ]
    fieldsets = (
        ('User Information', {
            'fields': ('username', ('first_name', 'last_name'), 'password', 'groups', 'is_active')
        }),
    )

I have created 2 groups:
1. student
2. faculty

Now the 1st problem is:
1. If we create a user and select 'student' group then how to check if 'enrollment' & 'admission_date' fields are filled or not. If not then show the error message to user that there are required fields.
2. If we create a user and select 'faculty' group then it should not check for these fields.

2nd problem is:
If you see "MyUserAdmin" class in admin.py, I have included 'password' in fieldsets. When we create user using django admin then it shows the password field as plain input text box. Also it's not hashing the password before saving in database.
1. How I can show 'password' & 'verify password' box.
2. Use password type in input field.
3. Hash the password before saving into the database.

Thanks for the help!

Regards,
Shashank

0

There are 0 answers