我正在尝试使用基于标准类的视图和表单库在 Django 中创建一个对象。我的表单中的三个字段依赖于从 URL 模式捕获的域变量。我的问题是:
- 我如何访问
domain
内部CreateSubscription
以便我可以设置Subscription.site
为Site.objects.filter(domain=domain)[0]
? - 如何限制呈现的下拉字段,
CreateSubscriptionForm
以便plan
仅显示SubscriptionPlan.objects.filter(site=Site.objects.filter(domain=domain)[0])
并payment_profile
限制为PaymentProfile.objects.filter(user=request.user)
?
为清楚起见,in 中的域r'^subscribe/(?P<domain>\w+\.\w+)/$'
与我自己站点的域无关。框架在django.contrib.sites
这里帮不了我。
提前感谢您帮助我解开所有这些 CBV 方法。:)
URL 模式是:
from django.conf.urls import patterns, url
from accounts.views import *
url(r'^subscribe/(?P<domain>\w+\.\w+)/$',
CreateSubscription.as_view(), name='subscribe_to_site'),
)
有问题的观点是:
from accounts.forms import *
from accounts.models import *
class CreateSubscription(CreateView):
model = Subscription
form_class = CreateSubscriptionForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(CreateSubscription, self).form_valid(form)
相关型号有:
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class PaymentProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
class SubscriptionPlan(models.Model):
site = models.ForeignKey(Site)
name = models.CharField(max_length=40)
class Subscription(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
site = models.ForeignKey(Site)
plan = models.ForeignKey(SubscriptionPlan)
payment_profile = models.ForeignKey(PaymentProfile)
最后,我的表格是:
from accounts.models import *
class CreateSubscriptionForm(forms.ModelForm):
class Meta:
model = Subscription
exclude = ('user', 'site', )