3

我已经使用了这个问题的答案,但由于某种原因,我没有得到好的结果。

我正在尝试为我的编辑表单和我的添加表单使用相同的模板。这是我的urls.py

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

我的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))

我的forms.py

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

最后是我的模板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>

出于某种原因,这是抛出 404:

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

我可能在这里遗漏了一些简单的东西,但在这一点上,我至少需要另一双眼睛。

提前致谢!

4

1 回答 1

3

您获得 404 是因为/student/edit/在尾部需要一个 id,否则没有路线,并且当您来自时,/student/new/您还没有 id。/student/edit/为在 POST 上创建记录时创建路由和视图并将逻辑放入其中以处理这种情况。

于 2012-05-21T00:38:15.430 回答