无法使用基于类的视图和django表单更新数据

时间:2017-03-07 11:26:24

标签: python django django-forms django-views

我无法使用django表单和基于类的视图更新userprofile实例。使用适当的参数发送POST请求,模板正确重定向,但遗憾的是userprofile没有更新。

请注意我是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>

1 个答案:

答案 0 :(得分:1)

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

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

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