在Django的管理页面中为用户添加字段

时间:2018-12-14 11:41:57

标签: python django

这个问题似乎很简单,但我找不到解决方案。我需要在django中扩展我的用户模型(添加电话号码),然后我选择了创建另一个名为UserInfo的模型的方法,该模型与用户模型1to1相关。它工作正常,唯一的问题是我无法让用户信息字段(电话号码)显示在管理面板的用户页面上。我尝试过的:

from app.models import UserInfo
from django.contrib import admin
from django.contrib.auth.models import User

class UserInfoInline(admin.TabularInline):
    model = UserInfo
class UserAdmin(admin.ModelAdmin):
    inlines = [UserInfoInline,]

admin.site.register(UserInfo)

编辑: 当前情况是:

try:
    admin.site.unregister(User)
except admin.sites.NotRegistered:
    pass
try:
    admin.site.register(User, UserAdmin)
except:
    pass

但是,这次我仍然从唯一的django模块中得到了错误:

python3.6/site-packages/django/contrib/admin/sites.py", line 109, in register
    raise AlreadyRegistered('The model %s is already registered' % model.__name__)
django.contrib.admin.sites.AlreadyRegistered: The model User is already registered

2 个答案:

答案 0 :(得分:1)

您应该做的是注销默认用户并注册UserAdmin

from app.models import UserInfo
from django.contrib import admin
from django.contrib.auth.models import User

class UserInfoInline(admin.TabularInline):
    model = UserInfo
class UserAdmin(admin.ModelAdmin):
    inlines = [UserInfoInline,]

# below lines should be added
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

尝试删除 UserInfo

的注册部分

编辑: 尝试按照下面的示例进行操作:

models.py

from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    STUDENT = 1
    TEACHER = 2
    SUPERVISOR = 3
    ROLE_CHOICES = (
        (STUDENT, 'Student'),
        (TEACHER, 'Teacher'),
        (SUPERVISOR, 'Supervisor'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    location = models.CharField(max_length=30, blank=True)
    birthdate = models.DateField(null=True, blank=True)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)

    def __str__(self):  # __unicode__ for Python 2
        return self.user.username

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from .models import Profile

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'

class CustomUserAdmin(UserAdmin):
    inlines = (ProfileInline, )

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


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

您可以详细了解here

答案 1 :(得分:0)

您需要重新注册用户管理员。

#include "arm_compute/core/Types.h"
#include "arm_compute/runtime/CL/CLFunctions.h"
#include "arm_compute/runtime/CL/CLScheduler.h"
#include "arm_compute/runtime/CL/CLTuner.h"
#include "utils/Utils.h"

namespace armcl = arm_compute;
namespace armcl_utils = arm_compute::utils;

int main(int argc, char *argv[])
{
  int n = 3;
  int m = 2;
  int p = 4;

  std::vector<float> src_a = {2, 1,
                          6, 4,
                          2, 3};
  std::vector<float> src_b = {5, 2, 1, 6,
                          3, 7, 4, 1};
  std::vector<float> c_targets = {13, 11, 6, 13,
                                  42, 40, 22, 40,
                                  19, 25, 14, 15};

  // Provides global access to a CL context and command queue.
  armcl::CLTuner tuner{};
  armcl::CLScheduler::get().default_init(&tuner);

  armcl::CLTensor a{}, b{}, c{};
  float alpha = 1;
  float beta = 0;
  // Initialize the tensors dimensions and type:
  const armcl::TensorShape shape_a(m, n);
  const armcl::TensorShape shape_b(p, m);
  const armcl::TensorShape shape_c(p, n);
  a.allocator()->init(armcl::TensorInfo(shape_a, 1, armcl::DataType::F32));
  b.allocator()->init(armcl::TensorInfo(shape_b, 1, armcl::DataType::F32));
  c.allocator()->init(armcl::TensorInfo(shape_c, 1, armcl::DataType::F32));

  // configure sgemm
  armcl::CLGEMM sgemm{};
  sgemm.configure(&a, &b, nullptr, &c, alpha, beta);

  // // Allocate the input / output tensors:
  a.allocator()->allocate();
  b.allocator()->allocate();
  c.allocator()->allocate();

  // // Fill the input tensor:
  // // Simplest way: create an iterator to iterate through each element of the input tensor:
  armcl::Window input_window;
  armcl::Iterator input_it(&a, input_window);
  input_window.use_tensor_dimensions(shape_a);

  std::cout << " Dimensions of the input's iterator:\n";
  std::cout << " X = [start=" << input_window.x().start() << ", end=" << input_window.x().end() << ", step=" << input_window.x().step() << "]\n";
  std::cout << " Y = [start=" << input_window.y().start() << ", end=" << input_window.y().end() << ", step=" << input_window.y().step() << "]\n";


  // // Iterate through the elements of src_data and copy them one by one to the input tensor:
  execute_window_loop(input_window, [&](const armcl::Coordinates & id)
                      {
                        std::cout << "Setting item [" << id.x() << "," << id.y() << "]\n";
                        *reinterpret_cast<float *>(input_it.ptr()) = src_a[id.y() * m + id.x()]; //
                      },
                      input_it);

  //  armcl_utils::init_sgemm_output(dst, src0, src1, armcl::DataType::F32);

  // Configure function

  // Allocate all the images
  //  src0.allocator()->import_memory(armcl::Memory(&a));
  //src0.allocator()->allocate();
  //src1.allocator()->allocate();

  // dst.allocator()->allocate();

  // armcl_utils::fill_random_tensor(src0, -1.f, 1.f);
  // armcl_utils::fill_random_tensor(src1, -1.f, 1.f);

  // Dummy run for CLTuner
  //sgemm.run();

  std::vector<float> lin_c(n * p);

  return 0;
}