Saya mencoba membuat UserProfileView dengan nama pengguna pengguna di url. Sebenarnya, ini berfungsi dengan pengaturan sebenarnya. Masalahnya adalah, ekstensi nama pengguna apa pun di url dialihkan ke profil pengguna yang masuk. Dan, tidak ada info yang masuk ke templat ketika saya mencoba membuka profil tanpa masuk. Ini kode saya, bantuan apa pun sangat kami hargai.
model.py
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
email = models.EmailField(max_length=150)
bio = models.TextField(max_length=280, blank=True)
avatar = models.ImageField(default='default.jpg', upload_to='avatars/')
def __str__(self):
return '@{}'.format(self.user.username)
def save(self):
super().save()
img = Image.open(self.avatar.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size, Image.BICUBIC)
img.save(self.avatar.path)
dilihat.py
class UserProfileView(SelectRelatedMixin, TemplateView):
model = Profile
template_name = 'accounts/profile.html'
select_related = ('user',)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
def get_success_url(self):
return reverse('accounts:profile', kwargs={'user': self.object.user})
urls.py
urlpatterns = [
path('<str:username>/', views.UserProfileView.as_view(), name='profile')
]
profile.html (bagaimana saya memanggil data terkait di template)
<h3>{{ user.profile }}</h3>
<p>{{ user.profile.email }}</p>
<p>{{ user.profile.bio }}</p>
<h3>{{ profile }}</h3>
*update untuk penjelasan lebih jelas:
username
pada modelUser
atauProfile
? Mencoba mencari tahu mengapa Anda menggunakan tampilan untuk Profil, bukan hanya untuk Pengguna... - person GProst   schedule 16.10.2020UserView
saja, bukanUserProfileView
yang menggunakan modelUser
, bukanProfile
? Bukankah lebih sederhana? Saya melihat bahwa di templat Anda tetap mengaksesprofile
melaluiuser.profile
... - person GProst   schedule 16.10.2020def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('user.username'))
- person Ediz   schedule 16.10.2020