Как передать два шаблона в один класс на основе представлений - PullRequest
0 голосов
/ 27 февраля 2020

У меня одна проблема с представлением шаблона django.

У меня два URL

1) Для текущего профиля пользователя

2) Для его команды mates

urls.py

path('profile/', views.UserprofileIndex.as_view(), name='user-profile'),
path('profile/<int:pk>', views.TeamProfileIndex.as_view(), name='team-profile'),

Это просмотры

class TeamProfileIndex(TemplateView):

template_name = 'accounts/profile/team_profile.html'

def get_context_data(self, **kwargs):
    context = dict()
    self.pk = self.kwargs.get("pk")
    try:
        user_profile = Profile.objects.get(user=self.pk)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404
    teams = User.objects.all()
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context


class UserprofileIndex(TemplateView):

template_name = 'accounts/profile/index.html'

def get_context_data(self, **kwargs):
    context = dict()
    try:
        user_profile = Profile.objects.get(user=self.request.user)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404

    teams = User.objects.all
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context

В обоих представлениях изменяется только один запрос, то есть user_profile.

Есть ли способ передать это в одном представлении на две разные html страницы?

Я пробовал следующий метод

class UserprofileIndex (TemplateView): # template_name = 'accounts / profile / index. html'

def initialize(self, *args, **kwargs):
    self.pk = None
    self.pk = kwargs.get('pk')

def get_template_names(self, *args, **kwargs):
    if self.pk:
        return 'accounts/profile/team_profile.html'
    else:
        return 'accounts/profile/index.html'

def get_context_data(self, **kwargs):
    context = dict()
    try:
        if self.pk:
            user_profile = UserProfile.objects.get(user=self.pk)
        else:
            user_profile = Profile.objects.get(user=self.request.user)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404

    teams = User.objects.all()
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context

Но это не работает

1 Ответ

1 голос
/ 27 февраля 2020

Это будет работать. Но я бы посоветовал использовать DetailView

class UserProfile(TemplateView):
    """
    User profile view
    """
    user_profile = None
    template_name = 'accounts/profile/index.html'
    team_profile_template_name = 'accounts/profile/team_profile.html'

    def get_user_profile(self):
        """
        Get user
        """
        if not self.user_profile:
            user_profile_pk = self.kwargs.get('pk')
            model, filter_kwargs = (UserProfile, dict(user=user_profile_pk)) \
                if user_profile_pk else (Profile, dict(user=self.request.user))
            self.user_profile = get_object_or_404(model, **filter_kwargs)
        return self.user_profile

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(dict(user_profile=self.get_user_profile(),
                            teams=User.objects.all()))
        return context

    def get_template_names(self):
        if self.kwargs.get('pk'):
            return [self.team_profile_template_name]
        return super().get_template_names()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...