ฉันกำลังพยายามสร้าง UserProfileView ด้วยชื่อผู้ใช้ของผู้ใช้ใน url ที่จริงแล้วมันใช้งานได้กับการตั้งค่าจริง ปัญหาคือส่วนขยายชื่อผู้ใช้ใดๆ ใน URL เปลี่ยนเส้นทางไปยังโปรไฟล์ของผู้ใช้ที่เข้าสู่ระบบ และไม่มีข้อมูลมาที่เทมเพลตเมื่อฉันพยายามไปที่โปรไฟล์โดยไม่ต้องลงชื่อเข้าใช้ นี่คือรหัสของฉัน ขอขอบคุณสำหรับความช่วยเหลือใดๆ
รุ่น.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)
มุมมอง.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 (ฉันจะเรียกข้อมูลที่เกี่ยวข้องในเทมเพลตได้อย่างไร)
<h3>{{ user.profile }}</h3>
<p>{{ user.profile.email }}</p>
<p>{{ user.profile.bio }}</p>
<h3>{{ profile }}</h3>
*อัปเดตเพื่อคำอธิบายที่ชัดเจนยิ่งขึ้น:
username
ในUser
หรือในรุ่นProfile
หรือไม่ กำลังพยายามคิดว่าเหตุใดคุณจึงใช้มุมมองสำหรับโปรไฟล์แทนที่จะเป็นเพียงสำหรับผู้ใช้... - person GProst   schedule 16.10.2020UserView
แทนUserProfileView
ที่ใช้User
model แทนProfile
ได้ไหม มันจะไม่ง่ายกว่านี้เหรอ? ฉันเห็นว่าในเทมเพลตคุณเข้าถึงprofile
ผ่านuser.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