这是模型。我创建了自己的用户模型
class Profile(models.Model):
user = models.OneToOneField(User)
favorite_food = models.CharField(max_length=100)
def set_password(self, raw_password):
self.user.set_password(raw_password)
以下是观点:
class UserFormView(View):
form_class = UserForm
template_name = 'templates/core/profile_form.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
return render(request, self.template_name, {'form': form})
这是UserForm
class UserForm(forms.ModelForm):
username = forms.CharField(max_length=10)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Profile
fields = ['username', 'password', 'favorite_food']
这里似乎有什么问题?它还说Profile has no user
我尝试将其更改为AbstractUser但是,它还显示有关反向访问器的错误
答案 0 :(得分:0)
尝试从表单中排除用户并将save方法添加到表单中:
class ProfileForm(forms.ModelForm):
username = forms.CharField(max_length=10)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Profile
fields = ['username', 'password', 'favorite_food']
exclude = ['user']
def save(self, user = None, force_insert=False, force_update=False, commit=False):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
profile = super(ProfileForm, self).save(commit=commit)
if user:
profile.user = user
profile.set_password(password)
profile.save()
return profile
在你看来:
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
profile = form.save(user = request.user, commit=False)