无法在Django中使用Python视图访问表单值

时间:2019-05-02 01:41:31

标签: django python-3.x django-forms django-views

我试图从动态填充数据库查询中输入字段数量的表单中访问表单值,但是我无法获取这些值。

def count_add(request):

    items = Item.objects.filter(username=request.user)

    if request.method == 'POST':
        form = CountAddForm(request.POST)

        for item in items:
            print(request.POST[item])
            # if request.POST[item] != None:
            #     print(item)
            #     rating = form.save(commit=False)
            #     rating.username = request.user
            #     rating.item = item
            #     rating.date = datetime.now()
            #     rating.rating = request.POST[item]
            #     rating.save
            #     form = CountAddForm()

    return render(request, 'count_add.html', {'items': items})
<div class="container">
    <div class="row">
        <div class="col s12 opacity">
            <h4 class="card-title center-align white-text">Rate Your Items Below</h4>
            <form method="POST" class="center-align white-text"> {% csrf_token %}

                <ul class="center-align white-text">
                    {% for item in items %}
                    <li class="input-field col s12">
                        <select name="{{ item }}" class="browser-default">
                            <option value="" disabled selected>{{ item }}</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                        </select>
                    </li>
                    {% endfor %}

我的愿望是从输入字段中获取一个值并将其保存在数据库中。当我实际上确实检索当前值时,我没有返回。

编辑: 我曾尝试使用is_valid和cleaned_data [item],但该表单似乎从未验证过。

1 个答案:

答案 0 :(得分:0)

致电is_valid,然后使用cleaned_data

def count_add(request):
    ...
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CountAddForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required

https://docs.djangoproject.com/en/2.2/topics/forms/#the-view