我正在尝试创建一个允许用户编辑其个人资料数据的表单。因此,我希望在用户编辑表单时显示数据库中的最新数据。这是我到目前为止所拥有的:
# models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length=30, blank=True)
birthdate = models.DateField(null=True, blank=True)
def __str__(self):
return self.user.username
# forms.py
class EditProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['location', 'birthdate']
# views.py
class EditProfileFormView(View):
form_class = EditProfileForm
template_name = 'forums/edit-profile.html'
def get(self, request, username):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
raise Http404('The User "' + username + '" could not be found.')
if (not request.user.is_authenticated):
return HttpResponseForbidden()
elif (user.id is not request.user.id):
return HttpResponseForbidden()
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
将表单设置为form_class(None)是什么给了我一个空表单,但是在同一个地方丢弃user.profile会给我一个错误'Profile'对象没有属性'get'
答案 0 :(得分:3)