Django FBV到CBV

时间:2017-02-03 14:42:15

标签: django

我正在重构我的代码并将所有FBV更改为CBV。但其中一个看起来并不是很好。所以我要求为我的例子提供正确的CBV。

这里是我的FBV

@login_required
def profile(request, username):
    user_main = get_object_or_404(User, username=username)
    user_profile = UserProfile.objects.get_or_create(user=user_main)[0]
    form = UserProfileForm({'website': user_profile.website, 'picture': user_profile.picture})
    if request.method == 'POST' and request.user == user_main:
        form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
        if form.is_valid():
            form.save(commit=True)
            return redirect(profile, username)
        else:
            print(form.errors)

    context_dict = {'user_main': user_main, 'user_profile': user_profile, 'form': form}
    return render(request, 'rango/profile.html', context=context_dict)

这就是我所拥有的:

@method_decorator(login_required, name='dispatch')
class ProfileView(DetailView, FormMixin):
    template_name = 'rango/profile.html'
    context_object_name = 'user_main'
    form_class = UserProfileForm

    def get_object(self, queryset=None):
        user_main = get_object_or_404(User, username=self.kwargs['username'])
        return user_main

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)
        context['user_profile'] = self.get_user_profile()
        return context

    def get_initial(self):
        user_profile = self.get_user_profile()
        return {'website': user_profile.website, 'picture': user_profile.picture}

    def get_form_kwargs(self):
        kwargs = super(ProfileView, self).get_form_kwargs()
        kwargs['instance'] = self.get_user_profile()
        return kwargs

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid and request.user == self.object:

            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        profile = form.save(commit=True)
        return redirect('profile', self.kwargs['username'])

    def form_invalid(self, form):
        print(form.errors)
        return super(ProfileView, self).form_invalid(form)

    def get_user_profile(self):
        return UserProfile.objects.get_or_create(user=self.object)[0]

我想我解决这个问题的方式看起来很糟糕。请告诉我使CBV看起来更好的正确方法。

0 个答案:

没有答案