嘿所有我正在使用Django 1.10.7
我正在创建一个为商店创建商店位置的表单。现在我想要发生的是在加载表单时让商店已经与商店位置相关联。
url具有商店ex的外键的正确ID:localhost:8000 // office / dealer / 1 / location / create。我看到商店密钥在请求关键字参数中。但我无法知道如何将其与表格联系起来。任何帮助都会非常感激
以下是我的代码
#views.py
class DealerLocationCreateView(CreateView):
model = models.DealerLocation
fields = ['dealer'
'dealer_location_name',
'dealer_location_mailing_address',
'dealer_location_mailing_city',
'dealer_location_mailing_state',
'dealer_location_mailing_zipcode',
'dealer_location_mailing_phone',
'dealer_location_shipping_address',
'dealer_location_shipping_city',
'dealer_location_shipping_state',
'dealer_location_shipping_zipcode',
'dealer_location_shipping_phone'
]
def form_valid(self, form):
form.instance.dealer = self.request.dealer_pk
return super(DealerLocationCreateView, self).form_valid(form)
-
# urls.py
url(r'^dealer/(?P<dealer_pk>\d+)/location/create', DealerLocationCreateView.as_view(), name='new-location'),
答案 0 :(得分:2)
为什么不使用:
def form_valid(self, form):
pk = self.kwargs.get("dealer_pk", None)
form.instance.dealer = pk
return super(DealerLocationCreateView, self).form_valid(form)