Django: saving multiple modelforms simultaneously (complex case) -
well, may simple case i'm having tough time figuring out.
i have 2 user registration funnels (corporate & else). when corporate user creates user instance through registration form, them input secondary forms create related instances (based on website , organization_contact models).
i know how solve making additional synchronous or asynchronous requests, i'd user fill out 3 forms , submit 1 click.
my issue here other 2 forms rely on user foreign key field. i've made field "null=true, blank=true" can validate , save forms without foreign key, want add key both model instances.
i thought validate 3 forms, save userform, , use model queryset return new user.id (all in 1 view). add user_id value other 2 form dictionaries (websiteform , organization_contactform).
it work so:
def register_company(request): if request.method=='post' uform=usercreationform(request.post, prefix='user') sform=siteform(request.post, prefix='site') oform=orgform(request.post, prefix='site') if uform.is_valid() , sform.is_valid() , oform.is_valid(): uform.save() user=user.objects.get(email__iexact=uform.cleaned_data['email']) uid=unicode(user.id) #now i'd add uid siteform , orgform dictionaries , save both instances
problems: 1) not sure if can save modelform , return model instance queryset in single view
2)i i'm not sure because couldn't passed problem of trying pass variable queryset.
the manager method seems not accept variable there. assume because passed equivalent hardcoded string , worked.
ok, thinking creating new manager method (email) accepted variable argument (the cleaned email field) , retrying process of saving 1 modelform, retrieving model id data, , saving other modelforms.
i thought might able handle issue through post save signal.
just general direction here helpful. need starting point.
are these modelform
s?
if request.method=='post' uform=usercreationform(request.post, prefix='user') sform=siteform(request.post, prefix='site') oform=orgform(request.post, prefix='site') if uform.is_valid() , sform.is_valid() , oform.is_valid(): # save returns object user = uform.save() # commit = false doesn't save db. site = sform.save(commit=false) site.user = user site.save() org = oform.save(commit=false) org.user = user org.save()
update regarding comments: why spread form saving logic around multiple areas , files (signals, form save) when can in 1 place?
the code more readable, , save lines of code. unless it's going used globally.
Comments
Post a Comment