在使用CreateView时,是否可以使用get_object方法而不是get_initial来预填充Django表单。我试图在数据库表中克隆(主键除外,所有属性都相同)条目。不使用UpdateView,因为它将不会更新现有记录。还是有其他方法可以解决这个问题?
class RequestCloneView(SuccessMessageMixin, CreateView):
model = Request
form_class = RequestAddForm
http_method_names = ['get', 'post']
template_name = 'request_add.html'
success_message = "Request Created!"
def get_initial(self):
initial_data = super(RequestCloneView, self).get_initial()
data = Request.objects.get(req_id=self.kwargs['qid'])
initial_data['req_label'] = data.req_label
initial_data['model'] = data.model
initial_data['version'] = data.version
initial_data['type'] = data.type
initial_data['test'] = data.test
return initial
# def get_object(self):
# return Request.objects.get(req_id=self.kwargs['qid'])
...
它对我有用,但想知道是否可以像对UpdateView那样使用get_object来预先填充表单,而不是手动将每个值分配给initial_data字典?还是其他更好的方法呢?