spoke spoke - 2 months ago 8x
Python Question

Django update model entry using form fails

I want to update a model entry using a form. the problem is that instead of updating the entry it creates a new entry.

def edit(request, c_id):
instance = get_object_or_404(C, id=int(c_id))

if request.POST:
form = CForm(request.POST, instance=instance)
if form.is_valid():

return redirect('/a/b', c_id)
form = CForm(instance=instance)

args = {}
args['form'] = form
args['c_id'] = c_id

return render_to_response('a/b.html', args)

HTML code:

<form action="/a/edit/{{ c_id }}/" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
{% endfor %}
<input type="submit" value="Submit"/>

CForm class code

class CForm(forms.ModelForm):
class Meta:
model = C
fields = ['name', 'code']


You're checking the request for a POST method incorrectly. request.POST isn't a boolean, it contains a dictionary of post variables and is always going to have the CSRF token in it so it will always be "truthy". What you need is request.method.

Instead of:

if request.POST:

Replace it with:

if request.method == "POST":