From d853278253b5efa60a691ae9b83fb6352d2a91f0 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Wed, 27 Dec 2006 05:15:22 +0000 Subject: [PATCH] newforms: Implemented formfield() for database ManyToManyField class and added unit tests git-svn-id: http://code.djangoproject.com/svn/django/trunk@4246 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/fields/related.py | 5 +++++ tests/modeltests/model_forms/models.py | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 797ef05be1..ce33968974 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -2,10 +2,12 @@ from django.db import backend, transaction from django.db.models import signals, get_model from django.db.models.fields import AutoField, Field, IntegerField, get_ul_class from django.db.models.related import RelatedObject +from django.utils.text import capfirst from django.utils.translation import gettext_lazy, string_concat, ngettext from django.utils.functional import curry from django.core import validators from django import oldforms +from django import newforms as forms from django.dispatch import dispatcher # For Python 2.3 @@ -713,6 +715,9 @@ class ManyToManyField(RelatedField, Field): def set_attributes_from_rel(self): pass + def formfield(self): + return forms.MultipleChoiceField(choices=self.get_choices_default(), required=not self.blank, label=capfirst(self.verbose_name)) + class ManyToOneRel(object): def __init__(self, to, field_name, num_in_admin=3, min_num_in_admin=None, max_num_in_admin=None, num_extra_on_change=1, edit_inline=False, diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index 5ffd6aac9f..da10e215a6 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -101,6 +101,18 @@ Traceback (most recent call last): ... ValueError: The Category could not be created because the data didn't validate. +ManyToManyFields are represented by a MultipleChoiceField. +>>> ArticleForm = form_for_model(Article) +>>> f = ArticleForm(auto_id=False) +>>> print f +Headline: +Pub date: +Categories: + You can pass a custom Form class to form_for_model. Make sure it's a subclass of BaseForm, not Form. >>> class CustomForm(BaseForm):