Friday, June 1, 2012

Re: Make ManyToMany field editable in a ModelForm

The Form just validates that the object you choose is a valid choice for that M2M field. If you wanted to created a new one on the fly, you'd probably want to use another Form and maybe go the Javascript way.

You could *possibly* get by, in the same form, with doing something like this:

class MyForm(forms.ModelForm):
    add_new_m2m = forms.BooleanField()
    new_m2m = forms.CharField()

    def save(self):

        # Instance of this ModelForm's meta "class" attribute
        m = super(MyForm, self).save(commit=True)

        # A Boolean deciding whether the user wants to create a new choice or not
        if self.cleaned_data['add_new_m2m']:

            # Create the new object, previously unselectable
            new_choice = M2M.objects.create(title=self.cleaned_data['m2m'])

            # Add the object to this Model
            m.m2m.add(new_choice)
           
Another way to go about it is to give the user the option to enter some data manually for that M2M field. Write the clean__m2mfield to accept whatever you feel is nessasary. Then, in your save method, if the field is not a choose-able M2M Object, then create a new one and add it in.

Those are just a couple of ideas. I'm sure others will have more for ya :)
           

On Fri, Jun 1, 2012 at 2:57 AM, Timothy Makobu <makobu.mwambiriro@gmail.com> wrote:
Yes, how does one do that?
Right now it's just rendering static choices that already exist. Or do I have to circumvent ModelForm for this field and present the field manually?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment