清理CBV

时间:2018-11-28 13:06:03

标签: python django methods django-class-based-views

我有这个符合预期的课程

class UpdateView(TemplateView):

    def get(self, request, username):
        id = User.objects.get(username = username).id
        user = get_object_or_404(User, id = id)
        employee = get_object_or_404(Employee, user_id = id)
        form_user = UserForm(instance=user)
        form_employee = EmployeeForm(instance=employee)
        args = {'form_user': form_user,'form_employee': form_employee, 'username': username}
        return render(request, 'user/update.html', args)

    def post(self, request, username):
        id = User.objects.get(username = username).id
        user = get_object_or_404(User, id = id)
        employee = get_object_or_404(Employee, user_id = id)
        form_user = UserForm(request.POST, instance=user)
        form_employee = EmployeeForm(request.POST, instance=employee)
        if form_user.is_valid() and form_employee.is_valid():
            form_user.save()
            form_employee.save()
            return redirect('user:list')
        args = {'form_user': form_user, 'form_employee': form_employee, 'username': username}
        return render(request, 'user/update.html', args)

我的问题是get和post方法都使用相同的id,user和employee变量。我该如何清理?

我知道我可以创建类似的渲染方法

def render(self, request, username):
    args = {'form_user': form_user, 'form_employee': form_employee, 'username': username}
    return render(request, 'user/update.html', args)

然后致电

return self.render(request)

在get和post方法的末尾,因此我也不必两次定义args,但是当前这与用户名冲突。这就是为什么我要首先使用3个变量解决问题的原因。

1 个答案:

答案 0 :(得分:1)

由于此视图有两种形式,因此它不适用于任何基于通用类的视图。

基于功能的视图将避免重复的上下文,并且易于遵循。

def update_employee(request, username):
    user = get_object_or_404(User, username=username)
    employee = get_object_or_404(Employee, user=user)
    if request.method == 'POST':
        form_user = UserForm(request.POST, instance=user)
        form_employee = EmployeeForm(request.POST, instance=employee)
        if form_user.is_valid() and form_employee.is_valid():
            form_user.save()
            form_employee.save()
            return redirect('user:list')
    else:
        form_user = UserForm(instance=user)
        form_employee = EmployeeForm(instance=employee)

    args = {'form_user': form_user,'form_employee': form_employee, 'username': username}
    return render(request, 'user/update.html', args)