完成了modelForm保存逻辑

master
RogerWork 1 year ago
parent 241404ca37
commit cd63549cbe
  1. 1
      form_demo/urls.py
  2. 23
      form_demo/views.py

@ -8,5 +8,6 @@ urlpatterns = [
path('userinfo/', views.userinfo_form),
path('uploadimg/', views.img_file_form),
path('userinfomodel/', views.userinfo_model_form),
path('userinfomodelsave/', views.userinfo_model_from_save),
re_path(r'media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}),
]

@ -49,8 +49,31 @@ def userinfo_model_form(request):
print(f.clean())
print(f.cleaned_data['username'])
print(f.data)
f.save()
else:
errors = f.errors
print(errors)
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f, 'errors': errors})
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f})
def userinfo_model_from_save(request):
if request.method == 'GET':
a = UserBaseInfo.objects.get(id=1)
myform = UserInfoModelForm(instance=a)
return render(request, 'form_demo/userinfomodels.html', {'form_obj': myform})
else:
f = UserInfoModelForm(request.POST)
if f.is_valid():
# 直接保存
# f.save()
# 延时保存
user = f.save(commit=False)
# user.username = request.username
print(user)
user.save()
else:
errors = f.errors
print(errors)
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f, 'errors': errors})
return render(request, 'form_demo/userinfomodels.html', {'form_obj': f})

Loading…
Cancel
Save