dansackett
dansackett

Reputation: 95

Django 1.8 ModelForm request.POST supersedes instance

So I'm working with the Django 1.8 Alpha codebase and wanted to see if anyone else was running into this funny issue. I have a ModelForm:

class ChildForm(forms.ModelForm):
    class Meta:
        model = Child
        fields = ('first_name', 'last_name', 'gender', 'birthday', 'avatar')

And I also have my view:

@login_required
def edit_child(request, id):
    """Edit a child"""
    child = get_object_or_404(Child, pk=id)

    if not child.parent == request.user:
        raise Http404()

    form = ChildForm(request.POST, request.FILES, instance=child)

    if request.method == 'POST' and form.is_valid():
        form.save()
        return redirect('dashboard')

    context = {
        'child': child,
        'form': form
    }

    return render(request, 'edit_child.html', context)

When I render the form in the template, everything works fine minus one thing. The initial values are empty. In past versions of Django, using both request.POST with instance=child allows the instance to shine through and fill the form. But for some odd reason it seems to be accepting request.POST as the initial state rather than the instance. In debugging:

The only issue is the rendering. For the sake of show, here's my template using crispy_forms for the form rendering:

<form role="form" method="post" action="{{ child.get_edit_url }}" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}
    <button type="submit" class="btn btn-default">Save</button>
</form>

Anyone see this before or see something that I'm clearly doing wrong?

Upvotes: 2

Views: 874

Answers (1)

dansackett
dansackett

Reputation: 95

So it turns out that I needed to explicitly set None if a dict was returned for BOTH files and post data:

form = ChildForm(request.POST or None, request.FILES or None, instance=child)

Carry on.

Upvotes: 2

Related Questions