[Django]-How to send object from detail view to another view in Django?

2πŸ‘

βœ…

Then you should make another view for url quiz-assessment and pass the quiz pk as you did above in your assessment view.

 def quiz_assessment(request,pk):
         quiz = Quiz.objects.get (pk=pk)
         return render (request,'assessment_template', {'quiz':quiz}

And in your url,pass the quiz id like this:

         path ('<int:pk>/quiz/assessment /',views.quiz_assessment,name='quiz_assessment')

And in your template you can give url like this:

        < a class="btn" href="{% url 'quiz_assessment' object.pk %}>
πŸ‘€arjun

2πŸ‘

As suggested in the comments by @Robin Zigmond, you can do like this.

#assess*m*nt view
def assessment(request, qid):
    context = {
        'quiz':Quiz.objects.get(id=qid),
    }
    return render(request, 'quiz_app/assessment.html', context)

In the HTML file

#detailview template for quiz
{% extends "quiz_app/base.html" %}
{% block content %}
        <article class="quiz-detail">
            <h1>{{ object.title }}</h1>
            <h2>{{ object.question_amount }} Questions</h2>
            <a class="btn" href="{% url 'quiz-assessment' qid=object.id %}">Start Quiz</a>
        </article>
{% endblock content %}

and in your urls.py change as:

path('quiz_asswssment/?P<int:qid>/', views.assessment, name="quiz_assessment")
πŸ‘€Sammy J

2πŸ‘

Besides, what SammyJ has suggested, You can use the django sessions library or the django cache framework. You can temporarily store the information you need for the next view and access it whenever you want to.

In what Sammy J had suggested, you will always to have make sure that the queryset is passed in the context, otherwise it will not be rendered.

def assesment(self, request, id):
    q = Quiz.objects.get(pk=id)
    request.session["someData"] = q.name
    request.session["qAmount] = q.amount

In your template file

<p>The title is : {{request.session.title}} and the amount is {{request.session.qamount}}

Note: Django sessions do not allow you to set a queryset as a session record, for that, you can use Django Cache framework.

Example

from django.core.cache import cache
cache.set('quiz', q)
getting cache -> cache.get('quiz')

Sessions framework docs : https://docs.djangoproject.com/en/2.2/topics/http/sessions/

Cache framework docs: https://docs.djangoproject.com/en/2.2/topics/cache/

πŸ‘€dotslash227

Leave a comment