Home > Net >  username=self.kwargs.get('username') returning Not Found: /
username=self.kwargs.get('username') returning Not Found: /

Time:10-30

Hi I am trying to set the show the items the is only related to a specific user who is currently logged in.

I have made sure that the user has items under his username. I want to filter the items to be viewed only to the related user. Currently I am getting an error of Not Found: / I am not sure why?

Here is the models.py:

class Item(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)

Here is the urls.py:

urlpatterns = [
    #path('', home.as_view(), name='home'), <-- Returned not found
    path('user/<str:username>/', home.as_view(), name='home'), <-- Retuned Not found as well

I have tried to have a queryset with the filter to the logged in user but returned back the same error.

Here is my views that I have tried

class home(LoginRequiredMixin, ListView):
    model = Item
    template_name = 'app_name/base.html'
    context_object_name = 'items'
    # queryset = Item.objects.filter(user=User)


    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        print(user)

    #     return Item.objects.filter(user=user)

In the home.html I added: {% block head_title %} {{ view.kwargs.username }} | {% endblock %}

My question:

How can I show the list of items that is only related to the logged in user? what am I doing wrong in here?

CodePudding user response:

Are you sure the not found error is raised from inside your view? Maybe you somehow misplaced the URLs and the request can't find the URL. Are you sure that your request reaches the view? You can verify this using a simple print. If not, make sure you've included your urls in the root urls file.

CodePudding user response:

Since self.kwargs is a key value pair, you need to access the val by

self.kwargs[f'username']  #f string if it is a variable which it should be.
Not
self.kwargs.get('username')
  • Related