[英]Foreign key to User table in django
我正在使用 django 的內置 contrib.auth 模塊,並在添加“帖子”時為用戶設置了外鍵關系:
class Post(models.Model):
owner = models.ForeignKey('User')
# ... etc.
現在當談到實際添加 Post 時,我不確定在調用 save() 之前在 owner 字段中提供什么。 我期望在用戶會話中出現類似 id 的內容,但我注意到 User 沒有 user_id 或 id 屬性。 我應該從用戶的經過身份驗證的會話中提取哪些數據來填充所有者字段? 我試圖查看數據庫表中發生了什么,但對 sqlite 設置還不太了解。
謝謝你的幫助...
您想提供一個“用戶”對象。 即你從 User.objects.get(pk=13) 得到的東西。
如果您使用 Django 的身份驗證組件,則用戶也會附加到請求對象,您可以直接在視圖代碼中使用它:
request.user
如果用戶未通過身份驗證,那么 Django 將返回 django.contrib.auth.models.AnonymousUser 的一個實例。 (每個http://docs.djangoproject.com/en/dev/ref/request-response/#attributes )
要求 --> Django 3、python 3
1)為了將用戶名添加到owner = models.ForeignKey('User')
以保存,在第一步中,您必須from django.conf import settings
添加models.py
上方的from django.conf import settings
並編輯owner = models.ForeignKey('User')
到這個樣本:
class Post(models.Model):
slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
2)並且要在Post
顯示詳細信息Post
,特殊所有者姓名或家庭或用戶名,您必須在views.py
第二步中添加以下代碼:
from django.shortcuts import get_object_or_404
.
.
.
def detailPost(request,slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
'instance': instance,
}
return render(request, template_name='detail_post.html', context=context)
3)在第三步中,您必須添加以下代碼以顯示創建帖子的用戶全名等用戶信息:
<p class="font-small grey-text">Auther: {{ instance.owner.get_full_name }} </p>
現在如果你想使用用戶名,你可以使用{{ instance.owner.get_username }}
或者如果你想訪問短名稱,你可以使用{{ instance.owner.get_short_name }}
。 有關更多信息,請參閱此鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.