2016-11-15 63 views
2

我想通過模型中的onetonefield擴展django用戶身份驗證。這裏是模型:如何將初始值分配給ModelAdmin中的自定義字段?

from django.db import models 
from django.contrib.auth.models import User 
from django.db.models.signals import post_save 
from django.dispatch import receiver 


class Profile(models.Model): 
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    nim = models.CharField(max_length=10, blank=True) 

    def __str__(self): 
     return self.user.username 

隨着基本的管理面板,我得到先創建用戶實例,然後配置文件。但我用自定義表單管理面板上,所以我可以在一個form.This創建它的形式看:

Profile add form

這是forms.py

from django import forms 
from django.contrib.auth.models import User 

from .models import Profile 


class ProfileForm(forms.ModelForm): 
    username = forms.CharField(required=False, max_length=150) 
    password = forms.CharField(required=False, max_length=50, widget=forms.PasswordInput) 

    class Meta: 
     model = Profile 
     fields = ('username', 'password', 'nim') 

,這是admin.py

from django.contrib import admin 
from django.contrib.auth.models import User 

from .forms import ProfileForm 
from .models import Profile 


class ProfileAdmin(admin.ModelAdmin): 
    form = ProfileForm 

    def save_model(self, request, obj, form, change): 
     username = form.cleaned_data['username'] 
     password = form.cleaned_data['password'] 
     user = User.objects.create_user(username=username, password=password) 
     user.save() 
     obj.user = user 
     obj.save() 


admin.site.register(Profile, ProfileAdmin) 

有了這一切,我可以創建配置文件實例就好了。但是,當我嘗試更改/編輯配置文件時,它沒有顯示用戶名和密碼字段的初始值,只有nim字段。

empty username and password field

感謝您的幫助

回答

3

試試這個:

class ProfileAdmin(admin.ModelAdmin): 
    form = ProfileForm 
    # ... 
    def get_form(self, request, obj=None, *args, **kwargs): 
     form = super(ProfileAdmin, self).get_form(request, *args, **kwargs) 
     #find the user via user profile forien key 
     the_user = User.objects.filter(pk=Profile.user.pk) 
     # Initial values 
     form.base_fields['username '].initial = the_user.username 
     return form 

也試試這個,看看DIFF:(場後才超級​​呼叫住)

 form.fields['username '].initial = the_user.username 
+0

它返回profileadmin沒有屬性用戶。 –

+0

oops:the_user = User.objects.filter(pk = Profile.user.pk) –

+1

form.fields提高屬性錯誤,稱ProfileForm沒有屬性字段。 form.base_fields適合我。謝謝 –

相關問題