0
我想在使用基於標準類的視圖和表單庫的Django中創建一個對象。我的表單中的三個字段依賴於從URL模式捕獲的域變量。我的問題是:Django:在基於類的視圖和表單中訪問URL變量
- 如何訪問
domain
內CreateSubscription
,這樣我可以設置Subscription.site
到Site.objects.filter(domain=domain)[0]
? - 如何限制從
CreateSubscriptionForm
呈現的下拉字段,以便僅顯示SubscriptionPlan.objects.filter(site=Site.objects.filter(domain=domain)[0])
而payment_profile
僅限於PaymentProfile.objects.filter(user=request.user)
?
爲了清晰起見,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',)
太棒了。奇蹟般有效。謝謝,Ngenator! – Wes 2013-03-19 23:54:17
沒問題,很高興我能幫上忙。 – Ngenator 2013-03-20 00:26:10