python - 无法使用基于类的 View 和 django 表单更新数据

标签 python django django-forms django-views

我无法使用 django 表单和基于类的 View 更新用户配置文件实例。 POST 请求使用正确的参数发送,模板正确重定向,但不幸的是用户配置文件没有更新。

请注意,我是 Django 新手,所以欢迎提出建议。

models.py:

class UserProfile(models.Model):
    objects = models.Manager()
    user = models.OneToOneField(User)
    search_range = models.IntegerField(default=150)

    def __str__(self):
        return self.user.username

forms.py:

class HomeForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('search_range',)

views.py:

class HomeView(TemplateView):
    template_name = 'home/home.html'

    def get(self, request):
        form = HomeForm()

        args = {'form': form}
        return render(request, self.template_name, args)

    def post(self, request):
        form = HomeForm(request.POST, instance=request.user.userprofile)
        if form.is_valid():
            form.save()
            return redirect('home:home')

        args = {'form': form}
        return render(request, self.template_name, args)

urls.py:

urlpatterns = [
    url(r'^$', HomeView.as_view(), name='home')
]

home.html:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Submit</button>
</form>

最佳答案

你的代码看起来不错。用户个人资料可能已保存,但由于您没有将 instance 关键字参数传递给 get 方法中的表单,因此 search_range 已预先填充使用默认值 (150)。

def get(self, request):
    form = HomeForm(instance=request.user.userprofile)

    args = {'form': form}
    return render(request, self.template_name, args)

关于python - 无法使用基于类的 View 和 django 表单更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42647107/

相关文章:

django - 在 Django 1.8 中创建多个对象而无需多次点击数据库

python - 删除时出现外键错误

Django:如何使用模态作为更新对象的形式

Django ModelForm : accessing a field's value in the view template

python - 使用 ImageField 对 Django ModelForm 进行单元测试,测试显示无效表单

python - 为什么将 hg.Vec3() 向量传递给由它修改的 Python 函数?

python - urllib2 中的数据与 Safari 的 Web Inspector 中的数据不同

python - Django - 更改字段验证消息

python - Python ntplib 响应中的所有字段是什么,它们是如何使用的?

python - praw:获取 subreddit 中随机帖子的正文和标题