我是用户的更新视图,以便他们可以更改其设置。我要这样做,以便当用户单击“编辑我的信息”按钮时,他们将被带到一个表单,其中的字段已经填写了该用户数据库中的内容。当不显示用户数据时,我已经能够用新信息更新数据库。我还能够在表单中显示用户数据,但是更新不再起作用。
我已经尝试了来自堆栈溢出的多个建议,所以我知道代码中一定有错误,导致我发现的所有内容都表达了同样的意思。我对django还是很陌生,所以我有些困惑,希望能得到我所有的帮助。
这是我的观点中的相关代码。py
class ProfileUpdate(UpdateView):
# model = Prof
# fields = ['privacy_level', 'bio', 'profile_picture']
model = Prof
form_class = ProfForm
template_name = 'user/prof_form.html'
# def form_valid(self, form):
# user = form.save(commit=True)
# # password = form.cleaned_data['password']
# # print(form)
# self.fields['bio'].required = False
# self.fields['bio'].initial = "sadfasdf"
# # user.set_password(password)
# user.save()
# return redirect('user:index')
def get(self, request, pk, *args, **kwargs):
try:
prof = Prof.objects.get(id=self.kwargs['pk'])
print(prof)
print("hello")
return redirect('user:index')
except:
return redirect('user:index')
def get_initial(self):
return {
'privacy_level': '1',
'bio': 'Hi there',
'profile_picture': '1',
}
def get_form(self, form_class=ProfForm):
prof = Prof.objects.get(id=self.kwargs['pk'])
form = ProfForm() #breaks updating, but allows the filling in of the forms
form.fields['privacy_level'].initial = prof.privacy_level
form.fields['bio'].initial = prof.bio
form.fields['profile_picture'].initial = prof.profile_picture
form = super(ProfileUpdate, self).get_form(form_class) # will update, won't autofill
return form
这是我表格中的代码:
class ProfForm(forms.ModelForm):
class Meta:
model = Prof
fields = ['privacy_level', 'bio', 'profile_picture']
预先感谢