【问题标题】:how to use one post method two times in differerent views function in django如何在 django 的不同视图功能中使用一个 post 方法两次
【发布时间】:2014-02-12 14:17:04
【问题描述】:

我在 views.py 中有一个 post 方法模板(即 foo_form.html)和两个函数(foo1,foo2),我想在其中使用 post 值。

我的 foo_form.html 在这里

<html>{% load i18n %}
  <head>
  <form method="POST" enctype="multipart/form-data" >
  {% csrf_token %}
    <input type="text" name= "month"> </input>
    <input type="text" name= "year"> </input>
    <input type="submit" value="view">
   </form>

在 foo1 函数中,我需要执行一些任务以及验证月份和年份并重定向到 security_check 页面,我需要检查他是否适合查看该页面。

现在如果他通过了检查任务然后重定向到 foo2 函数。在 foo2 函数中,我必须使用月和年> 我的 forms.py 是这样的

class month_Form(forms.Form):
  Month = forms.IntegerField()
  Year = forms.IntegerField()

我的views.py是这样的

def foo1(request):
  if request.method == 'POST':
    month_form = month_Form(request.POST)
    if pay_form.is_valid():
        # do some task
        return HttpResponseRedirect('/security_check/')
  return render(request, 'foo_form.html', {})

def foo2(request):
  month_form1 = month_Form(request.POST) # I cann't get whether request.method == 'POST': should be there or not?
  month_no = request.POST.get('Month',False)
  # unable to retrieve month_no 
  # and in debug method is showing "GET"

我的 /security_check/ 函数是这样的

def security_check(request):
  if request.method == 'POST':
    month_form = month_Form(request.POST)
    if pay_form.is_valid():
      # validated weather he has the permission to go to foo2
      #redirect to foo2
  #render to security_check_form.html(this is a security que form html)

我正在使用 Django 1.6。提前致谢

【问题讨论】:

  • 在您的示例中,/security_check/ URL 是否应该路由到您的 foo2 视图?目前还不清楚您的示例应该如何工作。
  • 不,不 /security_check/ 是另一个函数
  • 如何重定向到 foo2?
  • 返回 HttpResponseRedirect('/foo2/')
  • 一种可能的解决方案是将foo2 中的逻辑提取到一个可重用的函数中,然后将一个HttpResponseRedirect 返回给它,您将调用新函数。从用户的角度来看,这也会更快,因为您不会重定向他们。

标签: python django python-2.7 django-forms django-views


【解决方案1】:

哦,我是从 Django 那里得到的 doc.

我可以创建 security_check 函数视图,我可以在其中自定义我自己的表单(如 @login required() )

def foo1(request):
   if request.method==POST:
     #retrieve value in POST method 
     #call foo2
     return render (request,destination.html{variables})
   return render(request, 'foo_form.html', {}) 

@user_passes_test(security_check[, login_url=None])
def foo2(postdatas):
  #do some task
  # return tapule on the basis of requirement 

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多