django更新视图和传递上下文

时间:2014-12-04 10:11:54

标签: python django view django-context

我有更新视图:

class GeneralUserUpdateView(UpdateView):

    model = GeneralUser
    form_class = GeneralUserChangeForm
    template_name = "general_user_change.html"

    def dispatch(self, *args, **kwargs):
        return super(GeneralUserUpdateView, self).dispatch(*args, **kwargs)

    def post(self, request, pk, username):

        self.pk = pk
        self.username = username
        self.gnu = GeneralUser.objects.get(pk=self.pk)
        #form = self.form_class(request.POST, request.FILES)
        return super(GeneralUserUpdateView, self).post(request, pk)

    def form_valid(self, form, *args, **kwargs):
        self.gnu.username = form.cleaned_data['username']
        self.gnu.email = form.cleaned_data['email']
        self.gnu.first_name = form.cleaned_data['first_name']
        self.gnu.last_name = form.cleaned_data['last_name']
        self.gnu.address = form.cleaned_data['address']
        self.gnu.save()

        return redirect("user_profile", self.pk, self.username)

在此视图中,我想传递一个上下文:

context['picture'] = GeneralUser.objects.get(pk=self.pk)

我确实尝试了get_context_data但我无法访问那里的pk .. 我正在进行更新吗?我怎样才能在那里传递那个上下文?

1 个答案:

答案 0 :(得分:1)

你根本不应该凌驾post。所有这些逻辑都应该在get_context_data中发生。

事实上,您的所有替代都不是必需的。您在form_valid中所做的一切都将通过标准格式保存完成。而重写dispatch只是为了调用超类是没有意义的。

您的视图应该只是这样,没有被覆盖的方法:

class GeneralUserUpdateView(UpdateView):
    model = GeneralUser
    form_class = GeneralUserChangeForm
    template_name = "general_user_change.html"
    context_object_name = 'picture'

(虽然你想将GeneralUser的实例称为"图片")似乎有点奇怪。

修改以重定向到特定网址,您可以定义get_success_url

    def get_success_url(self):
        return reverse("user_profile", self.kwargs['pk'], self.kwargs['username'])