【问题标题】:Allowing user to only create certain amount of objects with non-paid account, using Django Stripe (dj-stripe)允许用户使用 Django Stripe (dj-stripe) 仅使用非付费帐户创建一定数量的对象
【发布时间】:2019-11-25 22:15:13
【问题描述】:

我目前有一个个人 CRM 应用程序,允许用户创建联系人,然后为这些联系人创建日志。下面是代码的样子。

views.py

class CreateContact(LoginRequiredMixin, CreateView):
    model = Contact
    template_name = 'network/contacts_list.html'
    form_class = ContactForm

    def get_success_url(self):
        return reverse('home')

    def form_valid(self, form):
        form.instance.contact_owner = self.request.user
        return super(CreateContact, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(CreateContact, self).get_context_data(**kwargs)
        context['contacts'] = Contact.objects.filter(contact_owner=self.request.user)
        return context



class CreateContactLog(LoginRequiredMixin, CreateView):
    model = ContactLog
    template_name = 'network/contact_detail.html'
    fields = ('log_type','body',)

    def get_success_url(self):
        return reverse('contact-detail', kwargs={'id':self.kwargs['id']})

    def form_valid(self, form):
        current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id'])
        form.instance.contact_owner = self.request.user
        form.instance.contact_id = current_contact
        return super(CreateContactLog, self).form_valid(form)

    def get_context_data(self, **kwargs):
        current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id'])
        context = super(CreateContactLog, self).get_context_data(**kwargs)
        context["contact_info"] = current_contact
        context["first_name"] = current_contact.first_name
        context["id"] = current_contact.contact_id
        context['log_entries'] = ContactLog.objects.filter(contact_owner=self.request.user, contact_id=current_contact)
        return context

一切正常。

现在我想开始接受付款,我想将我的应用与 Stripe 集成。最好的方法是使用第三方包dj-stripe

我想要 2 个计划,免费和付费。我想允许免费计划用户最多创建 10 个联系人。阅读 django-stripe 的文档后,我发现我可以使用基于类的视图,但我不明白如何限制特定数量的对象创建。

这是我目前的想法:

  • 也许创建两个类,其中一个允许创建三个对象,另一个允许无限制但需要付款。

  • 也许documentation 中有一个我错过的设置可以帮助解决这个问题。

解决此问题的最佳方法是什么?

如果您需要更多信息,请告诉我。

提前非常感谢您。

最好, 拉苏尔

【问题讨论】:

    标签: django django-models django-templates django-views


    【解决方案1】:

    我会创建一个 util 函数来检查:

    1. 用户有多少联系人
    2. 用户是否有付费计划

    检查 1 是对 contact_owner 的反向关系的直接计数。

    dj-stripe 有 Customer.get_or_create()Customer.has_active_subscription() 方法,您可以在检查 2 中使用。

    然后您可以在form_valid 中检查此实用程序的结果。如果结果为假,可以add an error to the form,然后调用form_invalid

    希望对你有帮助,

    亚历克斯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2020-09-30
      • 1970-01-01
      • 2019-12-31
      • 2021-06-24
      • 2020-09-04
      • 1970-01-01
      相关资源
      最近更新 更多