python 基于FormView类的django视图示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 基于FormView类的django视图示例相关的知识,希望对你有一定的参考价值。

from django.views import generic

class EmailPreferenceView(generic.FormView):
    form_class = EmailPreferenceForm

    def get(self, *args, **kwargs):
        # You can access url variables from kwargs
        # url: /email_preferences/geeknam > kwargs['username'] = 'geeknam'
        # Assign to self.subscriber to be used later
        self.subscriber = get_subscriber(kwargs['username'])

    def post(self, request, *args, **kwargs):
        # Process view when the form gets POSTed
        pass

    def get_initial(self):
        # Populate ticks in BooleanFields
        initial = {}
        for s in self.subscriber.events.all():
            initial[s.value_id] = True
        return initial

    def get_form(self, form_class):
        # Initialize the form with initial values and the subscriber object
        # to be used in EmailPreferenceForm for populating fields
        return form_class(
            initial=self.get_initial(),
            subscriber=self.subscriber
        )

    def get_success_url(self):
        # Redirect to previous url
        return self.request.META.get('HTTP_REFERER', None)

    def form_valid(self, form):
        messages.info(
            self.request,
            "You have successfully changed your email notifications"
        )
        return super(EmailPreferenceView, self).form_valid(form)

    def form_invalid(self, form):
        messages.info(
            self.request,
            "Your submission has not been saved. Try again."
        )
        return super(EmailPreferenceView, self).form_invalid(form)

email_preferences = EmailPreferenceView.as_view()

以上是关于python 基于FormView类的django视图示例的主要内容,如果未能解决你的问题,请参考以下文章

如何使用基于类的视图在同一模板中使用两个不同的 Django 表单

Django 使用 URL 参数在基于类的视图中查询数据库

python Django(极端情况):如何在FormView(CreateView / UpdateView)的form_valid方法中引发表单无效并添加错误消息

基于类的视图和装饰器

Django:使用 FormView 时可能有多种形式?

Django:如何使用动态(非模型)数据预填充 FormView?