Answer the question
In order to leave comments, you need to log in
How to display only link to your Django profile?
index.html
<a href="{%url 'home'%}">Главная</a>
{% if not request.user.is_authenticated %}
<a href="{%url 'register'%}">Регистрация</a>
<a href="{%url 'login'%}">Авторизоваться</a>
<a href="{%url 'post_list'%}">Новости</a>
{% else %}
<a href="{%url 'logout'%}">Выход</a>
<a href="{%url 'post_list'%}">Новости</a>
<br>
{% for post in my_profile %}
<a href="{%url 'profile' slug=post.slug%}">Профиль {{post.user}}</a>
{% endfor %}
{% endif %}
<p>Login: {{user.username}}</p>
<p>Location: {{user.userprofile.location}}</p>
<p>Age: {{user.userprofile.age}}</p>
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length=30, blank=True)
age = models.PositiveIntegerField(blank=True)
slug = models.SlugField()
def __str__(self):
return self.user.username
def save(self, *args, **kwargs): # new
if not self.slug:
self.slug = slugify(self.user.username)
return super().save(*args, **kwargs)
def index(request):
my_profile = UserProfile.objects.all()
return render(request, 'register/index.html', {'my_profile':my_profile})
from django.contrib.auth.decorators import login_required
@login_required
def profile(request, slug):
post = UserProfile.objects.get(slug=slug)
return render(request, 'register/profile.html',{'post':post})
urlpatterns = [
path('', views.index, name='home'),
path('register', views.register, name='register'),
path('login', LoginView.as_view(), name='login'),
path('logout', views.logout_user, name='logout'),
path('profile/<slug:slug>/', views.profile, name='profile'),
]
Answer the question
In order to leave comments, you need to log in
<a href="{% url 'profile' slug=user.userprofile.slug %}">Профиль {{ user.username }}</a>
Some confusion about variables.
You seem to be iterating over people's profiles, and the variable is called . Why? And why is the variable called ( my profile) if it contains all the users on the site.
I haven't used django for a long time, but, in theory, such a template should work
for post in my_profile
{% if not request.user.is_authenticated %}
<a href="{%url 'register'%}">Регистрация</a>
<a href="{%url 'login'%}">Авторизоваться</a>
<a href="{%url 'post_list'%}">Новости</a>
{% else %}
<a href="{%url 'logout'%}">Выход</a>
<a href="{%url 'post_list'%}">Новости</a>
<br>
<a href="{%url 'profile' request.user.slug %}">Профиль {{request.user}}</a>
{% endif %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question