3

I already used the answer to this question, but for some reason I'm not getting a good result.

I'm trying to use the same template for my edit form and my add form. Here's my urls.py:

url(r'^app/student/new/$', 'edit_student', {}, 'student_new'),
url(r'^app/student/edit/(?P<id>\d+)/$', 'edit_student', {}, 'student_edit'),

And my views.py:

def edit_student(request, id=None, template_name='student_edit_template.html'):
if id:
    t = "Edit"
    student = get_object_or_404(Student, pk=id)
    if student.teacher != request.user:
        raise HttpResponseForbidden()
else:
    t = "Add"
    student = Student(teacher=request.user)

if request.POST:
    form = StudentForm(request.POST, instance=student)
    if form.is_valid():
        form.save()

        # If the save was successful, redirect to another page
        redirect_url = reverse(student_save_success)
        return HttpResponseRedirect(redirect_url)

else:
    form = StudentForm(instance=student)

return render_to_response(template_name, {
    'form': form,
    't': t,
}, context_instance=RequestContext(request))

And my forms.py:

class StudentForm(ModelForm):
class Meta:
    model = Student
    exclude = ('teacher',)

And finally my template student_edit_template.html:

<h1>{{ t }} Student</h1>
<form action="/app/student/edit/{{ student.id }}" method="post"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

For some reason, this is throwing a 404:

Page not found (404)
Request Method: POST
Request URL:    http://192.168.1.3:5678/app/student/edit/

I'm probably missing something easy here, but at this point I need another set of eyes on it at the very least.

Thanks in advance!

Community
  • 1
  • 1
Matthew Calabresi
  • 487
  • 2
  • 11
  • 20
  • One thing is: that URL needs to look like `http://192.168.1.3:5678/app/student/edit/789/` or somesuch -- there's no ID in your URL, hence the 404. – fish2000 May 21 '12 at 00:22
  • Right -- but you can see from the template that I'm posting to that student ID, it should be posting to that URL. I should have been more specific -- it's 404'ing when I add a record. Is this something to do with the id not being generated yet? – Matthew Calabresi May 21 '12 at 00:42

1 Answers1

3

You're getting the 404 because /student/edit/ requires an id at the tail end otherwise there's no route, and when you're coming from /student/new/ you don't have an id yet. Create a route and view for /student/edit/ and put logic in there to handle the case for when you're creating a record on POST.

mVChr
  • 49,587
  • 11
  • 107
  • 104
  • Yep - that was it. I wasn't passing `student` to the template, so `id` was never going to get populated in any case. I had to pass `student` then change my POST call to have a trailing slash. That did the trick. – Matthew Calabresi May 21 '12 at 01:16