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?
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'
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With