1
我有一個CreateView,我需要從一個對象輸出數據。它工作正常,下面用get_object替換get_context_data在Django 1.5中
class MyCreateView(CreateView):
model = ModelName
def dispatch(self, request, *args, **kwargs):
self.project = get_object_or_404(Project, slug=kwargs['project'])
return super(MyCreateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs):
context_data = super(MyCreateView, self).get_context_data(*args, **kwargs)
context_data.update({'object': self.project})
return context_data
def form_valid(self, form):
obj = form.save(commit=False)
obj.project = self.project
obj.save()
return HttpResponseRedirect(self.get_success_url())
這個代碼,但我不知道是否有可能用get_object()
更換dispatch()
和get_context_data()
。我已經嘗試了下面的代碼,但它並沒有給我這個項目作爲對象。
class MyCreateView(CreateView):
model = ModelName
def get_object(self, queryset=None):
return = Project.objects.filter(slug=self.kwargs['project'])
def form_valid(self, form):
obj = form.save(commit=False)
obj.project = self.object
obj.save()
return HttpResponseRedirect(self.get_success_url())