簡體   English   中英

將 JS 變量發布到 Django 視圖並在單獨的模板中顯示為上下文變量

[英]Post JS variables to Django view and display as context variables in separate template

我正在努力實現三件事:

  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

我究竟做錯了什么?

感謝@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>

並且結果模板現在有一個 post 方法的views.py也返回上下文:

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 }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM