내 앱에서 사용자는 프로필을 연결할 수 있습니다. 사이트의 모든 페이지에 표시되는 사이드 바에서 사용자가 연결된 프로필의 사용자 이름을 표시하려고합니다. 지금까지 프로필을 연결하는 m2m 필드를 만들었습니다. 사용자가 로그인하면이 정보를 세션에 저장하여 다른 세션 정보와 함께 번들로 제공 할 수 있으며 명시 적으로 전달되어야하는 다른 변수를 만들지 않습니다. 각 템플릿. 그러나 연결된 프로필 목록에 액세스 할 때 프로필에 대한 ID 만 액세스 할 수 있으며 프로필에 대한 다른 정보는 액세스 할 수 없습니다.django 템플릿에서 m2m 관계에 액세스하는 방법
모델
class Profile(models.Model):
username = models.CharField(max_length=25)
link = models.ManyToManyField('self', null=True, blank=True, related_name='link_profiles')
보기
def link_profiles(request, pid):
#get both profiles
my_p = Profile.objects.get(id=request.session['profile']['id'])
their_p = Profile.objects.get(id=pid)
#add profiles to eachothers links
my_p.link.add(their_p)
their_p.link.add(my_p)
#save profiles
my_p.save()
their_p.save()
#reset my session var to include the new link
#this is that same bit of code that sets the session var when the user logs in
request.session['profile'] = model_to_dict(my_p)
return redirect('/profiles/' + pid)
템플릿 (사용 pyjade)
- for profile in session.profile.link
div
a(href="/profiles/{{ profile }}") profile {{ profile }}
이 의지 출력 <a href='/profiles/5'>profile 5</a>
같은,하지만 profile.id
및 profile.username
를 사용하여 그냥 <a href='/profiles/'>profile</a>
에 빈 공간을두고 . 이 방법으로 다른 세션 변수 (예 : request.session['links']
)를 만들 필요없이이 정보에 액세스 할 수 있습니까?