Django-为同一字段提交具有多个输入的表单 [英] Django - Submitting form with multiple inputs for same field

查看:106
本文介绍了Django-为同一字段提交具有多个输入的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预警:我对Django(通常是Web开发)很陌生.

Forewarning: I'm very new to Django (and web development, in general).

我正在使用Django托管基于Web的UI,该UI将从简短的调查中获取用户输入,并通过我在Python中开发的一些分析将其输入,然后在UI中呈现这些分析的可视化输出

I'm using Django to host a web-based UI that will take user input from a short survey, feed it through some analyses that I've developed in Python, and then present the visual output of these analyses in the UI.

我的调查包括10个问题,询问用户他们对特定主题的认同程度.

My survey consists of 10 questions asking a user how much they agree with a a specific topic.

用于调查的UI示例:

UI输入屏幕示例

对于 models.py ,我有2个字段:Question&选择

For models.py, I have 2 fields: Question & Choice

class Question(models.Model):
    question_text = models.CharField(max_length=200)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

我希望用户选择他们对所有10个问题的回答,然后单击提交"一次提交所有回答,但是我在Django中如何处理该问题上遇到了麻烦.

I am wanting to have a user select their response to all 10 questions, and then click submit to submit all responses at once, but I'm having trouble with how that would be handled in Django.

这是我正在使用的html表单,但是此代码段在每个问题之后都放置了一个提交"按钮,并且一次只允许一次提交.

Here is the html form that I'm using, but this code snippet places a "submit" button after each question, and only allows for a single submission at a time.

注意:下面的代码为每次迭代创建一个特定于问题的表格.

{% for question in latest_question_list %}
    <form action="{% url 'polls:vote' question.id %}" method="post">
    {% csrf_token %}
        <div class="row">
            <div class="col-topic">
                <label>{{ question.question_text }}</label>
            </div>
            {% for choice in question.choice_set.all %}
                <div class="col-select">
                    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
                    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
                </div>
            {% endfor %}
        </div>

    <input type="submit" value="Vote" />
    </form>
{% endfor %}

我对如何在一次提交中获得多个输入(全部用于问题/选择)并将其返回给 views.py

I'm interested in how I would take multiple inputs (all for Question/Choice) in a single submission and return that back to views.py

添加VIEWS.PY

当前,我的 views.py 脚本处理单个问题/选择对.一旦弄清如何允许用户一次提交所有10个问题/选择的表格,我将需要在 views.py 中反映出来.这可能是问题的第二部分.首先,如何通过一个提交"按钮使用户对所有10个问题提交所有答案?其次,如何设置 views.py 一次接受多个值?

Currently, my views.py script handles a single question/choice pair. Once I figure out how to allow users to submit the form one time for all 10 question/choices, I will need to reflect this in views.py. This could sort of be part 2 of the question. First, how do I enable a user to submit all of their responses to all 10 questions with one "submit" button? Second, how do I setup views.py to accept more than 1 value at a time?

views.py

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/survey.html', {
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()

        return HttpResponseRedirect(reverse('polls:analysis'))

请让我知道是否需要其他上下文.

提前谢谢!

-C

推荐答案

理想情况下,应该使用Django Forms完成此操作. Django表单具有widgets,而RadioSelect是其中之一.您可以使用它来呈现表单并立即获得每个问题的答案. 但这将需要您当前的处事方式进行很多更改.

Ideally, this should have been done with Django Forms. Django forms have widgets and RadioSelect is one of them. You can use that to render your form and get the answer to each question at once. But that will need a lot of change in the way you are currently doing things.

因此,您可以做的是,单击提交"按钮,收集所有问题/选择对,并通过POST请求立即发送它们.

So, what you can do is, on click on a submit button, collect all the question/choice pairs and send them at once with a POST request.

{% for question in latest_question_list %}
    <form>
        <div class="row">
            <div class="col-topic">
                <label>{{ question.question_text }}</label>
            </div>
            {% for choice in question.choice_set.all %}
                <div class="col-select">
                    <input type="radio" name="choice" value="{{ choice.id }}" />
                    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
                </div>
            {% endfor %}
        </div>
    </form>
{% endfor %}
<input id="submit-btn" type="submit" value="Vote" />

<script>
    $(document).on('click', '#submit-btn', function(event){
        var response_data = []
        var question_objs = $('.col-topic');
        var choice_objs = $('.col-select');

        for(i=0;i<question_objs.length;i++){
            var question_text = $(question_objs[i]).find('label').text();
            var choice_id = $(choice_objs[i]).find('input').val();
            var choice_text = $(choice_objs[i]).find('label').text();
            var question_choice = {
                "question_text": question_text,
                "choice_id": choice_id,
                "choice_text": choice_text
            }
            response_data.push(question_choice);
        }
        $.ajax({
            type: "POST",
            url: "url_to_your_view",
            data: response_data,
            success: function(response){
                alert("Success");
            }
        });
    });
</script>

这就是您的视图外观.

def question_choice_view(request):
    if request.method == "POST":
        question_choice_data = request.POST['data']
        # further logic

现在,question_choice_data是词典列表.列表中的每个字典将具有用户响应的question_text,choice_text和choice ID.

Now, question_choice_data is a list of dictionaries. Each dict in the list will have the question_text, choice_text and choice id of user's response.

这篇关于Django-为同一字段提交具有多个输入的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆