django使用ModelForm一步保存数据

Posted oysq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django使用ModelForm一步保存数据相关的知识,希望对你有一定的参考价值。

参考 django 官方文档 https://docs.djangoproject.com/zh-hans/2.0/topics/forms/modelforms/

首先,创建的form类,会有个meta类,

meta类里的要定义一个model,即是form表单连接的model,然后fields里是你所需要的model的字段,

就像这样

1     class Meta:
2         model=Model_Supply
3         fields = (Supply_user,ModelTitle,Introduction,ModelContext,ModelUses,Algorithm,Qualifications,Price,Photo,Appraisal,SellingMethod,TradeClass_S,TargetClass_S) 

 

此时,在后端使用save方法时,若数据通过后台获取,而不是前端获取,则可以在view中使用如下方法:

1  form = Model_Supply_Form(request.POST,request.FILES)
2  
3  if form.is_valid():          
4        uid = id
5        new_model = form.save(commit=False)    
6        new_model.Supply_user = uid
7        new_model.save()
此时,就可以保存你所需要的数据到数据库中了

以上是关于django使用ModelForm一步保存数据的主要内容,如果未能解决你的问题,请参考以下文章