Reputation: 35
How can i get the user profile based on his username not id , i tried with only slug_filed it shows me that there is no username choice , and i made this get object method but it didn't work
views.py
class ProfileDetail(DetailView):
model = Profile
template_name = 'profile.html'
slug_field = "username"
def get_object(self):
username = self.kwargs.get('username')
return get_object_or_404(User, username=User.username)
models.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
picture = models.ImageField(upload_to='profile_pics')
def __str__(self):
return str(self.user)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from users.views import register, UpdateUserView, ProfileDetail
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
path('register', register, name="register"),
path('accounts/', include('allauth.urls')),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('settings', UpdateUserView.as_view(), name='settings'),
path('profile/<slug>', ProfileDetail.as_view(), name='profile'),]
Upvotes: 1
Views: 87
Reputation: 7330
Your slug field should be like this.
class ProfileDetail(DetailView):
model = Profile
template_name = 'profile.html'
slug_field = "user__username"
And you don't need to override the get_object
method also.
Upvotes: 1