Python Наследование и Django - PullRequest
0 голосов
/ 22 февраля 2020

Я просто впервые пытаюсь наследовать в приложении Django, и у меня возникают проблемы.

У меня есть два класса, ProjectDetailView и ProjectDetailViewWithLinks, которые наследуются от ProjectDetailView. Я в основном хочу запустить набор функций из базового класса ( init и затем buildContextData). После этого я хочу добавить к контексту данные, используя функцию с именем __buildPrevAndNext, а затем завершить функцию get. Я приложил некоторый код. __Init , кажется, работает правильно, но когда я перехожу к super () .__ buildContextData, он продолжает работать неправильно и не go в базовый класс:

class ProjectDetailView(View):

    def __init__(self):
        self.__contextData = None
        self.__intPK = None
        self.__intLangID = None

    def __buildContextData(self, request,  **kwargs):
        '''
        This is used to build the context data that we are going to send to the template.
        I have done it this way because I want to build two versions of the class.   One
        that has a previous/next project link, but another class that does not.   This base
        class does not have the previous/next link.
        '''

        # Get the primary key of the Project and the corresponding MyProject object
        self.__intPK = self.kwargs['pk']
        project = MyProject.objects.get(pk=self.__intPK)

        # get the formatted date
        formatedDate = project.date.strftime("%d-%b-%Y")

        # Either throw a 404 or get the group id of the training course
        if not project.language:
            raise Http404

        # Store the language id
        self.__intLangID = project.language.id

        # Build the contextData
        self.__contextData = {
            'project': project,
            'formatedDate': formatedDate,
            'language': project.language,
        }


    def get(self, request, **kwargs):

        # Build the context data
        self.__buildContextData(request, **kwargs)

        # Now send the data to the template
        return render(request, 'project_detail.html', context=self.__contextData)

class ProjectDetailViewWithLinks(ProjectDetailView):

    def __init__(self):
        super().__init__()

    def __buildContextData(self, request,  **kwargs):
        super().__buildContextData(request, **kwargs)

    def __buildPrevAndNext(self, request):
        '''
        This should be run after __buildContextData and adds the extra data into the context for displaying
        the previous and next links.
        '''

        # Filter TrainingCourse table to a list containing the same group id of this course
        filtProjects = MyProject.objects.filter(language_id=self.__intLangID)

        # Get the next course from this list and the previous course from this list
        nextProject = filtProjects.filter(pk__gt=self.__intPK)
        if len(nextProject)>0:
            nextProject = nextProject[0]

        prevProject = filtProjects.filter(pk__lt=self.__intPK)
        if len(prevProject)>0:
            prevProject = prevProject[len(prevProject)-1]

        # Add the previous and next to the context
        self.__contextData['next'] = nextProject
        self.__contextData['prev'] = prevProject


    def get(self, request, **kwargs):

        # First, build the context data in a similar manner to the ProjectDetailView class
        self.__buildContextData(request, **kwargs)

        # Next, add the next and prev data onto the context data
        self.__buildPrevAndNext(request)

        # Finally render the template
        return render(request, 'project_detail.html', context=self.__contextData)

Не могли бы вы объяснить что я делаю неправильно и даже не go в функцию базового класса.

Спасибо

Марк

1 Ответ

0 голосов
/ 22 февраля 2020

Переименуйте ваш метод, чтобы иметь единственное нижнее подчеркивание:

def _buildContextData(self, request,  **kwargs):

Триггеры двойного начального подчеркивания искажение имени .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...