Охватываемые темы: Простой профиль (только данные User), Расширение через модель Profile, Автоматическое создание Profile через сигналы, Шаблон профиля.
Простой профиль (только данные User)
# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView, UpdateView
from django.contrib.auth.models import User
class ProfileView(LoginRequiredMixin, DetailView):
model = User
template_name = 'accounts/profile.html'
def get_object(self):
return self.request.user # всегда текущий пользователь
# urls.py
path('profile/', views.ProfileView.as_view(), name='profile'),
Расширение через модель Profile
# models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatars/', blank=True)
website = models.URLField(blank=True)
def __str__(self):
return f'Профиль {self.user.username}'
Автоматическое создание Profile через сигналы
# signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
Шаблон профиля
{% extends 'base.html' %}
{% block content %}
<div class="profile">
{% if user.profile.avatar %}
<img src="{{ user.profile.avatar.url }}" alt="Аватар">
{% endif %}
<h1>{{ user.get_full_name|default:user.username }}</h1>
<p>{{ user.profile.bio }}</p>
<a href="{% url 'profile-edit' %}">Редактировать профиль</a>
</div>
{% endblock %}
Редактирование профиля
class ProfileUpdateView(LoginRequiredMixin, UpdateView):
model = Profile
fields = ['bio', 'avatar', 'website']
template_name = 'accounts/profile_edit.html'
success_url = reverse_lazy('profile')
def get_object(self):
return self.request.user.profile
💬 Комментарии (0)
Комментариев пока нет
Станьте первым, кто поделится мнением об этой статье!