You can't use admin.site.register(User, PersonAdmin)
, since User
and Person
are not the same model. Also, it looks like you are trying to include these Person model fields inside the User admin:
from django.contrib.auth.admin
import UserAdmin
class PersonInline(admin.StackedInline):
""
" Details a person in line. "
""
model = Person
can_delete = False
verbose_name_plural = 'person'
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'city', 'state')
class UserAdmin(UserAdmin):
inlines = [
PersonInline
]
# Re - register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
<class 'polls.admin.PersonAdmin'>: anycodings_django (admin.E108) The value of anycodings_django 'list_display[4]' refers to 'age', which anycodings_django is not a callable, an attribute of anycodings_django 'PersonAdmin', or an attribute or method anycodings_django on 'auth.User'.,I'm trying to extend the User model to add anycodings_python additional attributes to my "Person" model anycodings_python when I create instances of it, and I keep anycodings_python getting the following errors:,Running Apollo Angular watchQuery() with different variables return the cache data,How to display Xcode code coverage when it's not displaying?
I'm trying to extend the User model to add anycodings_python additional attributes to my "Person" model anycodings_python when I create instances of it, and I keep anycodings_python getting the following errors:
ERRORS:
<class 'polls.admin.PersonAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'age', which is not a callable, an attribute of 'PersonAdmin', or an attribute or method on 'auth.User'.
<class 'polls.admin.PersonAdmin'>:(admin.E108) The value of 'list_display[5]' refers to 'city', which is not a callable, an attribute of 'PersonAdmin', or an attribute or method on 'auth.User'.
<class 'polls.admin.PersonAdmin'>: (admin.E108) The value of 'list_display[6]' refers to 'state', which is not a callable, an attribute of 'PersonAdmin', or an attribute or method on 'auth.User'.
Person model:
class Person(models.Model): "" " The model which defines a user of the application. Contains important information like name, email, city / state, age, etc "" " user = models.OneToOneField(User, on_delete = models.CASCADE) first_name = models.CharField(max_length = 200, null = True) last_name = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null = True) city = models.CharField(max_length = 200, null = True) state = models.CharField(max_length = 200, null = True) age = models.CharField(max_length = 50, null = True)
Create_account view:
def create_account(request):
#
function to allow a user to create their own account
if request.method == 'POST':
# sets a new user and gives them a username
new_user = User(username = request.POST["username"],
email = request.POST["email"],
first_name = request.POST["first_name"],
last_name = request.POST["last_name"],
age = request.POST["age"],
city = request.POST["city"],
state = request.POST["state"]
)
# sets an encrypted password
new_user.set_password(request.POST["password"])
new_user.save()
# adds the new user to the database
Person.objects.create(user = new_user,
first_name = str(request.POST.get("first_name")),
last_name = str(request.POST.get("last_name")),
email = str(request.POST.get("email")),
age = str(request.POST.get("age")),
city = str(request.POST.get("city")),
state = str(request.POST.get("state"))
)
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
You can't use admin.site.register(User, anycodings_django PersonAdmin), since User and Person are anycodings_django not the same model. Also, it looks like anycodings_django you are trying to include these Person anycodings_django model fields inside the User admin:
from django.contrib.auth.admin
import UserAdmin
class PersonInline(admin.StackedInline):
""
" Details a person in line. "
""
model = Person
can_delete = False
verbose_name_plural = 'person'
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'city', 'state')
class UserAdmin(UserAdmin):
inlines = [
PersonInline
]
# Re - register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Django: the value of list_display[4] refers to 'age', which is not a callable, etc,Django Custom User Model errors ((admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable,(admin.E108) The value of 'list_display[1]' refers to 'label', which is not a callable, an attribute of '?', or an attribute or method on 'org.Org',<class 'polls.admin.PersonAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'age', which is not a callable, an attribute of 'PersonAdmin', or an attribute or method on 'auth.User'.
You can't use admin.site.register(User, PersonAdmin)
, since User
and Person
are not the same model. Also, it looks like you are trying to include these Person model fields inside the User admin:
from django.contrib.auth.admin
import UserAdmin
class PersonInline(admin.StackedInline):
""
" Details a person in line. "
""
model = Person
can_delete = False
verbose_name_plural = 'person'
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'city', 'state')
class UserAdmin(UserAdmin):
inlines = [
PersonInline
]
# Re - register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
The fields option accepts the same types of values as list_display, except that callables aren’t accepted. Names of model and model admin methods will only be used if they’re listed in readonly_fields.,If you add the name of a callable to fields, the same rule applies as with the fields option: the callable must be listed in readonly_fields.,Lists of applications and models are sorted alphabetically by their names. You can override this method to change the default order on the admin index page.,Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).
from django.contrib
import admin
from myapp.models
import Author
class AuthorAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)
from django.contrib
import admin
from myapp.models
import Author
admin.site.register(Author)
from django.contrib
import admin
from.models
import Author
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
pass
from django.contrib
import admin
from.models
import Author, Editor, Reader
from myproject.admin_site
import custom_admin_site
@admin.register(Author, Reader, Editor, site = custom_admin_site)
class PersonAdmin(admin.ModelAdmin):
pass
from django.contrib
import admin
class AuthorAdmin(admin.ModelAdmin):
date_hierarchy = 'pub_date'
date_hierarchy = 'pub_date'
It is possible to include a model member function in the list_display Admin property. The same thing is not possible for ForeignKey models; at least not with any of the variations I have tried: foreign.method, foreign_method and foreign__method. , If anyone else who wants to be able to refer to foreign keys with underscore syntax in list_display comes across this ticket, I put together a subclass of ModelAdmin to do that: , There is no need to support functions on ForeignKey models. You can encapsulate that in a function on the model. , There's a trivially-easy solution you can code: methods on your model or model admin that return the information you desire, listed in your list_display.
I just wanted to raise this again. I'm using the new forms admin branch and it's odd that in the following
class BlueEDIJobFileAdmin(admin.ModelAdmin):
search_fields = ('blueedijob__client__code', )
list_display = ('id', 'blueedijob__client__code', )
I was going to experiment to see, but I can't. First, the patch doesn't apply cleanly to existing trunk. The actual apply failures are on the tests, not the code, so I thought I could experiment with the code, but I can't get that to work either. If I add something with the double underscore syntax to the list_display for one of the models in my app, I get an ImproperlyConfigured exception thrown during admin validation:
Traceback:
File "/home/kmt/django/trunk/django/core/handlers/base.py" in get_response
77. request.path_info)
File "/home/kmt/django/trunk/django/core/urlresolvers.py" in resolve
179. for pattern in self.urlconf_module.urlpatterns:
File "/home/kmt/django/trunk/django/core/urlresolvers.py" in _get_urlconf_module
198. self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
File "/home/kmt/software/web/xword/../xword/urls.py" in <module>
9. admin.autodiscover()
File "/home/kmt/django/trunk/django/contrib/admin/__init__.py" in autodiscover
40. __import__("%s.admin" % app)
File "/home/kmt/software/web/xword/../xword/crossword/admin.py" in <module>
61. admin.site.register(Puzzles, PuzzlesAdmin)
File "/home/kmt/django/trunk/django/contrib/admin/sites.py" in register
76. validate(admin_class, model)
File "/home/kmt/django/trunk/django/contrib/admin/validation.py" in validate
38. % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
Exception Type: ImproperlyConfigured at /admin/crossword/authors/
Exception Value: PuzzlesAdmin.list_display[4], 'AuthorID__Notes' is not a callable or an attribute of 'PuzzlesAdmin' or found in the model 'Puzzles'.
All I want to do is:
list_display = ('foreign_key__related_fieldname1', 'foreign_key__related_fieldname2')
def foreign_field(field_name):
def accessor(obj):
val = obj
for part in field_name.split('__'):
val = getattr(val, part)
return val
accessor.__name__ = field_name
return accessor
ff = foreign_field
class MyAdmin(ModelAdmin):
list_display = [ff('foreign_key__related_fieldname1'),
ff('foreign_key__related_fieldname2')
]
So you can just do:
class FooAdmin(RelatedFieldAdmin):
list_display = ('address__phone', 'address__country__country_code')
You can't use admin.site.register(User, PersonAdmin), since User and Person are not the same model. Also, it looks like you are trying to include these Person model fields inside the User admin:,There is a typo in your admin class as you are not overriding the default list_display option which contains first_name. It should be list_display instead of List_display inside UserAdmin:,Using TestCaseSource, you should be able to loop over an array of values and invoke the desired methods, for example like this:,process potentially async aggregate tasks in parallel and process them as each task completes in Unity
from django.contrib
import admin
from org.models
import Org
class OrgAdmin(admin.ModelAdmin):
list_display = ('name', 'label') # The error was there
admin.site.register(Org, OrgAdmin)
from django.contrib.auth.admin
import UserAdmin
class PersonInline(admin.StackedInline):
""
" Details a person in line. "
""
model = Person
can_delete = False
verbose_name_plural = 'person'
fields = ('username', 'email', 'first_name', 'last_name', 'age', 'city', 'state')
class UserAdmin(UserAdmin):
inlines = [
PersonInline
]
# Re - register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
class UserAdmin(BaseUserAdmin):
add_form = UserCreationForm
list_display = ('username', 'email', 'is_admin')
list_filter = ('is_admin', )
fieldsets = (
(None, {
'fields': ('username', 'email', 'password')
}),
('Permissions', {
'fields': ('is_admin', )
}),
)
search_fields = ('username', 'email')
ordering = ('username', 'email')
filter_horizontal = ()
admin.site.register(MyUser, UserAdmin)
# bad habit to be using the old style class definition(i.e.
`class Foo:`)
# the `@property`
decorator wont work
if you use the old style
class Sync(object):
def __init__(self, name, value, * dependants):
""
"Sync the attribute `name` on all `dependants` when `self.value` is updated"
""
self._name = name
self._value = value
self._updating = False
self._dependants = list(dependants)
self._update_dependants()
@property
def value(self):
return self._value
@value.setter
def value(self, x):
if x != self._value:
self._value = x
self._update_dependants()
def _update_dependants(self):
self._updating = True
for d in self._dependants:
if getattr(d, self._name) != self.value:
if isinstance(d, Sync):
if not d._updating:
setattr(d, self._name, self.value)
else:
setattr(d, self._name, self.value)
self._updating = False
def add_dependant(self, other):
self._dependants.append(other)
self._update_dependants()
def del_dependnant(self, other):
self._dependants.remove(other)
def __repr__(self):
return "Sync('" + self._name + "': " + repr(self.value) + ")"
def __eq__(self, other):
if isinstance(other, Sync):
return self.value == other.value
else:
return self.value == other
def __ne__(self, other):
return not self.__eq__(other)
s1 = Sync('value', 2)
s2 = Sync('value', 1)
print('setup the Sync objects:')
print('>>> ' + repr(s1) + (' == '
if s1 == s2
else ' != ') + repr(s2))
s1.add_dependant(s2)
s2.add_dependant(s1)
print('add sync objects as dependants of each other:')
print('>>> ' + repr(s1) + (' == '
if s1 == s2
else ' != ') + repr(s2))
s1.value += 1
print('check that value changes transfer from one to the other:')
print('>>> ' + repr(s1) + (' == '
if s1 == s2
else ' != ') + repr(s2))
<figure itemprop="image" itemscope itemtype="http://schema.org/ImageObject">
<figure itemprop="hasPart" itemscope itemtype="http://schema.org/ImageObject">
<script>
$("input[title]").on("keyup", function () {
/*We had emitted ToolTip attribute on our controls in Grid.
Those are translated to `title` in the browser. Here we are
picking controls based on the values that would be set by
asp.net while rendering grid.*/
var $t = $(this),
//pick value of title or tooptip attribute of $t control
i = $t.attr("title") || $t.attr("tooltip");
//we get value of $t and initialize a number from it as it is a string
var s = Number($t.val());
//if we are not able get a number from textbox value, return
if (isNaN(s)) return;
//we are looking for a span which has title attribute set to value
//we picked from textbox above also having class lbl-price
//and getting its text
var p = $("span[title='" + i + "'].lbl-price").text();
//then we get next span with same title value but class lbl-total
// and set its text to calculated value.
$("span[title='" + i + "'].lbl-total").text(s * +p);
});
</script>
Joined Oct 4, 2020 , Posted on Oct 31, 2020 • Updated on Oct 11, 2021
#we will use venv module to install Django #navigate to your working directory and run the below command python - m venv "vertual_environment_name" #now activate the virtual environment / venv / scripts / activate.bat # now Install Django pip install django == 3.0 .8
#your virtual env should be activated
django - admin startproject "project_name"
#navigate to your project folder
python manage.py startapp "app_name"
python manage.py startapp users
#add users app to installed_apps in your settings.py file
from django.db
import models
from django.utils
import timezone
from django.utils.translation
import gettext_lazy as _
from django.contrib.auth.models
import AbstractBaseUser, PermissionsMixin, BaseUserManager
# 1. creating Custome Manager
for User Model
class CustomAccountManager(BaseUserManager):
def create_user(self, email, user_name, first_name, password, ** other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
# convert all in lowercase
email = self.normalize_email(email)
user = self.model(email = email, user_name = user_name,
first_name = first_name, ** other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, user_name, first_name, password, ** other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError('Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, user_name, first_name, password, ** other_fields)
# 2. Creating Custom User Model
class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique = True)
user_name = models.CharField(max_length = 150, unique = True)
first_name = models.CharField(max_length = 150)
start_date = models.DateTimeField(
default = timezone.now)
about = models.TextField(_('about'), max_length = 500, blank = True)
is_staff = models.BooleanField(
default = False)
is_active = models.BooleanField(
default = True)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
# required
for superuser
REQUIRED_FIELDS = ['user_name', 'first_name']
def __str__(self):
return self.user_name
# you must have added the users app into the installed_apps # add this attribute AUTH_USER_MODEL = 'users.NewUser' # it will tell Django to use this as a User Authentication model.
from django.contrib
import admin
from.models
import NewUser
from django.contrib.auth.admin
import UserAdmin
from django.forms
import Textarea
class UserAdminConfig(UserAdmin):
model = NewUser
search_fields = ('email', 'user_name', 'first_name', )
list_filter = ('email', 'user_name', 'first_name',
'is_active', 'is_staff')
ordering = ('-start_date', )
list_display = ('email', 'user_name', 'first_name',
'is_active', 'is_staff')
fieldsets = (
(None, {
'fields': ('email', 'user_name', 'first_name')
}), ('Permissions', {
'fields': ('is_staff', 'is_active')
}),
('Personal', {
'fields': ('about', )
}),
)
formfield_overrides = {
NewUser.about: {
'widget': Textarea(attrs = {
'rows': 10,
'cols': 40
})
},
}
add_fieldsets = (
(None, {
'classes': ('wide', ),
'fields': ('email', 'user_name', 'first_name', 'password1', 'password2', 'is_active', 'is_staff')
}),
)
admin.site.register(NewUser, UserAdminConfig)