这是表单页面
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput, required=False)
class Meta():
model = User
fields = ['username', 'email', 'password']
class ProfileForm(forms.ModelForm):
class Meta():
model = Profile
fields = ['pic']
&这是视图页面
from django.shortcuts import render
from .forms import UserForm, ProfileForm
def register(request):
if(request.method == 'POST'):
userform = UserForm(request.POST)
profileform = ProfileForm(request.POST)
if(userform.is_valid() and profileform.is_valid()):
user = userform.save()
user.set_password(user.password)
user.save()
profile = profileform.save(commit=False)
profile.user = user
if('pic' in request.FILES):
profile.pic = request.FILES['pic']
profile.save()
else:
print(userform.errors, profileform.errors)
else:
userform = UserForm()
profileform = ProfileForm()
return render(request, 'register.html', {'userform':userform,
'profileform':profileform})
当我提交密码或图片时,它不会将用户保存到管理区域,并说需要密码并且图片没有上传
答案 0 :(得分:0)
从表单保存密码时,应该使用commit=False
,而不是像普通形式那样使用set()
。
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput, required=False)
class Meta:
model = Users
fields =['email', 'password', 'username']
class ProfileForm(forms.ModelForm):
class Meta():
model = Profile
fields = ['pic']
from django.shortcuts import render
from .forms import UserForm, ProfileForm
def register(request):
if(request.method == 'POST'):
form = UserForm(request.POST or None)
profileform = ProfileForm(request.POST or None)
if(userform.is_valid() and profileform.is_valid()):
userform = form.save(commit=False)
userform.password = make_password(form.cleaned_data['password'])
userform.save()
profile = profileform.save(commit=False)
profile.user = user
if('pic' in request.FILES):
profile.pic = request.FILES['pic']
profile.save()
else:
print(userform.errors, profileform.errors)
else:
userform = UserForm()
profileform = ProfileForm()
return render(request, 'register.html', {'userform':userform,
'profileform':profileform})
也请查看此link。