简体   繁体   English

使用save_model方法在Django管理中创建模型对象

[英]Create model object in django admin using save_model method

I am coming from php background so python-django is totally new to me. 我来自php背景,因此python-django对我来说是全新的。 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. 每当save_model从admin部分创建新用户时,我都尝试使用save_model方法在admin.py中的account_emailaddress表中插入新记录。

Following are the partial contents from models.py 以下是来自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 来自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--------------- ------------------更新1开始---------------

From models.py 来自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--------------- ------------------更新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. 上面的代码有效,但是我不能在这里使用它,因为allauth应用程序(我正在前端中用于用户注册)试图在account_emailaddress表中创建同一行,从而造成重复错误。

Is it possible so that if the user is created by admin then create object. 是否有可能,如果用户是由admin创建的,则创建对象。

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: 您已将从user到EmailAddress的related_name定义为address ,因此应使用:

obj.address.save()

Note, even if you hadn't defined this, the default related_name is the lower-case version of the model name. 请注意,即使您尚未定义此名称,默认的related_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. 首先,如果您不想使用调试器,则可以通过仅打印所有属性print(dir(obj))来始终检查属性名称。 If you want to permit only admin users to create that objects you can write this check if request.user.is_superuser: . 如果您只允许管理员用户创建该对象,则可以if request.user.is_superuser:编写此检查。 Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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