I'm trying to use context processor to show profile page and when I use it the website shows
Profile has no user
Context processor:
from .models import Profile
def get_profile (request):
profile = Profile()
return{'information':profile}
models.py
class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=_("user"), on_delete=models.CASCADE)
slug = models.SlugField(blank=True, null=True)
image = models.ImageField(_("image"), upload_to='profile_img', blank=True, null=True)
country = CountryField()
address = models.CharField(max_length=100)
join_date = models.DateTimeField(_("join date"),default = datetime.datetime.now)
Also I made primary url for profile so when I want to go to profile page I write on url
accounts/profile/mohammad
account is the name of apps, profile is the name of page, mohammad is user name
Hints: I want to use profile.html on dropdown menu
CodePudding user response:
You can access the Profile
for the given user with:
def get_profile (request):
profile = None
if request.user.is_authenticated:
profile = Profile.objects.filter(user=request.user).first()
return {'information': profile }
or as @xyres says:
def get_profile (request):
profile = None
if request.user.is_authenticated:
profile = getattr(user, 'profile', None)
return {'information': profile }
For a user that is not authenticated, or has no Profile
, information
will be None
, otherwise it is a Profile
object with as .user
the logged in user.
If you want to access of the user specified by a slug for example, you use the view, so you can define a path:
path('accounts/profile/<slug:username>/', some_view)
and then we can use:
from django.shortcuts import get_object_or_404
def some_view(request, username):
profile = get_objec_or_404(Profile, slug=username)
# …
return render(request, 'some-template.html', {'information': profile})