How to display many-to-many field as a list of text input fields?
When I display the ToolBoxEditForm it uses a multiple select field. But what I want is a form that lets the user edit each tool he has in the toolbox as a text field. I cant figure out how to do this with the many-to-many field.
class Tool(models.Model):
tool_name = 开发者_如何学JAVAmodels.CharField(unique=True, max_length=200)
......
class ToolBox(models.Model):
tools = models.ManyToManyField(Tool,max_length=300)
class ToolBoxEditForm (ModelForm):
tools = ???
class Meta:
model = ToolBox
exclude = ('user', 'popularity',)
I'm doing a bit of guess work, as I've played with the ManytoManyField and forms for different purposes. I added the custom field manipulation in the constructor.
I suppose a similar trick can be used to create text fields. This example should create three extra text fields, which you can later validate.
class ToolBoxEditForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ToolBoxEditForm , self).__init__(*args, **kwargs)
for i in range(3):
self.fields['many_to_many_field_%d' % i] = CharField()
精彩评论