Профили Django - добавление дополнительных объектов в детальный вид - PullRequest
1 голос
/ 19 июля 2011

После расширения превосходных django-профилей проекта django (найденных на https://bitbucket.org/ubernostrum/django-profiles/wiki/Home)) я наткнулся на что-то, что я пытался решить несколько дней.

Идея довольно проста. У меня есть пользователи, у которых есть профили пользователей (объект UserProfile, связанный с User). Теперь я добавил в свой проект новый объект, Employment, который также связан с объектом User.

class Employment(models.Model):
    """
    A class to describe the relationship of employment, past or present, between an employee and an organization.

    """

    def __unicode__(self):
        return self.function

    def get_absolute_url(self):
        return "/recycling/employment/%i/" % self.id

    user = models.ForeignKey(User)
    organization = models.ForeignKey(Organization)
    date_start = models.DateField('Start date of employment', help_text="Please use the following format: YYYY-MM-DD.", null=True, blank=True)
    date_end = models.DateField('End date of employment', help_text="Please use the following format: YYYY-MM-DD.", null=True, blank=True)
    function = models.CharField(max_length=100)
    present_job = models.BooleanField()


class UserProfile(models.Model):
    """
    A class representing a the profile of a user.  Needs to be generic enough to involve both employees as employers.

    """

    def _get_absolute_url(self):
        return ('profiles_profile_detail', (), { 'username': self.user.username })

    # Link person to user
    user = models.ForeignKey(User, unique=True, null=True)

    registration_date = models.DateField(auto_now_add=True)

Теперь я хотел бы иметь страницу (подробный вид), где я могу показать UserProfile, а также все вакансии для конкретного пользователя. Я полагал, что добавление extra_context - это путь, и это работает, например .:

('^profiles/(?P<username>\w+)/$', 'profiles.views.profile_detail', {'extra_context': {'employment_list': Employment.objects.all(),}}), 

Однако проблема, с которой я сталкиваюсь, заключается в том, что я хотел бы иметь пользовательские объекты (таким образом, фильтрацию), а не только все (). Одна ловушка заключается в том, что проект django-Profiles по-прежнему работает с функциями как представлениями, а не классами, поэтому создание подклассов не вариант. Еще один момент, требующий внимания, заключается в том, что представление не должно кэшироваться, поэтому, если пользователь добавляет другой объект занятости и перенаправляется на страницу сведений, это изменение должно быть отражено. Было бы неплохо найти решение для этого, не адаптируя сам код django-profile ...

Спасибо за вашу помощь!


Нашел способ сделать это, оказалось довольно просто. Я создал новый вид, который генерирует список с фильтром. Передайте этот список в extra_context представлению, определенному в приложении профилей, и выполните ...

def detail_userprofile_view(request, username):
    """
    Returns a detail view including both the User Profile and the Employments linked to the user.
    """

    employment_list = Employment.objects.filter(user__username=username)
    context_dict = { 'employment_list': employment_list,}

    return profile_detail(request, username, extra_context=context_dict)

1 Ответ

0 голосов
/ 19 июля 2011

Вы всегда можете написать новый взгляд.Что-то простое, например:

urls

url(r'^profiles/(?P<username>\w+)/$', profiles.views.profile_detail, name='profile_detail'),

views

def profile_detail(request, username):
    context_dict = {}
    user = get_object_or_404(User, username=username)
    profile = get_object_or_404(Profile, user=user)
    employment = get_object_or_404(Employment, user=user)

    context_dict = { 'user': user,
                     'profile':profile,
                     'employment':employment,
    }
    return render_to_response('details.html', context_dict, RequestContext(request))

Теперь в вашем шаблоне вы можете перейти {{ user.first_name }} или {{ profile }} или {{ employment.organization }} и т. Д...

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