我已经使用了this question的答案,但出于某种原因我没有得到好结果。
我正在尝试为我的编辑表单和添加表单使用相同的模板。这是我的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/
我可能在这里错过了一些简单的东西,但此时我至少需要另外一套眼睛。
提前致谢!
答案 0 :(得分:2)
你得到了404,因为/student/edit/
需要在尾端有一个id,否则没有路由,当你来自/student/new/
时,你还没有id。为/student/edit/
创建路径和视图,并在其中放置逻辑以处理在POST上创建记录时的情况。