DJANGO:如何在表单中呈现模型对象名称而不是文字“模型对象”?

时间:2012-03-13 19:50:29

标签: django forms django-models many-to-many inline-formset

我有以下模型:部门,项目,部门项目,员工和成员资格。部门有许多项目和项目有许多员工通过成员资格分配角色。我正在尝试创建一个InlineFormset,以便EU可以将Employee的角色分配给多个项目。

我的模板呈现正确的标签和字段,但Departmentprojects标签和字段不显示项目的名称。它只显示“Departmentprojects对象”。如何让表单呈现项目名称而不是“Departmentprojects object”?

-

浏览器中的当前模板:

Departmentproject标签:(下拉菜单中有两个选项列为“Departmentprojects对象”) 职责:项目经理

浏览器中的所需模板:

部门项目名称1:项目经理

部门项目名称2:其他一些角色

-

模型:

class Projects(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
        return self.name

class Department(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
        return self.name

class Employees(models.Model):
    name = models.CharField(max_length=15)
    def __unicode__(self):
        return self.name

class Departmentprojects(models.Model):
    department = models.ForeignKey(Department)
    projects = models.ForeignKey(Projects)
    members = models.ManyToManyField(Employees, through='Membership')

class Membership(models.Model):
    departmentprojects = models.ForeignKey(Departmentprojects)
    employees = models.ForeignKey(Employees)
    role = models.CharField(max_length=20)

-

查看

def addtoprojects(request, employees_id):
    e = get_object_or_404(Employees, pk=employees_id)
    ProjectsInlineFormSet = inlineformset_factory(Employees, Membership, max_num=1)
    if request.method == "POST":
        formset = ContactInlineFormSet(request.POST, instance=e)
        if formset.is_valid():
            formset.save()
    else:
        formset = ProjectsInlineFormSet(instance=e)
    return render_to_response('gcstest/contact.html', {'e': e, 'formset': formset}, context_instance=RequestContext(request))

-

TEMPLATE

<form method="post" action="/assign_to_project/{{ employees.id }}/">
    {% csrf_token %}
    <table>
        {{ formset }}
    </table>
    <input type="submit" value="Submit"/>
</form>

1 个答案:

答案 0 :(得分:3)

Departmentprojects模型添加__unicode__方法,例如

class Departmentprojects(models.Model):
    department = models.ForeignKey(Department)
    projects = models.ForeignKey(Projects)
    members = models.ManyToManyField(Employees, through='Membership')

    def __unicode__(self):
        return "%s > %s" % (self.department, self.projects)