Matthew Calabresi
Matthew Calabresi

Reputation: 487

Edit/Add objects using the same django form

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!

Upvotes: 3

Views: 4138

Answers (1)

mVChr
mVChr

Reputation: 50185

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.

Upvotes: 3

Related Questions