gpt4 book ai didi

django - 如何为 ModelAdmin 中的自定义字段分配初始值?

转载 作者:行者123 更新时间:2023-12-01 16:09:31 25 4
gpt4 key购买 nike

我正在尝试通过模型中的 onetonefield 扩展 django 用户身份验证。这是模型:

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

使用基本管理面板,我可以先创建用户实例,然后再创建配置文件。但是我在管理面板上使用自定义表单,所以我可以在一个表单上创建它。这是表单的外观:

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

谢谢你的帮助

最佳答案

试试这个:

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

也试试看差异:(字段仅在 super 调用后存在)

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

关于django - 如何为 ModelAdmin 中的自定义字段分配初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com