使用save_model方法在django admin中创建模型对象

时间:2017-08-14 11:55:01

标签: python django

我来自php背景所以python-django对我来说是全新的。无论何时从管理部门创建新用户,我都会尝试使用account_emailaddress方法从admin.py在save_model表中插入新记录。

以下是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'

来自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)

我收到错误 -

'User' object has no attribute 'EmailAddress'

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

来自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)

以上代码有效,但我无法在此处使用,因为allauth app(我在前端使用用户注册)尝试在account_emailaddress中创建相同的行表因而产生重复错误。

是否可以这样,如果用户是由admin创建的,那么就创建对象。

非常感谢任何帮助或建议。提前谢谢。

2 个答案:

答案 0 :(得分:2)

您已将“User”中的related_name定义为address,因此您应该使用以下内容:

obj.address.save()

注意,即使您没有对此进行定义,默认的related_name也是模型名称的小写版本。

答案 1 :(得分:0)

我只想在答案中添加一些注释。首先,如果您不想使用调试器,只需打印所有属性print(dir(obj))即可检查属性名称。如果您只想允许管理员用户创建该对象,您可以编写此检查if request.user.is_superuser:。希望这会对你有所帮助。