我认为你需要:
from django.shortcuts import get_object_or_404
class ProductCreate(CreateView):
"""Creates a Product for a Shop."""
model = Product
def form_valid(self, form):
"""Associate the Shop with the new Product before saving."""
form.instance.shop = self.shop
return super(CustomCreateView, self).form_valid(form)
def dispatch(self, *args, **kwargs):
"""Ensure the Shop exists before creating a new Product."""
self.shop = get_object_or_404(Shop, pk=kwargs['shop_id'])
return super(ProductCreate, self).dispatch(*args, **kwargs)
def get_context_data(self, **kwargs):
"""Add current shop to the context, so we can show it on the page."""
context = super(ProductCreate, self).get_context_data(**kwargs)
context['shop'] = self.shop
return context
我希望它有帮助!:)
您不妨看看超级方法的作用。
(免责声明:无耻的自我宣传。)