如何在Django模板中区分两种形式?

时间:2020-09-18 18:30:14

标签: python html django forms templates

我直接在Django HTML模板中创建表单。 在此模板中,我有2种形式。

{% extends 'base.html' %}

{% block title %}
   <title>Add Groups</title>
{% endblock %}


{% block content %}

<h1>Add Groups</h1>

<form method="post">
   {% csrf_token %}
   <label>User</label>
   <input type="text" name="user_name"/>
   <label>Password</label>
   <input type="text" name="password"/>

   <input type="submit" value="Submit">
</form>

{% if groups %}
   <form method="post">
       {% csrf_token %}
   {% for group in groups %}

       <div class="div_group">
           <h3>
               <input type="checkbox" name="{{group.id}}" value="{{group.name}}">

               {{group.name}}</h3>
           <div> 
               <span>Id:</span>
               {{group.id}}
               <br>
               <a href="{{group.link}}">{{group.link}}</a>
               <br>
               <span>Role:</span>
               {{group.role}}
               <br>
               <span>Tags:</span>
               {{group.tags}}

           </div>
       </div>

   {% endfor %}
       <input type="submit" value="Add Grupos">
   </form>
{% endif %}

<br>

{% endblock %}

在views.py中,我试图与表单区分开。 我要求输入仅以第一种形式出现的字段

def admin_add_group(request):
   if request.user.is_staff and request.user.is_staff:
       context = {}

       if request.method == 'POST':
           if 'user_name' in request.POST:
               user_name= request.POST['user_name']
               mendeley_password = request.POST['password']    
               
               try:
                   # login mendeley
                   md.authenticate(mendeley_user, mendeley_password)
                   groups = md.get_groups()
                   context['groups'] = groups
               except Exception as exc:
                   context['errors'] = [str(exc)]
           else:
               c = request.POST
               print(c)
               # redirect to groups view.

       return render(request, 'admin_add_group.html', context)

   else:
       context = {}
       return render(request, 'admin_add_group.html', context)

还有另一种方法可以知道发出邮寄请求的形式吗? 也许要添加隐藏的输入?仅出于此目的,我想知道哪种是最佳做法。

2 个答案:

答案 0 :(得分:0)

我用两种形式的name="form_id"添加了一个隐藏字段

 <form method="post">
    {% csrf_token %}    
    <input type="hidden" name="form_id" value="groups_data">
    ...

<form method="post">
    {% csrf_token %}
    <input type="hidden" name="form_id" value="user_data">
    ...

在视图中我要求它:

 if request.method == 'POST':
        if request.POST['form_id'] == 'user_data':
        ...

答案 1 :(得分:-1)

您可以命名提交按钮name="form1submit",然后通过在request.POST字典中查找此名称来询问是否按下了该按钮。

if 'form1submit' in request.POST:
    # is the form 1
else:
    # is the form 2