0

Hy. I want to modify a record for my database. I have:

models.py

class People(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
email = models.EmailField(blank = True)
grade = models.CharField(max_length = 2)

def __unicode__(self):
    return '%s %s' % (self.first_name, self.last_name)

class PeopleForm(ModelForm):
class Meta:
    model = People 

    fields = ['first_name', 'last_name', 'email', 'grade']

views.py

def modify(request, person_pk):
title = 'Creating new program'
template = 'modify.html'

data = People.objects.get(pk = person_pk)

form = PeopleForm(instance=data)
context = {'form': form}
if request.POST:
    form = PeopleForm(request.POST)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('/peoples/'))
    else:
        return render_to_response(template, context, context_instance=RequestContext(request))
return render_to_response(template, context, context_instance=RequestContext(request))

urls.py

url(r'^modify/(?P<person_pk>.*)$', views.modify, name='modify'),

forms.py

class PeopleForm(forms.ModelForm):

class Meta:
    model = People 
    fields = ('first_name', 'last_name', 'email', 'grade')

And template

<form action="/peoples/" method="post">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" name="submit" value="Modify">
</form>

I don't know why when I click the modify button, I complete the fields and when I press the button to the previous page, the entry field from database doesn't update. Do you have any suggestions?

1 Answer 1

1

The main thing I see that looks odd is that your HTML form tag has "/peoples/" as its action, but that URL is not bound to your form processing view in the code we see here. I mostly use action="" in my forms, so that it submits to the same URL that rendered the view.

Secondly, when you redefine your python variable form in your view:

if request.POST:
    form = PeopleForm(request.POST)

You have already assigned the old form to the context, and do not reassign it. So if your form is not valid, you won't see the errors or submitted values.

This is of course irrelevant if your form action is wrong such that the view is not called with the POST data.

Sign up to request clarification or add additional context in comments.

2 Comments

If I'm deleting "/peoples/" from HTML form tag then it will create a new record instead of modifying the existing one.
Try passing in instance to your form constructor along with the POST data: form = PeopleForm(request.POST, instance=data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.