Django-在视图之间传递数据和重定向

时间:2019-06-24 12:11:24

标签: django django-templates django-views

我正在制作一个与在线测验有关的项目,而当我想将数据从一个视图传递到另一个视图时,我陷入了困境。我的目标是在提交表单后,在一个视图中从用户那里获得一个测验名称并将其传递给另一个视图。

我已经看过2次了:

  • add()-具有第一种形式的测验名称,并重定向到具有测验名称的add_questions
  • add_questions()-捕获提交的测验的名称并显示问题的另一种形式

views.py


    @login_required
    def add(request):
        if request.method == 'POST':
            QuizForm = QuizNameForm(request.POST)
            if QuizForm.is_valid():
                # create a quiz
                new_quiz = QuizForm.save(commit=False)
                new_quiz.owner = request.user
                new_quiz.save()

                request.session['quiz_id'] = new_quiz.id
                print("Quiz saved, now I'm redirecting to add_questions")
                return redirect(add_questions)
                #return HttpResponseRedirect('add_questions') ---  didn't work
                #return render(request, 'quiz/add_questions.html', {}) --- didn't work
        else: 
            QuizForm = QuizNameForm()
        return render(request, 'quiz/add.html', {'quizForm': QuizForm})

    @login_required
    def add_questions(request):
        print("Add questions here! I've captured a quiz named: {}".format(quiz.name))
        quiz = DB_questions.objects.get(id=request.session['quiz_id'])
        if request.method == 'POST':
            print("ok, post method - cool")
        #create a question/answer forms
        else:
            print("Got into else in add_questions view")
            Question_form = QuestionForm()

        return render(request, 'quiz/add_questions.html', {'quiz_name': quiz.name, 'question_form': Question_form })

我用于添加测验名称的模板-templates / add.html


<div class="container">
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <!-- Get name of the quiz-->
            <form action="{% url 'add' %}" method="post">
                {% csrf_token %}
                {{ quizForm.name }}
                <input class="btn btn-success w-100" type="submit" value="Proceed">
            </form>
        </div>
        <div class="col-md-4"></div>
    </div>
</div>

显示名称和问题形式的模板-templates / add_question.html


<div class="row">
    <div class="col-md-5"></div>
    <h2 class="select_title"> Quiz: {{ quiz_name }}</h2>
    <div class="col-md-5"></div>
</div>

<form action="{% url 'add_questions' %}" method="post">
    {% csrf_token %}
    {{ question_form.content }}
</form>

最后是urls.py

    urlpatterns = [
        # ...
        url(r'^add', views.add, name='add'),
        url(r'^add_questions', views.add_questions, name='add_questions'),
    ]

主要问题是,提交测验名称后,系统会将测验添加到数据库中,但不会将我重定向到“ add_questions”。它仍然停留在“添加”视图中。

我也不确定这是否是实现它的正确方法。我已经找到了许多不同的实现方式,但是没有一个适合我。 (诸如HttpResponseRedirect(),redirect(),render()等解决方案)

总结:

1)在这种情况下,以表单提交数据后在视图之间传输数据的最佳方法是什么?

2)我应如何重定向到另一个视图,以使其显示正确的模板?

1 个答案:

答案 0 :(得分:0)

据我所知,这应该适合您: views.py:

    @login_required
    def add(request):
        if request.method == 'POST':
            QuizForm = QuizNameForm(request.POST)
            if QuizForm.is_valid():
                # create a quiz
                new_quiz = QuizForm.save(commit=False)
                new_quiz.owner = request.user
                new_quiz.save()

                print("Quiz saved, now I'm redirecting to add_questions")
                return render(request, 'quiz/add_questions.html', {'quiz_id': new_quiz.id})
        else: 
            QuizForm = QuizNameForm()
        return render(request, 'quiz/add.html', {'quizForm': QuizForm})

    @login_required
    def add_questions(request):
        quiz = DB_questions.objects.get(id=request['quiz_id'])
        if request.method == 'POST':
            print("ok, post method - cool")
        #create a question/answer forms
        else:
            print("Got into else in add_questions view")
            Question_form = QuestionForm()

        return render(request, 'quiz/add_questions.html', {'quiz_name': quiz.name, 'question_form': Question_form })

这样,您既可以呈现模板,也可以通过请求对象(而非会话)发送 quiz_id