在django-admin中添加用户时分配组

时间:2009-12-08 02:43:05

标签: django django-admin

在我的应用程序中,我有将Users模型作为外键的模型,例如:

class Doctor(models.Model):    
username=models.ForeignKey(User, unique=True)
...

在管理网站中,添加新医生时,我可以选择在用户名字段旁边添加新用户。这正是我想要的,但在打开的对话框中,它要求新用户的用户名和密码;我还希望能够为这个新用户分配一个组。这样做的最佳方式是什么?

谢谢, lokharkey

2 个答案:

答案 0 :(得分:2)

在您的应用程序中,创建一个'admin.py',您实际上将自己的模型注册到admin,添加以下代码。

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

class MyUserCreationForm(UserCreationForm):
    """
    A form that overrides the UserCreationForm
    """
    class Meta:
        model = User
        fields = ("username", "groups")

UserAdmin.add_form = MyUserCreationForm

admin.site.register(Doctor)

现在您只需要覆盖渲染此覆盖表单的模板。 创建一个目录结构,

"your_project_root_directory"/templates/admin/auth/user/add_form.html

并将内容复制为,

{% extends "admin/change_form.html" %}
{% load i18n %}

{% block after_field_sets %}

<p>{% trans "First, enter a username and password. Then, you'll be able to edit more user options." %}</p>

<fieldset class="module aligned">

<div class="form-row">
  {{ form.username.errors }}
  {# TODO: get required class on label_tag #}
  <label for="id_username" class="required">{% trans 'Username' %}:</label> {{ form.username }}
  <p class="help">{{ form.username.help_text }}</p>
</div>

<div class="form-row">
  {{ form.password1.errors }}
  {# TODO: get required class on label_tag #}
  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
</div>

<div class="form-row">
  {{ form.password2.errors }}
  {# TODO: get required class on label_tag #}
  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
</div>

<div class="form-row">
  {{ form.groups.errors }}
  {# TODO: get required class on label_tag #}
  <label for="id_groups" class="required">{% trans 'Groups' %}:</label> {{ form.groups }}
  <p class="help">{% trans 'All existing Groups listed here. If you are not seeing any group, means you dont have any groups object created.' %}</p>
</div>

<script type="text/javascript">document.getElementById("id_username").focus();</script>

</fieldset>
{% endblock %}

你很高兴。它的工作片段。

答案 1 :(得分:0)

出于好奇,这种解决方案是否被认为是Django的犹太人?也就是说,复制/粘贴像这样的大块代码似乎违背了Django开发人员推广的DRY原则。