简体   繁体   English

创建表单时Django意外的关键字参数

[英]Django unexpected keyword argument when creating form

Motivation 动机

I'm currently creating a to-do-list app in django for practice. 我目前正在django中创建待办事项应用程序以进行练习。 What I'm trying to do now is to give the "user" the option to submit multiple to-do items at once. 我现在想要做的是让“用户”可以一次提交多个待办事项。 To do so, I display the form multiple times and then retrieve the items from each form individually. 为此,我多次显示该表单,然后分别从每个表单中检索项目。

Attempt & Error 尝试与错误

Here's the form in question: 这是有问题的表格:

class AddItemForm(forms.Form):
    name = forms.CharField(max_length=60, label='Item Name')
    priority = forms.IntegerField(required=False,
            widget=forms.Select(choices=Item.PRIORITY))
    due_date = forms.DateTimeField(required=False, label='Due Date')

However, when I try to create a form using keyword arguments (the lines of interest are in the for loop): 但是,当我尝试使用关键字参数创建表单时(感兴趣的行在for循环中):

def add_item(request):
    if request.method == 'POST':
        r = request.POST
        names = r.getlist('name')
        priorities = r.getlist('priority')
        due_dates = r.getlist('due_date')
        for i in xrange(len(names)):
            form = AddItemForm(
                       name=names[i],
                       priority=priorities[i],
                       due_date=due_dates[i],
                   )
            if form.is_valid():
                item = form.cleaned_data
                Item.objects.create(**item) 
        return HttpResponseRedirect('/todo')

    form = AddItemForm()
    try:
        num_items = xrange(int(request.GET.get('n', 1)))
    except ValueError:
        num_items = xrange(1)
    return render(request, 'add_item.html', 
            {'form': form, 'num_items': num_items})

I get the following error message: 我收到以下错误消息:

Exception Type: TypeError
Exception Value:    
__init__() got an unexpected keyword argument 'priority'

I don't understand what's going on since I do have priority as a field in AddItemForm. 我不知道发生了什么,因为我确实具有AddItemForm中的字段的优先级

HTML 的HTML

Here's the template html if it helps: 这是模板html(如果有帮助的话):

<!DOCTYPE html>
<html>
  <head> <title>Add item</title> </head>
  <body>
    <form method="post">{% csrf_token %}
      {% for i in num_items %}
        <div>{{ form }}</div>
      {% endfor %}
      <input type="submit">
    </form>

    <br><br>
    <form action="/todo" method="get">
      <input type="submit" value="Go back to To-Do List">
    </form>
  </body>
</html>

Well, that's not how forms work. 好吧,这不是表单的工作方式。 You're not supposed to process the POST arguments first, and you can't pass data for individual fields as arguments like that. 您不应该首先处理POST参数,也不能像这样传递各个字段的数据。 You're simply supposed to pass request.POST into the form instantiation as-is. 您只需request.POST原样将request.POST传递到表单实例化中。

The way to do a set of multiple identical forms is to use a formset . 处理一组多个相同表单的方法是使用一个formset You can then pass the POST data straight into the formset instantiation, and get validated forms out. 然后,您可以将POST数据直接传递到表单集实例中,并获得经过验证的表单。

Note that since your form is being used to create model instances, you may want to consider using a modelform (and a model formset, on the same page). 请注意,由于您的形式被用于创建模型的情况下,你可能要考虑使用的ModelForm (和模型表单集,在同一页上)。

Django the form. Django表单。 init () accepts an 'initial' keyword argument, you could have set the initial values of the form in the following way: init ()接受“ initial”关键字参数,您可以通过以下方式设置表单的初始值:

form = AddItemForm(initial = {
                      'name':names[i],
                      'priority':priorities[i],
                      'due_date':due_dates[i],
                   }
               )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM