@Chaoma97

Как выводить только ссылку на свой профиль Django?

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 %}


profile.html
<p>Login: {{user.username}}</p>
<p>Location: {{user.userprofile.location}}</p>
<p>Age: {{user.userprofile.age}}</p>


models.py
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)


views.py
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})


urls.py
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'),
]


61e1a39c1e3d2840415298.png
61e1a3f954108680496207.png

Что только не пробовал(что в моих силах).
Вкратце: Хочу создать ссылку на профиль свой, пытался сделать фильтрацию но безуспешно, ощущение, что прям на поверхности ответ, но не понимаю)
И ещё если не трудно, на ошибки укажите в коде(на плохой код) :). Как лучше не делать, и как лучше делать, пожалуйста)
  • Вопрос задан
  • 399 просмотров
Решения вопроса 1
deepblack
@deepblack Куратор тега Python
<a href="{% url 'profile' slug=user.userprofile.slug %}">Профиль {{ user.username }}</a>


user.userprofile.slug
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
SoreMix
@SoreMix Куратор тега Python
yellow
Какая-то путанница в переменных.

for post in my_profile
Вроде итерируете по профилям людей, а переменная называется post. Почему? Да и почему переменная называется 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 %}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
26 апр. 2024, в 07:47
2000 руб./за проект
26 апр. 2024, в 06:46
1000 руб./в час
26 апр. 2024, в 05:31
1000 руб./за проект