Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django使用数据库中的数据获取表单_Python_Django - Fatal编程技术网

Python Django使用数据库中的数据获取表单

Python Django使用数据库中的数据获取表单,python,django,Python,Django,我试图创建一个表单,允许用户编辑他们的个人资料数据。因此,我希望在用户编辑表单时显示来自数据库的最新数据。以下是我到目前为止的情况: # models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birthdate = mod

我试图创建一个表单,允许用户编辑他们的个人资料数据。因此,我希望在用户编辑表单时显示来自数据库的最新数据。以下是我到目前为止的情况:

# 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”

请尝试用实例填充表单

form = self.form_class(instance=user.profile)
注意:使用标准可能会更容易