【问题标题】:Edit/Add objects using the same django form使用相同的 django 表单编辑/添加对象
【发布时间】:2012-05-27 12:57:58
【问题描述】:

我已经使用了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/

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

提前致谢!

【问题讨论】:

  • 一件事是:该 URL 需要看起来像 http://192.168.1.3:5678/app/student/edit/789/ 或类似的 - 您的 URL 中没有 ID,因此是 404。
  • 是的——但您可以从模板中看到我发布到那个学生 ID,它应该发布到那个 URL。我应该更具体一点——当我添加一条记录时,它是 404'ing。这是否与尚未生成的 id 有关?

标签: python django


【解决方案1】:

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

【讨论】:

  • 是的 - 就是这样。我没有将student 传递给模板,所以id 在任何情况下都不会被填充。我必须通过 student 然后将我的 POST 调用更改为尾部斜杠。成功了。
猜你喜欢
  • 2011-01-24
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多