DetailView

115 views
Skip to first unread message

David

unread,
Nov 21, 2012, 10:45:19 AM11/21/12
to django...@googlegroups.com
Hello

I am trying to use a class based generic view (DetailView) to view user profiles.

What I am trying to achieve is: if no user PK is provided in the URL show the logged in user. If there is a user PK in the URL show that user. Thus reducing the need to have 2 views.

My code currently errors out complaining of a missing key error "pk" if I do not specify a PK in the URL. If a PK is supplied in the URL it works fine.

Any help would be appreciated.

Thank you


This is my code so far:

class home(DetailView):
    context_object_name = 'profile'
    template_name = 'view_profile.html'

    def get_context_data(self, **kwargs):
        context = super(home, self).get_context_data(**kwargs)
        u_ct = ContentType.objects.get_for_model(get_user_model()).id
        
        context.update({
            'profile_ct': u_ct,
        })
        return context

    def get_queryset(self):
        UserModel = get_user_model()

        pk = self.kwargs['pk']
        
        if not pk:
            profile = UserModel.objects.filter(pk=self.request.user)
        else:
            profile = UserModel.objects.filter(pk=self.kwargs['pk'])
        return profile

Szabo, Patrick (LNG-VIE)

unread,
Nov 21, 2012, 10:55:37 AM11/21/12
to django...@googlegroups.com

Hi,

 

Code looks fine to me, maybe you could give us the exact error message ?

You could also try request.user.id or something to get the actual pk and not only the user object  but that’s just a guess.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/yXHgVvDdOaEJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

 

. . . . . . . . . . . . . . . . . . . . . . . . . .

Ing. Patrick Szabo

Developer

LexisNexis

A-1030 Wien, Marxergasse 25

 

Patric...@lexisnexis.at

Tel.: +43 1 53452 1573

Fax.: +43 1 534 52 146

. . . . . . . . . . . . . . . . . . . . . . . . . .

 

Message has been deleted

Tom Evans

unread,
Nov 21, 2012, 11:07:01 AM11/21/12
to django...@googlegroups.com
This will always return a KeyError if 'pk' is not a valid key. You should use:

pk = self.kwargs.get('pk', self.request.user.id)

Cheers

Tom

David

unread,
Nov 21, 2012, 11:17:38 AM11/21/12
to django...@googlegroups.com, teva...@googlemail.com
Thank you for you reply Tom.

I am now getting:

"Generic detail view home must be called with either an object pk or a slug."

I have tried using the pk line you pointed to in the get_queryset method. Should I instead be trying to use def get: ?

David

unread,
Nov 21, 2012, 12:24:19 PM11/21/12
to django...@googlegroups.com, teva...@googlemail.com
Think I now have this working with the following:

    def get_queryset(self):
        self.kwargs['pk'] = self.kwargs.get('pk', self.request.user.id)
        UserModel = get_user_model()
        profile = UserModel.objects.filter(pk=self.kwargs['pk'])
        return profile

Thanks for your replies and assistance.

Sergiy Khohlov

unread,
Nov 22, 2012, 3:21:06 AM11/22/12
to django...@googlegroups.com, patric...@lexisnexis.at
I would like to say that this code is really bad :


def get_queryset(self):
UserModel = get_user_model()

pk = self.kwargs['pk']

if not pk:
profile = UserModel.objects.filter(pk=self.request.user)
else:
profile = UserModel.objects.filter(pk=self.kwargs['pk'])
return profile


I've also made it few times.
Lets try to fix :


def get_queryset(self) passes nothing to the function and of course
dic self.kwargs[] is not present :

adding args to this one
def get_queryset(self, kwargs):
""" this is more better """

after this I'm proposing add some debugging steps:
# this string be removed after fixing most bug
print self.kwargs

let start do do with our pk : we dont know if this user id is present
in database then try to do this in polite way via exception :

try:
return UserModel.objects.filter(int (pk=self.kwargs['pk']))
except KeyError:
# if pk is not present the we should create it ? Is not it ? I
have not seen this code in your example


If you need more help ask me.

thanks ,
Serge

+380636150445


2012/11/21 David <david...@adviserbreakthrough.co.uk>:
> Hi Patrick
>
> The error exists on this line:
>
> pk = self.kwargs['pk']
>
> KeyError at /accounts/profile/
> 'pk'
> Request Method: GET
> Request URL: http://127.0.0.1:8000/accounts/profile/
> Django Version: 1.5
> Exception Type: KeyError
> Exception Value:
> 'pk'
> Exception Location: C:\Users\DavidWills.DELTAGEM\Django
> Projects\membersarea\accounts\views.py in get_queryset, line 69
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/sAl9k5yrHOsJ.

David

unread,
Nov 22, 2012, 4:30:02 AM11/22/12
to django...@googlegroups.com
Sergiy

Some of your points cover my old code (which was very much a first draft). This is the updated version:

class home(DetailView):
    context_object_name = 'profile'
    template_name = 'view_profile.html'

    def get_context_data(self, **kwargs):
        context = super(home, self).get_context_data(**kwargs)
        u_ct = ContentType.objects.get_for_model(get_user_model()).id

        context.update({
            'profile_ct': u_ct,
        })
        return context

    def get_queryset(self):
        self.kwargs['pk'] = self.kwargs.get('pk', self.request.user.id)
        UserModel = get_user_model()
        profile = UserModel.objects.filter(pk=self.kwargs['pk'])
        return profile

Every user will have a profile so there "shouldn't" be a reason for the:

profile = UserModel.objects.filter(pk=self.kwargs['pk'])

to fail.

If you can help I'd be grateful but I think the above is better.

Sergiy Khohlov

unread,
Nov 22, 2012, 5:10:49 AM11/22/12
to django...@googlegroups.com
Could you please add next string before
profile = UserModel.objects.filter(pk=self.kwargs['pk'])

print self.kwargs['pk'], type(self.kwargs['pk'])
I would like to know something

2012/11/22 David <david...@adviserbreakthrough.co.uk>:
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/DWgNfzJ51oUJ.

David

unread,
Nov 22, 2012, 5:23:27 AM11/22/12
to django...@googlegroups.com
Hi Sergiy

That line outputs:

1 <type 'int'>

Sergiy Khohlov

unread,
Nov 22, 2012, 5:42:55 AM11/22/12
to django...@googlegroups.com
good news ! pk key is ok , But your database does not contain
record for this user.
you can do this by manually investigating database or by next code:

rom django.core.exceptions import ObjectDoesNotExist
try:
MyModel = UserModel.objects.get(id=1)

except ObjectDoesNotExist:
print("Either the entry or blog doesn't exist.")
2012/11/22 David <david...@adviserbreakthrough.co.uk>:
> Hi Sergiy
>
> That line outputs:
>
> 1 <type 'int'>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/p3yEqcw-2_cJ.
Reply all
Reply to author
Forward
0 new messages