简体   繁体   English

使用Django createview创建相关对象

[英]Created related objects using django createview

Hey All I am using Django 1.10.7 嘿,我正在使用Django 1.10.7

I am creating a form that creates a store location to a store. 我正在创建一个表单,用于创建商店的商店位置。 Now what I want to happen is to have the store already associated with the store location when the form is loaded. 现在,我想做的是在加载表单时使商店已经与商店位置相关联。

The url has the proper id of the foreign key of the store ex: localhost:8000//office/dealer/1/location/create. 网址具有商店外键的正确ID,例如:localhost:8000 // office / dealer / 1 / location / create。 and I see that that the store key is in the request keyword arguments. 并且我发现store密钥在request关键字参数中。 But I can't get how to associate that into the form. 但是我不知道如何将其关联到表单中。 Any help would be really appreciated 任何帮助将非常感激

Here is how I have my code 这是我的代码

#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'),

Why not using : 为什么不使用:

def form_valid(self, form):
    pk = self.kwargs.get("dealer_pk", None)
    form.instance.dealer = pk
    return super(DealerLocationCreateView, self).form_valid(form)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM