Django 中基于类的通用视图的问题
我正在尝试使用基于 Django 类的通用视图编写 CRUD 应用程序。以下是我编写的用于在数据库中创建新用户的代码。
from django.views.generic import CreateView
from django.contrib.auth.decorators import login_required
from django.contrib import messages
class UserCreateView(CreateView):
"""
Display and accept a new user to be created in db
"""
form_class = ProfileForm
template_name = 'userdb/profile_form.html'
success_url = '/organization/users/'
def post(self, request, *args, **kwargs):
messages.success(request, "Success", extra_tags='msg')
return super(UserCreateView, self).post(request, *args, **kwargs)
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(UserCreateView, self).dispatch(*args, **kwargs)
请注意,要添加向用户显示的成功消息,我必须扩展 post 函数。我知道这不是一个好方法,因为当调用此函数时,无法确定提交的表单是否包含有效数据。所以我的问题是,是否有推荐的方法将 Django 消息传递框架与基于类的通用视图相结合?
I'm trying to write a CRUD application using Djangos class based generic views. Following is the code i wrote to create a new user in the db.
from django.views.generic import CreateView
from django.contrib.auth.decorators import login_required
from django.contrib import messages
class UserCreateView(CreateView):
"""
Display and accept a new user to be created in db
"""
form_class = ProfileForm
template_name = 'userdb/profile_form.html'
success_url = '/organization/users/'
def post(self, request, *args, **kwargs):
messages.success(request, "Success", extra_tags='msg')
return super(UserCreateView, self).post(request, *args, **kwargs)
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(UserCreateView, self).dispatch(*args, **kwargs)
Note that to add a success message to be displayed to the user I've had to extend the post function. I know this is not a good way to do this as, when this function gets called it's not decided whether the submitted form contains valid data. So my question is, Is there recommended way of combining Djangos messaging framework with class based generic views?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案取决于您具体希望使用消息传递框架做什么。如果需要为每个
get
请求调用它,那么您自然需要将其放入get
方法中(重点是没有合适的位置来放置此代码)。不管怎样,听起来你正在寻找一个只有在表单有效时才会触发的地方。
CreateView
使用ModelFormMixin
实现了form_valid
方法,该方法仅在成功保存表单时触发。完美的!The answer depends on what specifically you're looking to do with the messaging framework. If it needs to be called for every
get
request you'd naturally need to put it in theget
method (point being there's no one right place to put this code).Anyways, it sounds like you're looking for a place that's only triggered when the form is valid.
CreateView
uses theModelFormMixin
which implements aform_valid
method which is only fired upon successful form saving. Perfect!