将JS变量发布到Django视图并在单独的模板中显示为上下文变量

时间:2019-12-03 15:55:30

标签: python django

我正在努力实现三件事:

  1. 使用标准HTML表单在一个模板中收集一些用户输入(以下questions.html);
  2. 将该输入内容发布到我的views.py;最后
  3. 将该输入作为上下文变量显示在单独的模板中(下面的results.html)。

一旦我开始使用它,我将在views.py中对输入进行一些处理,然后再将一些输出作为上下文变量传递给我-但首先我需要弄清楚从用户那里移出的基本原理在一个模板中输入-> views.py->在另一个模板中的上下文变量。

此外,由于我不想保存任何用户数据,因此我故意不接触任何数据库。

这是我的questions.html所拥有的,收集了年龄和受教育程度:

<script type="text/javascript">
    $(document).ready(function(){
        $('#submit_answers').submit(function (event) {
            var user_age = document.getElementById("age-choice").value;
            var user_education = document.getElementById("education-choice").value;
            $.ajax({
                type:"POST",
                url:"{% url 'results' %}",
                data : {
                    'age': user_age,
                    'education': user_education,
                    'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val()
                },
            })
        }
    )});
</script>

<p>Please answer the following questions:</p>

<p>What is your age?</p>
<form action="" method="GET" id="age-dropdown">
    {% csrf_token %}
    <select class="browser-default custom-select" id="age-choice">
        <option value="18-30">18-30</option>
        <option value="30-40">30-40</option>
        <option value="40-50">40-50</option>
        <option value="50-65">50-65</option>
        <option value="65-100">Over 65</option>
    </select>
</form>

<p>What is your highest level of education?</p>
<form action="" method="GET" id="education-dropdown">
    {% csrf_token %}
    <select class="browser-default custom-select" id="education-choice">
        <option value="None">None</option>
        <option value="GCSE">GCSE</option>
        <option value="A-level">A-level</option>
        <option value="University">University</option>
        <option value="Postgraduate">Postgraduate</option>
    </select>
</form>

<form id="submit_answers" method="post">
    {% csrf_token %}
    <input type="submit" name="submit_answers" class="btn btn-primary btn-sm pull-right" value="Submit" />
</form>

这是我的urls.py

urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('questions/', QuestionsView.as_view(), name='questions'),
    path('results/', ResultsView.as_view(), name='results'),
]

这是我的views.py

class QuestionsView(TemplateView):
    template_name = 'questions.html'

class ResultsView(TemplateView):
    template_name = 'results.html'

    def answers(request):
        if request.method == 'POST':
            context = {}
            context["age"] = request.POST['age']
            context["education"] = request.POST['education']
            return context

还有results.html

<p>Results:</p>
Age: {{ age }} <br />
Education: {{ education }}

有了上面的内容,我在终端机上得到了这个

Method Not Allowed (POST): /results/
Method Not Allowed: /results/
[03/Dec/2019 15:43:22] "POST /results/ HTTP/1.1" 405 0
Method Not Allowed (POST): /questions/
Method Not Allowed: /questions/
[03/Dec/2019 15:43:22] "POST /questions/ HTTP/1.1" 405 0

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

感谢@DanielRoseman和@Matthias的建议。我遵循丹尼尔(Daniel)的建议改用表格,而马蒂亚斯(Matthias)的建议则删除JS,如下所示:

首先填写表单forms.py

EDUCATION_CHOICES= [
    ('none', 'None'),
    ('gcse', 'GCSE'),
    ('alevel', 'A-level'),
    ('university', 'University'),
    ]

class UserInputForm(forms.Form):
 age = forms.IntegerField(label='Enter your age')
 education = forms.CharField(label='What is your highest level of education?', widget=forms.Select(choices=EDUCATION_CHOICES))

然后是表单模板userinputform.html

<form action="/results/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

结果列表中的views.py现在具有一个post方法,该方法也返回上下文:

class HomePageView(TemplateView):
    template_name = 'home.html'

class ResultsView(TemplateView):
    template_name = 'results.html'

    def post(self, request):
        context = {}
        context["age"] = request.POST['age']
        context["education"] = request.POST['education']
        return render(request, 'results.html', context)

def userinputform(request):
    form = UserInputForm()
    return render(request, 'userinputform.html', {'form':form});

最后,results.html

<p>Results:</p>
Age: {{ age }} <br />
Education: {{ education }}