如何在基于类的视图中设置实例变量?

时间:2017-11-24 11:49:28

标签: python django

我想检查用户是否在基于类视图的初始化中处于特定组中。

然后在get_form()get_context_data()

等多种方法中使用该变量

但是我收到错误:

File "/projects/hr_project/entries/views.py", line 117, in get_form_class
    if self.is_manager:
AttributeError: 'EntryCreateView' object has no attribute 'is_manager'

以下是基于类的视图:

class EntryCreateView(
        LoginRequiredMixin,
        FormView,
        MessagePermissionRequiredMixin,):
    '''Class based view to enter new timesheet entries
    '''
    form_class = None
    template_name = 'entries/entry_form.html'
    permission_required = None
    permission_denied_message = 'You do not have the permission to create an entry for that user'

    def dispatch(self, request, *args, **kwargs):
        # Initialise variables and check permissions once
        # Set the intial date
        if self.kwargs.get('date'):
            self.date = self.kwargs.get('date')
        else:
            self.date = self.get_form().fields['date'].initial

        self.date = str(self.date)
        self.date_val = datetime.strptime(self.date, '%Y-%m-%d')
        self.is_manager = False
        manager_group = Group.objects.get(name='Managers')
        if manager_group in request.user.groups.all():
            self.is_manager = True

        # Set the user and permission
        self.permission = True
        self.user = request.user
        if self.is_manager:
            # Check user is manager
            self.user = self.kwargs.get('user')
        else:
            if self.kwargs.get('user') == request.user.id:
                self.user = self.kwargs.get('user')
            else:
                self.permission = False
        super().dispatch(request, *args, **kwargs)

    def has_permission(self):
        ''''Override how permissions are checked
        '''
        return self.permission

    def get_context_data(self, *args, **kwargs):
        context_data = super().get_context_data(*args, **kwargs)
        return context_data

1 个答案:

答案 0 :(得分:0)

如果我正确地解释了这一点,那么问题在于is_manager在对象的实例上不可用。

如果在is_manager方法中将dispatch声明为实例变量,则只有在该类上调用此特定方法时,才会在该类的实例上设置它。

如果您创建了班级的a对象,请执行a.dispatch(your_arguments)您应该能够正确访问a.is_manager

通常,如果您希望您的类具有实例变量,则可以在您的classe __init__函数中执行此操作,例如:

class Test:
  def __init__(self):
    self.is_manager = False

希望有所帮助。