简体   繁体   中英

Create model object in django admin using save_model method

I am coming from php background so python-django is totally new to me. I am trying to insert a new record in account_emailaddress table from admin.py using save_model method , whenever a new user is created from admin section.

Following are the partial contents from models.py

class EmailAddress(models.Model):
    user = models.OneToOneField(User, unique=True, related_name ='address')
    email = models.EmailField()
    verified = models.BooleanField(verbose_name=_('verified'), default=True)
    primary = models.BooleanField(verbose_name=_('primary'), default=True)

    class Meta:
        db_table = 'account_emailaddress'

From admin.py

from django.contrib import admin
from django.contrib.auth import admin as upstream
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group, User
from django.utils.translation import ugettext, ugettext_lazy as _
from .models import EmailAddress



class CustomUserAdmin(UserAdmin):
    list_display = ('email', 'first_name', 'last_name', 'is_staff')
    list_select_related = ( 'profile', )

    #exclude = ('username',)

    fieldsets = (
        ('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
    )

    add_fieldsets = (
        ('None', {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2')}
        ),
    )

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

    def get_ordering(self, request):
        return ['-date_joined']


    def save_model(self, request, obj, form, change):
        obj.EmailAddress.save()
        obj.save()



admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

I am getting an error --

'User' object has no attribute 'EmailAddress'

------------------UPDATE 1 BEGIN---------------

From models.py

class UserProfile(models.Model, HashedPk):
    user = models.OneToOneField(User, unique=True, related_name ='profile')
    job_title = models.CharField(max_length=128, blank=True, null=False, default="")
    website = models.URLField(max_length=255, blank=True, null=True)
    organisation = models.CharField(max_length=50, blank=True, null=True, default="")
    phone_number = PhoneNumberField( blank=True, null=True)

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
        #if the loggedin user is admin or user_created_by admin then create the object 
        #EmailAddress.objects.create(user=instance, email=instance.email)

------------------UPDATE 1 END---------------

#EmailAddress.objects.create(user=instance, email=instance.email)

The above code works but I won't be able to use it here because allauth app(I am using for user registration in the frontend) tries to create the same row in account_emailaddress table and thus create duplicate error.

Is it possible so that if the user is created by admin then create object.

Any help or suggestion is highly appreciated. Thanks in advance.

You've defined the related_name from User to EmailAddress as address , so that's what you should use:

obj.address.save()

Note, even if you hadn't defined this, the default related_name is the lower-case version of the model name.

I just want to add some notes to answers. At first you can allways check the property name by just printing all properties print(dir(obj)) if you don't want to use debuggers. If you want to permit only admin users to create that objects you can write this check if request.user.is_superuser: . Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM