2013-04-06 21 views
0

我對python或django非常陌生。我繼承了一些需要一些「修復」的代碼,我可以使用一些幫助。Django ModelChoiceField顯示django.contrib.auth和配置文件表中的值

這裏的情況:

我們有一個下拉框,從中可以選擇多個用戶。目前,用戶顯示爲用戶名。我們希望將它們顯示爲全名。

的問題: 的用戶名是來自:django.contrib.auth

名字和姓氏是從剖面模型來。 這裏的剖面模型的樣子:

class Profile(models.Model): 
CURRENTLY_STUDENT = "STU" 
CURRENTLY_PROFESSOR = "PFR" 
CURRENTLY_CHOICES = [ 
    (CURRENTLY_STUDENT, "Student"), 
    (CURRENTLY_PROFESSOR, "Professor"), 
] 

user = models.OneToOneField(User, related_name="profile") 
currently_am = models.CharField(max_length=3, choices=CURRENTLY_CHOICES, default=CURRENTLY_STUDENT) 
first_name = models.CharField(max_length=50) 
last_name = models.CharField(max_length=50) 

如果你必須顯示我們使用全名如下:

user.profile.display_name 

其中DISPLAY_NAME是:

def display_name(self): 
     name = "%s %s" % (self.first_name, self.last_name) 
    return name 

以下是代碼爲forms.py中的下拉框:

from django import forms 
from django.contrib.auth.models import User 
from account.utils import user_display 


class UserMultipleChoiceField(forms.ModelMultipleChoiceField): 

def label_from_instance(self, obj): 
    return user_display(obj) 


class ShareForm(forms.Form): 

participants = UserMultipleChoiceField(
    queryset=User.objects.none(), 
    label="", 
    widget=forms.SelectMultiple(
     attrs={ 
      "data-placeholder": "Choose members.. " 
     } 
    ) 
) 

以下是從帳戶/ utils.py代碼爲user_display

from account.conf import settings 

def user_display(user): 
return settings.ACCOUNT_USER_DISPLAY(user) 

,這裏是從帳戶/ conf.py代碼

class AccountAppConf(AppConf): 
USER_DISPLAY = lambda user: user.username 
  • 不能使用obj.get_full_name()作爲名字和姓氏不是來自django.contrib.auth,而是存儲在上面提到的配置文件模型中。

  • 由於ModelChoiceField是在django.contrib.auth上繪製的,因此無法使用return obj.profile.display_name()。

請問有人能幫助我嗎?如何在下拉框中顯示全名,並且在某人從下拉列表中選擇並點擊提交後仍然將「用戶」作爲值傳遞?

謝謝您的幫助:)

回答

1

那麼你可以指定自定義選擇,如:

choices = [(obj.id, obj.profile.display_name()) for obj in User.objects.all()] 

participants = UserMultipleChoiceField(
    queryset=User.objects.none(), 
    label="", 
    widget=forms.SelectMultiple(
     attrs={ 
      "data-placeholder": "Choose members.. " 
     } 
    ), 
    choices=choices 
) 
+0

感謝阿米爾。對此,我真的非常感激 :) – Ace 2013-04-18 21:50:00

相關問題