在这里,我制作了一个表单,用于从用户那里获取组名,然后尝试使用用户输入的名称创建组名,但它没有给我预期的结果。它既不会引发任何错误,也不会将数据保存在数据库中。 当我使用group_name = request.POST['name']
而不是cleaned_data
时,它会抛出:
django.utils.datastructures.MultiValueDictKeyError: 'name'
我在这里做错了什么?
forms.py
class AddUserGroupForm(forms.Form):
name = forms.CharField(max_length=255)
views.py
def add_user_groups(request):
form = AddUserGroupForm()
#group_name = request.POST['name']
#print(group_name,'group_name')
if form.is_valid():
group_name = form.cleaned_data['name']
permissions = request.POST.getlist('user_permissions')
new_group = Group.objects.create(name=group_name)
new_group.permissions.add(permissions)
messages.success(request,'New group added.')
return redirect('organization:view_groups')
return render(request,'organization/add_user_groups.html',{'user_permissions':user_permissions,'form':form})
模板
<form action="{% url 'organization:add_user_group' %}" method="post">
{% csrf_token %}
<label> Group Name : </label>
<input type="text" class="form-control required" placeholder="Enter
group name" name="name">
<label>Permissions:</label>
{% for permission in user_permissions %}
<input name="user_permissions" type="checkbox" id="permission-{{permission.id}}"
value="{{permission.id}}">
<label for="permission-{{permission.id}}"> {{permission.name}}</label>
</div>
{% endfor %}
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
因为如果您想访问数据,您的cleaned_dataform = AddUserGroupForm()
为
空
做form = AddUserGroupForm(request.POST)
以便根据请求清理数据POST
并对其调用is_valid()
。
如果您希望添加验证,请将其添加到表单类clean
方法中,请参见此处
应该是这样的
def add_user_groups(request):
if request.method == 'POST':
form = AddUserGroupForm(request.POST)
#group_name = request.POST['name']
#print(group_name,'group_name')
if form.is_valid():
group_name = form.cleaned_data['name']
permissions = request.POST.getlist('user_permissions')
new_group = Group.objects.create(name=group_name)
new_group.permissions.add(permissions)
messages.success(request,'New group added.')
return redirect('organization:view_groups')
else:
#empty form for get request
form = AddUserGroupForm()
return render(request,'organization/add_user_groups.html',{'user_permissions':user_permissions,'form':form})