Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use <username> in detailview for django 2.0

Tags:

python

django

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=40, blank=True)
bio = models.TextField(max_length=500, null=True, blank=True)

def get_absolute_url(self):
    return reverse('userprofile:to_profile', args=[str(self.user.username)])

So I have made this model to save it as whatever.com/userprofile:to_profile/thisisusername

And on url, I have

    path('accounts/profile/<username>/', ProfileDetailView.as_view(), name="to_profile"),

For the view, I have

class ProfileDetailView(DetailView):
model = Profile
template_name = "account/profile.html"

I do know that default DetailView takes pk and slug but whenever I try to pass the username with

pk_url_kwarg = "username"

I get an error

invalid literal for int() with base 10

Is there anyway we can use username for generic detailview? or is pk the only way to go?

like image 883
Julius Kim Avatar asked Jan 28 '23 09:01

Julius Kim


2 Answers

Two things you will need to do:

First change your URL's to:

path('accounts/profile/<str:slug>/', ProfileDetailView.as_view(), name="to_profile"),

Second define the method to get the SlugField

class ProfileDetailView(DetailView):
    model = Profile
    template_name = "account/profile.html"

    def get_slug_field(self):
    """Get the name of a slug field to be used to look up by slug."""
        return 'user__username'
like image 165
Gregory Avatar answered Jan 31 '23 08:01

Gregory


You can’t use pk_url_kwarg because username is not the primary key of the Profile model that you are displaying in the view.

Override get_object instead.

from django.shortcuts import get_object_or_404

def get_object(self):
    return get_object_or_404(Profile, user__username=self.kwargs['username'])
like image 22
Alasdair Avatar answered Jan 31 '23 07:01

Alasdair