Saran Prasad
Saran Prasad

Reputation: 165

How to pass database queryset objects from class based views(class SignUp(generic.CreateView)) to templates in Django

views.py

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from .forms import CustomUserCreationForm

class SignUp(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

urls.py

urlpatterns = [
    url(r'signup/', views.SignUp.as_view(), name='signup'),
    url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
]

I used django custom user creation method to sign up users, its working fine. But how to pass objects to templates in my class SignUp. I'm new to class based view. Please help me.

Upvotes: 0

Views: 612

Answers (2)

Tanay Sheth
Tanay Sheth

Reputation: 11

To pass context, you can write

context_object_name = 'username'

Now think like you are making a To Do app and want to print the Tasks as per their You can then do the following inside your class based view,

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tasks'] = context['tasks'].filter(user=self.request.user)
        context['count'] = context['tasks'].count()

In this way, you can write the database queryset in class based views.

If you want a perfect guide or source code to learn the django authentication i.e. login and logout user functions, I suggest you to go once through this tutorial, It is a todo list app which will cover your doubts

To Do list app with django authentication and queryset in class based views

The sourcecode for the above is here:

Source code

Upvotes: 1

ruddra
ruddra

Reputation: 51988

You need to override get_context_data method in SignUp class, like this:

class SignUp(generic.CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

    def get_context_data(self, **kwargs):
       context = super(SignUp, self).get_context_data(**kwargs)
       context['your_qset'] = YourModel.objects.all()
       return context

and use it in template:

{% for obj in your_qset %}
   {{ obj }}
{% endfor %}

Upvotes: 0

Related Questions