我的第一个基于Django类的视图

时间:2018-03-14 01:37:05

标签: django python-3.x

我迷失在Django Class Based Views中。我有一个基于工作函数的视图来创建用户“配置文件”。配置文件是User对象的扩展。功能版本是:

@verified_email_required
def create(request):
    if request.method == 'POST':
        #
        # should have *just* created a profile. save it then display it
        form = ProfileForm(request.POST)

        if form.is_valid():
            profile = form.save(commit=False)
            profile.user = request.user
            profile.save()

            my_render = render(request, 'Members/index.html', {
                'profile': profile,
                'profileState': "display"
            })
        else:
            #
            # form has issues. send it back to the create form to fix.
            my_render = render(request, 'Members/profile.html', {
                'profileForm': form,
                'profileState': "editForCreate"
            })
    else:
        #
        # no profile. Create one
        form = ProfileForm()

        my_render = render(request, 'Members/profile.html', {
            'profileForm': form,
            'profileState': "create"
        })

    return my_render

所以现在我想在CBV中复制这种一般行为。文档说它将自己处理大部分内容 - 但我迷失在细节中。到目前为止,我有:

@verified_email_required
class Create(CreateView):
    model = Profile
    template_name = 'Members/profile.html'
    form_class = ProfileForm
    success_url = 'Members/index.html'
    http_method_names = ['GET', 'POST']

    def form_valid(self, form):
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()

我相信它会处理一般的POST和GET逻辑。它会将form传递给template_name,成功创建案例会有success_url

如何将额外的上下文“profileState”标签传递给模板和成功网址?如何将“个人资料”发送到成功网址?

我的想法是覆盖get_context_data,但我不知道如何“有条件地”传递标签和/或个人资料。

另外,在form_valid我需要访问request.user。我该怎么做?

0 个答案:

没有答案