Beispiel #1
0
def profile_list(request,
                 public_profile_field=None,
                 template_name='profiles/profile_list.html',
                 **kwargs):
    """
    A list of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``public_profile_field``
        The name of a ``BooleanField`` on the profile model; if the
        value of that field on a user's profile is ``False``, that
        profile will be excluded from the list. Use this feature to
        allow users to mark their profiles as not being publicly
        viewable.
        
        If this argument is not specified, it will be assumed that all
        users' profiles are publicly viewable.
    
    ``template_name``
        The name of the template to use for displaying the profiles. If
        not specified, this will default to
        :template:`profiles/profile_list.html`.

    Additionally, all arguments accepted by the
    :view:`django.views.generic.list_detail.object_list` generic view
    will be accepted here, and applied in the same fashion, with one
    exception: ``queryset`` will always be the ``QuerySet`` of the
    model specified by the ``AUTH_PROFILE_MODULE`` setting, optionally
    filtered to remove non-publicly-viewable proiles.
    
    **Context:**
    
    Same as the :view:`django.views.generic.list_detail.object_list`
    generic view.
    
    **Template:**
    
    ``template_name`` keyword argument or
    :template:`profiles/profile_list.html`.
    
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    if public_profile_field is not None:
        queryset = queryset.filter(**{public_profile_field: True})
#    kwargs['queryset'] = queryset
#    return object_list(request, template_name=template_name, **kwargs)
    context = RequestContext(request)
    return render_to_response(template_name, {
        'object_list': queryset,
        'request': request,
    },
                              context_instance=context)
Beispiel #2
0
def profile_list(request, public_profile_field=None,
                 template_name='profiles/profile_list.html',
                 extra_filter=None, **kwargs):
    """
    A list of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``public_profile_field``
        The name of a ``BooleanField`` on the profile model; if the
        value of that field on a user's profile is ``False``, that
        profile will be excluded from the list. Use this feature to
        allow users to mark their profiles as not being publicly
        viewable.
        
        If this argument is not specified, it will be assumed that all
        users' profiles are publicly viewable.
    
    ``template_name``
        The name of the template to use for displaying the profiles. If
        not specified, this will default to
        :template:`profiles/profile_list.html`.

    ``extra_filter``
        Optional callable which will be called with a ``QuerySet`` (after
        ``public_profile_field`` is applied) and its result will be used for
        rendering the template.

    Additionally, all arguments accepted by the
    :view:`django.views.generic.list_detail.object_list` generic view
    will be accepted here, and applied in the same fashion, with one
    exception: ``queryset`` will always be the ``QuerySet`` of the
    model specified by the ``AUTH_PROFILE_MODULE`` setting, optionally
    filtered to remove non-publicly-viewable proiles.
    
    **Context:**
    
    Same as the :view:`django.views.generic.list_detail.object_list`
    generic view.
    
    **Template:**
    
    ``template_name`` keyword argument or
    :template:`profiles/profile_list.html`.
    
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    if public_profile_field is not None:
        queryset = queryset.filter(**{ public_profile_field: True })
    if callable(extra_filter):
        queryset = extra_filter(queryset)
    kwargs['queryset'] = queryset
    return object_list(request, template_name=template_name, **kwargs)
Beispiel #3
0
def profile_list(request, order_by=None, public_profile_field=None,
                 template_name='profiles/profile_list.html', **kwargs):
    """
    A list of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``public_profile_field``
        The name of a ``BooleanField`` on the profile model; if the
        value of that field on a user's profile is ``False``, that
        profile will be excluded from the list. Use this feature to
        allow users to mark their profiles as not being publicly
        viewable.
        
        If this argument is not specified, it will be assumed that all
        users' profiles are publicly viewable.
    
    ``template_name``
        The name of the template to use for displaying the profiles. If
        not specified, this will default to
        :template:`profiles/profile_list.html`.

    Additionally, all arguments accepted by the
    :view:`django.views.generic.list_detail.object_list` generic view
    will be accepted here, and applied in the same fashion, with one
    exception: ``queryset`` will always be the ``QuerySet`` of the
    model specified by the ``AUTH_PROFILE_MODULE`` setting, optionally
    filtered to remove non-publicly-viewable proiles.
    
    **Context:**
    
    Same as the :view:`django.views.generic.list_detail.object_list`
    generic view.
    
    **Template:**
    
    ``template_name`` keyword argument or
    :template:`profiles/profile_list.html`.
    
    """
    kwargs['extra_context']['order_by'] = order_by
    profile_model = utils.get_profile_model()
    if order_by == "snippets":
        queryset = profile_model.objects.annotate(snippet_count=Count('user__snippet')).order_by("-snippet_count", "display_name")
    else:    
        order_by = {"displayname":"display_name",
                    None:"display_name",
                    "username":"******"}[order_by]
    
        queryset = profile_model._default_manager.order_by(order_by)
    if public_profile_field is not None:
        queryset = queryset.filter(**{ public_profile_field: True })
    kwargs['queryset'] = queryset
    return object_list(request, template_name=template_name, **kwargs)
Beispiel #4
0
def profile_list(request, public_profile_field=None,
                 template_name='profiles/profile_list.html', **kwargs):
    """
    List of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    If a field on the profile model determines whether the profile can
    be publicly viewed, pass the name of that field as the keyword
    argument ``public_profile_field``; the ``QuerySet`` of profiles
    will be filtered to include only those on which that field is
    ``True`` (as a result, this field must be a ``BooleanField``).
    
    This view is a wrapper around the
    :view:`django.views.generic.list_detail.object_list` generic view,
    so any arguments which are legal for that view will be accepted,
    with the exception of ``queryset``, which will always be set to
    the default ``QuerySet`` of the profile model, optionally filtered
    as described above.
    
    Template:
    
        ``template_name`` keyword argument or
        :template:`profiles/profile_list.html`.
    
    Context:
    
        Same as the :view:`django.views.generic.list_detail.object_list`
        generic view.
    
    """
    profile_model = utils.get_profile_model()
    if 'queryset' in kwargs:
        del kwargs['queryset']
    queryset = profile_model._default_manager.all()
    if public_profile_field is not None:
        queryset = queryset.filter(**{ public_profile_field: True })
    return object_list(request,
                       queryset=queryset,
                       template_name=template_name,
                       **kwargs)
Beispiel #5
0
def profile_list(request,
                 public_profile_field=None,
                 template_name='profiles/profile_list.html',
                 **kwargs):
    """
    A list of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    If a field on the profile model determines whether the profile can
    be publicly viewed, pass the name of that field as the keyword
    argument ``public_profile_field``; the ``QuerySet`` of profiles
    will be filtered to include only those on which that field is
    ``True`` (as a result, this field must be a ``BooleanField``).
    
    This view is a wrapper around the
    :view:`django.views.generic.list_detail.object_list` generic view,
    so any arguments which are legal for that view will be accepted,
    with the exception of ``queryset``, which will always be set to
    the default ``QuerySet`` of the profile model, optionally filtered
    as described above.
    
    Context:
    
    Same as the :view:`django.views.generic.list_detail.object_list`
    generic view.
    
    Template:
    
    ``template_name`` keyword argument or
    :template:`profiles/profile_list.html`.
    
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    if public_profile_field is not None:
        queryset = queryset.filter(**{public_profile_field: True})
    kwargs['queryset'] = queryset
    return object_list(request, template_name=template_name, **kwargs)
Beispiel #6
0
 def get_model(self):
     return utils.get_profile_model()
Beispiel #7
0
 def get_model(self):
     return utils.get_profile_model()
Beispiel #8
0
 def __init__(self, public_profile_field=None, **kwargs):
     self.public_profile_field = public_profile_field
     self.model = utils.get_profile_model()
     super(ProfileList, self).__init__(**kwargs)
Beispiel #9
0
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordResetForm as BasicPasswordResetForm
from django.conf import settings
from django.utils.translation import ugettext as _
from registration.forms import RegistrationFormUniqueEmail
from my_profiles.models import ProfileImage

from profiles import utils
profile_model = utils.get_profile_model()

class ProfileImageForm(forms.ModelForm):

    class Meta:
        model = ProfileImage

class ProfileForm(forms.ModelForm):
    
    class Meta:
        model = profile_model
        exclude = ('user','latitude','longitude','mugshot')

class RegistrationForm(RegistrationFormUniqueEmail):
    """
    Subclass here if we want to add more fields or details to registration
    form. For now just inherit unique email form.
    """
    # max_length attr based on User definition since these are going in
    # user model
    first_name = forms.CharField(max_length=30)  
    last_name = forms.CharField(max_length=30)  
Beispiel #10
0
def custom_list(request, template_name='profiles/profile_list.html', **kwargs):
    """
    A list of user profiles, based on code from django-profiles
    https://bitbucket.org/ubernostrum/django-profiles
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    birds_queryset = profile_model._default_manager.all()
    countries_queryset = profile_model._default_manager.all()
    collaboration_queryset = utils.get_model('profile', 'collaborationchoice')._default_manager.all()
    extra_context = {'seabird': None, 'country':None, 'country_tag':None, 'collaboration_choice':None}
 
    seabird = request.GET.get('s', None)
    if seabird is not None:
        try:
            bird = SeabirdFamily.objects.get(choice__istartswith = seabird)
            queryset = queryset.filter(seabirds = bird)
            countries_queryset = countries_queryset.filter(seabirds = bird)
            extra_context['seabird'] =  bird
        except (SeabirdFamily.DoesNotExist, MultipleObjectsReturned):
            pass
    
    country = request.GET.get('c', None)
    if country is not None and country in COUNTRIES.keys():
        queryset = queryset.filter(country=country)
        birds_queryset = birds_queryset.filter(country=country)
        extra_context['country'] = unicode(COUNTRIES[country])
        extra_context['country_tag'] =  country

    collab_choice = request.GET.get('r', None)
    if collab_choice:
        choice = CollaborationChoice.objects.get(id=collab_choice)
        queryset = queryset.filter(collaboration_choices=choice)
        extra_context['collaboration_choice'] = int(collab_choice)

    kwargs['queryset'] = queryset.order_by('user__last_name')
    extra_context['profile_birds'] = SeabirdFamily.objects.filter(profiles__in=UserProfile.objects.all()).distinct()
    countries = list(set([(u.country.name, u.country) for u in UserProfile.objects.all()]))
    extra_context['profile_countries'] =  [c[1] for c in sorted(countries)]
    extra_context['profile_collaboration_choices'] = CollaborationChoice.objects.all()

    def _record_details(r, filter_queryset, record_type, activetest, country=None, seabird=None, collab_choice=None):
        query_string_params = {}
        r.tag = "a"
        href = "/petrel/"
        classes = ["badge"]
        if record_type == 'seabirds':
            name_attr = 'choice'
            r.records = len(filter_queryset.filter(**{record_type: r}))
        elif record_type == 'country':
            name_attr = 'name'
            r.records = len(filter_queryset.filter(**{record_type: r}))
        elif record_type == 'collaboration_choice':
            name_attr = 'id'
            r.records = len(filter_queryset.filter(userprofile__in=queryset))
        else:
            raise ValueError

        name  = getattr(r, name_attr)
        active = activetest(name)
        if active:
            classes.append("activebadge")
        elif r.records > 0:
            classes.append("linkbadge")
        else:
           classes.extend(["smallbadge", "inactivebadge"])
           r.tag = "span"

        if active:
	    if country and not record_type == 'country':
                query_string_params['c'] = country
            if seabird and not record_type == 'seabirds':
	        query_string_params['s'] = seabird[:3].lower()
            if collab_choice and not record_type == 'collaboration_choice':
                query_string_params['r'] = collab_choice
        elif record_type == 'country':
            query_string_params['c'] = force_unicode(name)
            if seabird:
	        query_string_params['s'] = seabird[:3].lower()
            if collab_choice:
                query_string_params['r'] = collab_choice
        elif record_type == 'seabirds':
	    query_string_params['s'] = name[:3].lower()
            if country:
                query_string_params['c'] = force_unicode(country)
            if collab_choice:
                query_string_params['r'] = collab_choice
        elif record_type == 'collaboration_choice':
            query_string_params['r'] = name
            if country:
                query_string_params['c'] = force_unicode(country)
            if seabird:
	        query_string_params['s'] = seabird[:3].lower()

        try:
            c = query_string_params['c']
            if c and len(c) != 2:
                query_string_params['c'] = COUNTRIES_REVERSED[c]
        except KeyError:
            pass
        query_string = urlencode(dict((k,unicode(v).encode('utf-8', 'xmlcharreplace')) for k,v in query_string_params.iteritems()))
        if query_string:
            href = href + '?' + query_string
            href = 'href="{0}"'.format(href)
        elif r.records > 0:
            href = 'href="/petrel/"'
        else:
            href = ''
        r.href = href
        r.classes = " ".join(classes)
        return r

    def birds_activetest(bird_name):
        try:
            return bird_name == extra_context['seabird'].choice
        except AttributeError:
            return False

    def country_activetest(country_name):
        try:
            return country_name == force_unicode(extra_context['country'].encode('utf-7', 'xmlcharreplace'))
        except AttributeError:
            return False

    def collab_choice_activetest(collab_choice_id):
        try:
            c1 = CollaborationChoice.objects.get(pk=collab_choice_id).pk
            c2 = extra_context['collaboration_choice']
            return c1 == c2
        except CollaborationChoice.DoesNotExist:
            return False

    for pb in extra_context['profile_birds']:
        pb = _record_details(pb, birds_queryset, 'seabirds', birds_activetest, country, seabird, collab_choice)
    for pc in extra_context['profile_countries']:
        pc = _record_details(pc, countries_queryset, 'country', country_activetest, country, seabird, collab_choice)
    for pr in extra_context['profile_collaboration_choices']:
        pr = _record_details(pr, collaboration_queryset, 'collaboration_choice', collab_choice_activetest, country, seabird, collab_choice)
    return object_list(request, template_name=template_name, extra_context=extra_context, **kwargs)
Beispiel #11
0
def custom_list(request, template_name='profiles/profile_list.html', **kwargs):
    """
    A list of user profiles, based on code from django-profiles
    https://bitbucket.org/ubernostrum/django-profiles
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    birds_queryset = profile_model._default_manager.all()
    countries_queryset = profile_model._default_manager.all()
    collaboration_queryset = utils.get_model(
        'profile', 'collaborationchoice')._default_manager.all()
    extra_context = {
        'seabird': None,
        'country': None,
        'country_tag': None,
        'collaboration_choice': None
    }

    seabird = request.GET.get('s', None)
    if seabird is not None:
        try:
            bird = SeabirdFamily.objects.get(choice__istartswith=seabird)
            queryset = queryset.filter(seabirds=bird)
            countries_queryset = countries_queryset.filter(seabirds=bird)
            extra_context['seabird'] = bird
        except (SeabirdFamily.DoesNotExist, MultipleObjectsReturned):
            pass

    country = request.GET.get('c', None)
    if country is not None and country in COUNTRIES.keys():
        queryset = queryset.filter(country=country)
        birds_queryset = birds_queryset.filter(country=country)
        extra_context['country'] = unicode(COUNTRIES[country])
        extra_context['country_tag'] = country

    collab_choice = request.GET.get('r', None)
    if collab_choice:
        choice = CollaborationChoice.objects.get(id=collab_choice)
        queryset = queryset.filter(collaboration_choices=choice)
        extra_context['collaboration_choice'] = int(collab_choice)

    kwargs['queryset'] = queryset.order_by('user__last_name')
    extra_context['profile_birds'] = SeabirdFamily.objects.filter(
        profiles__in=UserProfile.objects.all()).distinct()
    countries = list(
        set([(u.country.name, u.country) for u in UserProfile.objects.all()]))
    extra_context['profile_countries'] = [c[1] for c in sorted(countries)]
    extra_context[
        'profile_collaboration_choices'] = CollaborationChoice.objects.all()

    def _record_details(r,
                        filter_queryset,
                        record_type,
                        activetest,
                        country=None,
                        seabird=None,
                        collab_choice=None):
        query_string_params = {}
        r.tag = "a"
        href = "/petrel/"
        classes = ["badge"]
        if record_type == 'seabirds':
            name_attr = 'choice'
            r.records = len(filter_queryset.filter(**{record_type: r}))
        elif record_type == 'country':
            name_attr = 'name'
            r.records = len(filter_queryset.filter(**{record_type: r}))
        elif record_type == 'collaboration_choice':
            name_attr = 'id'
            r.records = len(filter_queryset.filter(userprofile__in=queryset))
        else:
            raise ValueError

        name = getattr(r, name_attr)
        active = activetest(name)
        if active:
            classes.append("activebadge")
        elif r.records > 0:
            classes.append("linkbadge")
        else:
            classes.extend(["smallbadge", "inactivebadge"])
            r.tag = "span"

        if active:
            if country and not record_type == 'country':
                query_string_params['c'] = country
            if seabird and not record_type == 'seabirds':
                query_string_params['s'] = seabird[:3].lower()
            if collab_choice and not record_type == 'collaboration_choice':
                query_string_params['r'] = collab_choice
        elif record_type == 'country':
            query_string_params['c'] = force_unicode(name)
            if seabird:
                query_string_params['s'] = seabird[:3].lower()
            if collab_choice:
                query_string_params['r'] = collab_choice
        elif record_type == 'seabirds':
            query_string_params['s'] = name[:3].lower()
            if country:
                query_string_params['c'] = force_unicode(country)
            if collab_choice:
                query_string_params['r'] = collab_choice
        elif record_type == 'collaboration_choice':
            query_string_params['r'] = name
            if country:
                query_string_params['c'] = force_unicode(country)
            if seabird:
                query_string_params['s'] = seabird[:3].lower()

        try:
            c = query_string_params['c']
            if c and len(c) != 2:
                query_string_params['c'] = COUNTRIES_REVERSED[c]
        except KeyError:
            pass
        query_string = urlencode(
            dict((k, unicode(v).encode('utf-8', 'xmlcharreplace'))
                 for k, v in query_string_params.iteritems()))
        if query_string:
            href = href + '?' + query_string
            href = 'href="{0}"'.format(href)
        elif r.records > 0:
            href = 'href="/petrel/"'
        else:
            href = ''
        r.href = href
        r.classes = " ".join(classes)
        return r

    def birds_activetest(bird_name):
        try:
            return bird_name == extra_context['seabird'].choice
        except AttributeError:
            return False

    def country_activetest(country_name):
        try:
            return country_name == force_unicode(
                extra_context['country'].encode('utf-7', 'xmlcharreplace'))
        except AttributeError:
            return False

    def collab_choice_activetest(collab_choice_id):
        try:
            c1 = CollaborationChoice.objects.get(pk=collab_choice_id).pk
            c2 = extra_context['collaboration_choice']
            return c1 == c2
        except CollaborationChoice.DoesNotExist:
            return False

    for pb in extra_context['profile_birds']:
        pb = _record_details(pb, birds_queryset, 'seabirds', birds_activetest,
                             country, seabird, collab_choice)
    for pc in extra_context['profile_countries']:
        pc = _record_details(pc, countries_queryset, 'country',
                             country_activetest, country, seabird,
                             collab_choice)
    for pr in extra_context['profile_collaboration_choices']:
        pr = _record_details(pr, collaboration_queryset,
                             'collaboration_choice', collab_choice_activetest,
                             country, seabird, collab_choice)
    return object_list(request,
                       template_name=template_name,
                       extra_context=extra_context,
                       **kwargs)
Beispiel #12
0
        qs = []
        # get related methods like picture_set, article_set, etc.
        # checking that are BaseContent types
        for related_name in dir(content_object):
            if related_name.endswith('_set'):
                rel_set = getattr(content_object, related_name)
                if rel_set.model in frontend.site.base_content_types:
                    sqs = rel_set.all()
                    # We only want the items that doesn't have author set
                    if hasattr(rel_set.model, "author"):
                        sqs = sqs.filter(author=None)
                    qs.extend(sqs)
        return qs

    def get_response(self, request, req_context, options, content_object):
        if options['show_authored_content']:
            authored_contents_page = self.get_page(request, req_context,
                                                   options,
                                                   content_object.user)
        else:
            authored_contents_page = None

        return render_to_string(
            self.template, {
                'inline_view_name': options["inline_view_name"],
                'page': authored_contents_page
            }, req_context)


frontend.site.register_view(get_profile_model(), UserDetail)
Beispiel #13
0
def profile_list(request, public_profile_field=None,
                 template_name='profiles/profile_list.html', **kwargs):
    """
    A list of user profiles.
    
    If no profile model has been specified in the
    ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.

    **Optional arguments:**

    ``public_profile_field``
        The name of a ``BooleanField`` on the profile model; if the
        value of that field on a user's profile is ``False``, that
        profile will be excluded from the list. Use this feature to
        allow users to mark their profiles as not being publicly
        viewable.
        
        If this argument is not specified, it will be assumed that all
        users' profiles are publicly viewable.
    
    ``template_name``
        The name of the template to use for displaying the profiles. If
        not specified, this will default to
        :template:`profiles/profile_list.html`.

    Additionally, all arguments accepted by the
    :view:`django.views.generic.list_detail.object_list` generic view
    will be accepted here, and applied in the same fashion, with one
    exception: ``queryset`` will always be the ``QuerySet`` of the
    model specified by the ``AUTH_PROFILE_MODULE`` setting, optionally
    filtered to remove non-publicly-viewable proiles.
    
    **Context:**
    
    Same as the :view:`django.views.generic.list_detail.object_list`
    generic view.
    
    **Template:**
    
    ``template_name`` keyword argument or
    :template:`profiles/profile_list.html`.
    
    """
    profile_model = utils.get_profile_model()
    queryset = profile_model._default_manager.all()
    if public_profile_field is not None:
        queryset = queryset.filter(**{ public_profile_field: True })
    if request.GET.get('order_field'):
        order_field = request.GET.get('order_field')
        order_dir = request.GET.get('order_dir', 'asc')
        
        if order_field == 'username':
            if order_dir == 'asc':
                queryset = queryset.order_by('user__username')
            else:
                queryset = queryset.order_by('-user__username')
        if order_field == 'name':
            if order_dir == 'asc':
                queryset = queryset.order_by('nome')
            else:
                queryset = queryset.order_by('-nome')
        if order_field == 'year':
            if order_dir == 'asc':
                queryset = queryset.order_by('year')
            else:
                queryset = queryset.order_by('-year')
        if order_field == 'resources':
            if order_dir == 'asc':
                queryset = queryset.annotate(resources=Count('user__resource_collaborator')).order_by('resources')
            else:
                queryset = queryset.annotate(resources=Count('user__resource_collaborator')).order_by('-resources')
    kwargs['queryset'] = queryset
    return object_list(request, template_name=template_name, **kwargs)