Home > Net >  DJANGO update is_active when email_confirmed is checked
DJANGO update is_active when email_confirmed is checked

Time:04-02

On the Django admin interface, when I check email_confirmed under the Profile model, is there a way for me to automatically update is_active under the Djangos authentication User model? Linking them together in a way. Would like the ability to be able to check both with 1 click if a user hasn't recieved their sign-up email.

Profile.py

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    unique_id = models.UUIDField(null=False, blank=False, default=uuid.uuid4, unique=True, editable=False)

    email_confirmed = models.BooleanField(default=False)


    def __str__(self):
        return self.user.username

admin.py

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'email_confirmed')
    search_fields = ('user__email',)
    readonly_fields = ('user', 'unique_id')
    fieldsets = (
        ('Details', {
            'fields': ('unique_id', 'user')
        }),
        ('Status', {
            'fields': ('email_confirmed')
        }),
        ('Timezone', {
            'fields': ('timezone')
        }),
    )

I have looked into using @reciever(setting_changed) in Profile.py, but didn't quite understand. Similarly I have looked into the following in admin.py, and trying to set is_active to true in there but to no avail.

def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "email_confirmed":

Thank you in advance for you help

CodePudding user response:

You will need to override save method for this and save user model whenver the email is confirmed.

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    unique_id = models.UUIDField(null=False, blank=False, default=uuid.uuid4, unique=True, editable=False)

    email_confirmed = models.BooleanField(default=False)


    def __str__(self):
        return self.user.username
    
    def save(self,*args,**kwargs):
        if self.email_confirmed:
           self.user.is_active=True
           self.user.save()
        super(Profile,self).save(*args,**kwargs)

I have not implemented but I think this works.

  • Related