我在Django项目中遇到了小问题,希望在这里能得到一些好的答案。
我通过执行如下代码将用户个人资料内联表单添加到django User表单中:
from django.core.exceptions import ValidationError
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.contrib.auth.models import User
from djangocalendar.models import UserProfile
from tableapp.models import *
from djangocalendar.models import *
from django import forms
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = True
verbose_name_plural = 'profile'
class MyUserChangeForm(UserChangeForm):
def clean_first_name(self):
if self.cleaned_data["first_name"].strip() == '':
raise ValidationError("First name is required.")
return self.cleaned_data["first_name"]
def clean_last_name(self):
if self.cleaned_data["last_name"].strip() == '':
raise ValidationError("Last name is required.")
return self.cleaned_data["last_name"]
# Define a new User admin
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
inlines = UserProfileInline,
# Register your models here
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
问题,我正面临这个问题,此行也与“用户添加”表单和“更改用户”表单一起出现。我不希望在添加用户时显示它。
赞在此屏幕截图中:内联表单与添加用户表单一起出现!我不想在这里添加内联表单。但是我想在用其他表单(如个人表单,信息表单)编辑用户时显示嵌入式表单。
答案 0 :(得分:1)
我找到了解决方法
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
inlines = UserProfileInline,
def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(MyUserAdmin, self).get_inline_instances(request, obj)