使用 django admin 进行一对多内联选择 [英] one-to-many inline select with django admin

查看:43
本文介绍了使用 django admin 进行一对多内联选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了标准的多对一关系.有很多字段,但就我们这里的目的而言,相关模型是:

I have a standard many-to-one relationship set up. There are a bunch of fields, but for our purposes here, the relevant model is:

class Class(models.Model):
    name = models.CharField(max_length=128)

class Student(models.Model):
    class = models.ForeignKey(Class)
    name = models.CharField(max_length=128)
    address = models.CharField(max_length=128)
    # ...etc

我创建了一个管理员,效果很好.它甚至可以在我编辑学生时自动设置班级.然而,当我去创建/编辑一个类时,我得到的只是名称的输入框.

I created an admin, and it works great. it even automatically has the ability for me to set the Class when I am editing a Student. However, when I go to create/edit a Class, all I get is an input box for the name.

有没有办法添加一个框/字段,可以从班级管理页面将学生添加为班级成员?我可以制作一个内联表格,但那是为了创建新的学生.我已经创建了所有学生,我只是在寻找一种快速方法将多个现有学生添加到不同的班级.

Is there a way to add a box/field where Students can be added as members of Class from the Class admin page? I can make a form inline, but that is to create new Students. I already have all my Students created and am just looking for a quick method to add multiple existing Students to different Class'.

推荐答案

这是 Luke Sneeringer 建议的自定义表单"解决方案.无论如何,我很惊讶没有开箱即用的 Django 解决方案来解决这个(相当自然且可能很常见)的问题.我错过了什么吗?

Here is "custom form" solution as Luke Sneeringer suggested. Anyway, I'm suprised by absence of out-of-the-box Django solution to this (rather natural and probably common) problem. Am I missing something?

from django import forms
from django.db import models
from django.contrib import admin

class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo

    bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all())

    def __init__(self, *args, **kwargs):
        super(FooForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['bars'].initial = self.instance.bar_set.all()

    def save(self, *args, **kwargs):
        # FIXME: 'commit' argument is not handled
        # TODO: Wrap reassignments into transaction
        # NOTE: Previously assigned Foos are silently reset
        instance = super(FooForm, self).save(commit=False)
        self.fields['bars'].initial.update(foo=None)
        self.cleaned_data['bars'].update(foo=instance)
        return instance

class FooAdmin(admin.ModelAdmin):
    form = FooForm

这篇关于使用 django admin 进行一对多内联选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆