Django: Prefill a ManytoManyField

Posted by Emile Petrone on Stack Overflow See other posts from Stack Overflow or by Emile Petrone
Published on 2011-03-10T23:26:43Z Indexed on 2011/03/11 0:10 UTC
Read the original article Hit count: 469

I have a ManyToManyField on a settings page that isn't rendering. The data was filled when the user registered, and I am trying to prefill that data when the user tries to change it.

Thanks in advance for the help!

The HTML:

    {{form.types.label}}

    {% if add %}
        {{form.types}}
    {% else %}
        {% for type in form.types.all %}
            {{type.description}}
        {% endfor %}
    {% endif %}

The View:

@csrf_protect
@login_required
def edit_host(request, host_id, template_name="host/newhost.html"):

host = get_object_or_404(Host, id=host_id)   

if request.user != host.user:
    return HttpResponseForbidden()

form = HostForm(request.POST)    

if form.is_valid():
    if request.method == 'POST':

        if form.cleaned_data.get('about') is not None:
            host.about = form.cleaned_data.get('about')
        if form.cleaned_data.get('types') is not None:
            host.types = form.cleaned_data.get('types')

        host.save()
        form.save_m2m()
        return HttpResponseRedirect('/users/%d/' % host.user.id)
else:
    form = HostForm(initial={
        "about":host.about,
        "types":host.types,
        })

data = { "host":host, "form":form } 

return render_to_response(template_name,
    data,
    context_instance=RequestContext(request))

Form:

class HostForm(forms.ModelForm):
    class Meta:
        model = Host
        fields = ('types', 'about', )

    types = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple, queryset=Type.objects.all(),
        required=True)

    about = forms.CharField(
        widget=forms.Textarea(),
        required=True)  

    def __init__(self, *args, **kwargs):
        super(HostForm, self).__init__(*args, **kwargs)
        self.fields['about'].widget.attrs = {
            'placeholder':'Hello!'}

© Stack Overflow or respective owner

Related posts about django

Related posts about django-forms