2010-10-21 109 views
3

如何從登錄用戶信息預填充管理員字段?從登錄用戶預填充管理員字段用戶

我有model.py:

from django.db import models 
class News(models.Model): 
    title = models.CharField(max_length=65) 
    body = models.TextField() 
    author = models.CharField(max_length=55) 

,我有admin.py:

from django.contrib import admin 
from django.contrib.auth.models import User 
from newsite.news.models import News 
class NewsAdmin(admin.ModelAdmin): 
    list_display = ('title','author') 
    search_fields = ['title', 'author'] 
    prepopulated_fields = {'author': (?????)} 
admin.site.register(News, NewsAdmin) 

我一直在努力試圖找出如何讓當前登錄用戶成prepopulated_field作者。

任何提示將不勝感激。謝謝。

回答

4

models.py是這樣的:

author = models.ForeignKey(User) 

Admin.py是這樣的:

class BugAdmin(admin.ModelAdmin): 
    fields = ['name', 'slug', 'summary', 'categories', 'status', 'browser', 'frequency', 'really_bug'] 
    exclude = ('author','excerpt') 
    prepopulated_fields = { 'slug' : ['name'] } 
    form = BugForm 

    def save_form(self, request, form, change): 
     obj = super(BugAdmin, self).save_form(request, form, change) 
     if not change: 
      obj.author = request.user 
     return obj 
+0

注意,他/她是從請求對象拉低數據。 (obj.poster = request.user)請求對象恰好在每次請求時都會首先生成。 – 2010-10-21 11:44:58

+0

非常感謝小費。還有一個問題: – Kevin 2010-10-21 12:25:45

+0

你有form = BugForm。那麼你是否忽略了管理員的默認表單?你有沒有可以作爲例子分享的forms.py?謝謝。 – Kevin 2010-10-21 12:26:50

相關問題