[英]How to pass database queryset objects from class based views(class SignUp(generic.CreateView)) to templates in Django
views.py视图.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网址.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.我使用 django 自定义用户创建方法来注册用户,它工作正常。 But how to pass objects to templates in my class SignUp.
但是如何将对象传递给我的类 SignUp 中的模板。 I'm new to class based view.
我是基于类的视图的新手。 Please help me.
请帮我。
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 ie 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如果你想要一个完美的指南或源代码来学习 django 身份验证,即登录和注销用户功能,我建议你通过本教程一次,这是一个待办事项列表应用程序,它将覆盖你的疑虑
To Do list app with django authentication and queryset in class based views 在基于类的视图中使用 django 身份验证和查询集列出应用程序
The sourcecode for the above is here:上面的源代码在这里:
You need to override get_context_data method in SignUp
class, like this: 您需要在
SignUp
类中重写get_context_data方法,如下所示:
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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.