3

I want to use class based views to build a profile page. Are there any inbuilt views to achieve this. For eg: I have used auth_views for login and register. Django auth.views doesnt contain a profile view. So I decided to create my own using django inbuilts for create update and delete tasks in the profile. Which class based view should I use to achieve this ?

Sahal Sajjad
  • 235
  • 1
  • 5
  • 18

3 Answers3

4

Profile page is nothing more than DetailView - only difference is that object is an actual user profile. If you want to display current user detail page, just override get_object method and return user from request.session (or it's profile if this is different thing in your project).

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77
  • if a user is not authenticated, how to redirect him to login page automatically – Sahal Sajjad Aug 12 '15 at 15:05
  • @SahalSajjad If you protect a view as [@login_required](https://docs.djangoproject.com/en/1.8/topics/auth/default/#the-login-required-decorator) it will redirect to login ans after login to the desired page. In Class-Based Views, you can protect the [dispatch()](https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#django.views.generic.base.View.dispatch) method. – Gocht Aug 12 '15 at 15:12
0

Read https://docs.djangoproject.com/en/1.8/topics/class-based-views/generic-display/#built-in-class-based-generic-views and https://docs.djangoproject.com/en/1.8/ref/class-based-views/generic-editing/#generic-editing-views for generic views details. But for best understading of class based views read source code files in django.views.generic package.

Rajesh Kaushik
  • 1,471
  • 1
  • 11
  • 16
0

From my own little experiment while trying to learn Django (just started)

Code snippet from base.html:

        {% if user.is_authenticated %}
            <a href="{% url 'logout' %}">{{user.username}} Logout   -- </a>
            <a href="{% url 'users:user_detail' user.pk %}">{{user.username}} Profile</a>
        {% else %}
            <a href=="{% url 'login' %}">Login</a>
        {% endif %}

From my views.py

class UserDetailView(DetailView):
    model = User   # this is imported from django.contrib.auth.models
    context_object_name = 'user_object'
    template_name = 'users / user_detail.html'

From my user_detail.html page: (for above code snippet : The user variable is injected by the django.contrib.auth.context_processors.auth context processor)

{% if user == user_object %}
    <h4>user and object are the same. Welcome {{ user_object }}</h4>
{% endif %}
Ai_Nebula
  • 39
  • 9