On an earlier question I asked: How to have two separate querysets under the same class based view. The initial problem was a simple due to a syntax error but after fixing it i got :get() got an unexpected keyword argument 'pk' I believe it to be a problem on how i wrote my views.
EDIT: Clarifying the issue: is how to have two querysets one calling User's pk info and one making a list of users under the same class.
views.py
class ViewProfile(generic.ListView):
model = Post
template_name = 'accounts/profile.html'
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
kwargs = {'user': request.user}
return render(request, 'accounts/profile.html', kwargs)
def get(self, request):
users =User.objects.all()
object_list= Post.objects.filter(owner =self.request.user).order_by('-timestamp')
args ={'object_list':object_list,'users':users}
return render (request, self.template_name, args)
urls.py
# profilepage
url(r'^profile/$', views.ViewProfile.as_view(), name='view_profile'),
# profilepage
url(r'^profile/(?P<pk>\d+)/$', views.ViewProfile.as_view(), name='view_profile_with_pk'),
profile
<div class="col-md-4">
<h1>Friends</h1>
{%for user in users %}
<a href="{% url 'accounts:view_profile_with_pk' pk=user.pk %}">
<h3>{{user.username}}</h3>
</a>
{%endfor%}
</div>
As you see, your
view_profile_with_pkurl pattern takes apkparamter:But then in your
ViewProfileview you have configured yourget()method like:You can clearly notice that
get()takes exactly two parameters, which areselfandrequest. There is nopkanywhere. So Django doesn't know about it.Yet.
You can add
*argsand**kwargsarguments to theget()function, which will take care of your url parameters:And then you can freely get your
pkinside the function:But I don't understand why you have defined the
view_profilefunction, while you can implement it's logic inside theget()function:This will work, until you provide a non-existing
pkto the view. This will result an exception. You can fix that by usingget_object_or_404():Now you should have a fully functional view.
EDIT:
As you've just stated, the view returns the same
Userdata. This is because of:This line is meaningless, because every time the user sends a request to your view, he will get a
usersproperty in thecontext, which just holds all the users in your database.A possible and more meaningful solution will be to attach the current user to this property:
Now the view will return the
Posts and their relatedUser.