0

我有以下基于类的 TemplateView,我希望我的 TemplateView 像 UpdateView。但我不太确定在哪里使用实例参数设置表单。我在 get_context_data 中尝试过,但没有奏效。有任何想法吗 ?

class ProfileUpdateView(generic.TemplateView):
    template_name = "profile/update_profile.html"

    def dispatch(self, *args, **kwargs):
        if self.request.user.is_authenticated():
            return super(ProfileUpdateView, self).dispatch(*args, **kwargs)
        else:
            return HttpResponseRedirect('/profiles/login')

    def get_context_data(self, *args, **kwargs):
        context = {}
        try:
            Profile.objects.get(user__id=self.request.user.id)
            user = Profile.objects.get(user__id=self.request.user.id)
            context['profile_form'] = profile_form(data=request.POST, instance=user)
        except:
            context['profile_form'] = ProfileForm(data=self.request.POST)
            context['profile'] = Profile.objects.filter(user=self.request.user.id)
            context['experiences'] = Experience.objects.filter(user=self.request.user.id)
            context['education'] = Education.objects.filter(user=self.request.user.id)
            context['award'] = Award.objects.filter(user=self.request.user.id)
            context['publication'] = Publication.objects.filter(user=self.request.user.id)
            context['membership'] = Membership.objects.filter(user=self.request.user.id)
            context['patent'] = Patent.objects.filter(user=self.request.user.id)
            context['certificate'] = Certificate.objects.filter(user=self.request.user.id)
            context['language'] = Language.objects.filter(user=self.request.user.id)
        return context

    def post(self, request, *args, **kwargs):
        if self.request.POST:
            profile_form = ProfileForm(data=request.POST)
            if profile_form.is_valid():
                profile = profile_form.save(commit=False)
                profile.user = request.user
                profile.save()
                return HttpResponseRedirect('/')
4

1 回答 1

1

尝试使用 CBV(CreateView),然后使用initial和 defget_initial(self):

看到这个链接,我想这可以帮助你。第 9-11 节和第 9-12 节。

于 2018-09-04T00:52:09.440 回答