使用get_或create Django
这是本书的延续 问题是代码不允许创建新对象,因为使用get_或create Django,django,forms,django-formwizard,Django,Forms,Django Formwizard,这是本书的延续 问题是代码不允许创建新对象,因为thing=get\u object\u或\u 404(thing,pk=id) 如何使用此函数使用get\u或\u create?或者是否有其他更好的方法在该函数中创建新对象?谢谢你的想法 一种方法是: class CreateWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
thing=get\u object\u或\u 404(thing,pk=id)
如何使用此函数使用
get\u或\u create
?或者是否有其他更好的方法在该函数中创建新对象?谢谢你的想法 一种方法是:
class CreateWizard(SessionWizardView):
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
def done(self, form_list, **kwargs):
id = form_list[0].cleaned_data['id']
try:
thing = Thing.objects.get(pk=id)
instance = thing
except:
thing = None
instance = None
if thing and thing.user != self.request.user:
raise HttpResponseForbidden()
if not thing:
instance = Thing()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
setattr(instance, field, value)
instance.user = self.request.user
instance.save()
return render_to_response('wizard-done.html', {
'form_data': [form.cleaned_data for form in form_list],})
class CreateWizard(SessionWizardView):
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
def done(self, form_list, **kwargs):
id = form_list[0].cleaned_data['id']
try:
thing = Thing.objects.get(pk=id)
instance = thing
except:
thing = None
instance = None
if thing and thing.user != self.request.user:
raise HttpResponseForbidden()
if not thing:
instance = Thing()
for form in form_list:
for field, value in form.cleaned_data.iteritems():
setattr(instance, field, value)
instance.user = self.request.user
instance.save()
return render_to_response('wizard-done.html', {
'form_data': [form.cleaned_data for form in form_list],})