On Wed, Nov 21, 2012 at 3:45 PM, David
<[email protected]> wrote:
> 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']

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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to