[Answer]-Why there is no way to change data bound to Django form?

1👍

It is not very clear what you are trying to ask, but here is a simple example of a view with a model form:

from django.shortcuts import render

def myview(request):
    form = MyModelForm(data=request.POST or None)
    if form.is_valid()
        saved_obj = form.save()
        return redirect('success_url')
    return render(request, 'myform_template.html', {'form': form})

When you visit the view initially you will get a blank form (because request.POST is empty so the form data is None i.e. the form is not ‘bound’)

You should set your form action in the HTML to post to the same url, simplest way is blank action: <form action="" method="post">

When you submit the form request.POST will contain the submitted data, so the form will be bound. If the form is valid we save a new model instance, then it is good practice to redirect. If the form is not valid the form will be redisplayed with the data the user submitted, along with error messages.

If you want to edit an existing model instance the pattern looks like:

from django.shortcuts import render, get_object_or_404

def myview(request, pk):
    existing_obj = get_object_or_404(MyModel, pk=pk)
    form = MyModelForm(data=request.POST or None, instance=existing_obj)
    if form.is_valid()
        saved_obj = form.save()
        return redirect('success_url')
    return render(request, 'myform_template.html', {'form': form})

In this case when you initially load the page the form will be filled with the existing values from the model instance instead of a blank form.

All of the above can be done in less lines of code using Django class-based views, but they hide what is happening behind a layer of abstraction, so I think probably it’s useful to see the basic form handling pattern of Django.

See docs for the render and get_object_or_404 shortcut functions here:
https://docs.djangoproject.com/en/dev/topics/http/shortcuts/

Leave a comment