Ordering users by date created in django admin panel - python

How do you order users in the django admin panel so that upon display they are ordered by date created? Currently they are listed in alphabetical order
I know that I can import the User model via: from django.contrib.auth.models import User
How do I go about doing this?

To change the default ordering of users in admin panel you can subclass the default UserAdmin class. In your applications's admin.py:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyUserAdmin(UserAdmin):
# override the default sort column
ordering = ('date_joined', )
# if you want the date they joined or other columns displayed in the list,
# override list_display too
list_display = ('username', 'email', 'date_joined', 'first_name', 'last_name', 'is_staff')
# finally replace the default UserAdmin with yours
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
For more information refer to the documentation.

The admin site will default to the ordering specified on your model itself, e.g.
class MyUserModel:
created = models.DateTimeField()
class Meta:
ordering = ('created', )
If you want something more flexible, that is, if you want to use Django default user model without subclassing it, take a look at https://docs.djangoproject.com/ja/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
--
Edit: While what I say is not wholly incorrect, #rafalmp's answer is the right one.

Related

I want to create custom signup form and add extra fields in Django default user model

I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city.
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
full_name=forms.CharField(max_length=50,required=True)
phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'}))
address=forms.CharField(max_length=200,required=True)
city=forms.CharField(max_length=200,required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city')
def register(self):
self.save()
I created form by using this method. First, created forms.py for extra fields then inherited it. It is working; but still some fields disappear.
Because, you are adding additional fields to the default user model. First you have to
-Create a Custom User Model by using AbstractUser
Then
-Create a Custom Form for UserCreationForm
You can search google for:
Extend-existing-user-model-in-django

Merging "add" form in Django Admin from 2 or more Models (connected with one-to-one relationship)

I have a Django's default UserCreationForm to add a new user via Admin app. I want to add new fields from another custom model called UserProfile. The UserProfile has a One-to-One relationship with Django's User model. The additional fields which UserProfile model has are phone number, company name etc.
Is there a way where I can merge UserProfile form with Django's default User form while creation of the new user from Admin panel?
I looked at Django's documentation here on Inline forms but seems their require foreign key relationship.
Django 2.1
Assuming you have Profile with extra field phone_number. Like this
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
phone_number = models.CharField(max_length=24)
You can follow following steps to add extra fields in UserCreationForm in Admin.
1. Create custom UserCreationForm
Inherit from UserCreationForm and Add extra fields and functionality.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from account.models import Profile
class UserWithProfileCreationForm(UserCreationForm):
phone_number = forms.CharField(max_length=32)
def save(self, commit=True):
instance = super().save(commit=True)
profile = Profile(user=instance, phone_number=self.cleaned_data['phone_number'])
profile.save()
return instance
2. Unregister (already registered) User model and register again with custom form and fields
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# unregister first
admin.site.unregister(User)
#admin.register(User)
class UserWithProfileAdmin(UserAdmin):
add_form = UserWithProfileCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
# add any custom fields here
'fields': ('username', 'password1', 'password2', 'phone_number'),
}),
)
There are two ways to do this.
First, you can create a custom User model from AbstractBase
# models.py
class MyUser(AbstractBaseUser):
profile = models.OneToOneField(UserProfile)
And then update your admin view.
#admin.py
from django.contrib.auth.admin import UserAdmin
class UserProfileInline(admin.TabularInline):
model = UserProfile
class MyUserAdmin(UserAdmin):
inlines = [
UserProfileInline,
]
admin.site.register(MyUser, MyUserAdmin)
Second, you can simply add the OneToOneField(User) in your UserProfile model, and follow the similar method to update the admin view.

Django - Change Fields in Group Admin Model

The built-in django group model on the admin site only shows name:
but I want to include additional fields that are already part of the group model, such as id.
I have tried adding these fields using the following admin.py setup:
from django.contrib import admin
from django.contrib.auth.models import Group
class GroupsAdmin(admin.ModelAdmin):
list_display = ["name", "pk"]
class Meta:
model = Group
admin.site.register(Group, GroupsAdmin)
But this returns the error:
django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered.
I have successfully registered other models (I've created) on admin but the above doesn't work for those models that are already a part of django.
How can I add fields in the admin model for Group?
The accepted answer is correct, however, I would like to point out that you could inherit from the GroupAdmin if your goal is only extending that is, and not modifying:
from django.contrib.auth.admin import GroupAdmin
class GroupsAdmin(GroupAdmin):
list_display = ["name", "pk"]
admin.site.unregister(Group)
admin.site.register(Group, GroupsAdmin)
You need to unregister it first from the built-in Group model and then register it again with your custom GroupAdmin model.
So:
class GroupsAdmin(admin.ModelAdmin):
list_display = ["name", "pk"]
class Meta:
model = Group
admin.site.unregister(Group)
admin.site.register(Group, GroupsAdmin)
Also, the Meta class is not required. You can remove it.

Indirect inline in Django admin

I have the following models:
class UserProfile(models.Model):
user = models.OneToOneField(User)
class Property(models.Model):
user = models.ForeignKey(User)
I would like to create a TabularInline displaying every Property connected to a particular UserProfile on its Django admin page. The problem here is, of course, that Property does not have a ForeignKey directly to UserProfile, so I cannot simply write
class PropertyTabularInline(admin.TabularInline):
model = Property
class UserProfileAdmin(admin.ModelAdmin):
inlines = (PropertyTabularInline,)
How can I easily do what I want?
You can overwrite the User admin page to display both the Profile and the Property models.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from myapp.models import *
class ProfileInline(admin.TabularInline):
model = Profile
class PropertyInline(admin.TabularInline):
model = Property
class UserAdmin(UserAdmin):
inlines = (ProfileInline, PropertyInline,)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
You can also remove any unwanted/unused User properties from being displayed (e.g. Groups or Permissions)
more here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model
and here:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
class PropertyTabularInline(admin.TabularInline):
model = Property
def formfield_for_dbfield(self, field, **kwargs):
if field.name == 'user':
# implement your method to get userprofile object from request here.
user_profile = self.get_object(kwargs['request'], UserProfile)
kwargs["queryset"] = Property.objects.filter(user=user_profile)
return super(PropertyInLine, self).formfield_for_dbfield(field, **kwargs)
once this is done, you can add this inline to user UserProfileAdmin like:
class UserProfileAdmin(admin.ModelAdmin):
inlines = (PropertyTabularInline,)
Haven't tested it, but that should work.
It is achievable by making one change in your models.
Instead of creating OneToOne relationship from UserProfile to User, subclass User creating UserProfile. Code should look like that:
class UserProfile(User):
# some other fields, no relation to User model
class Property(models.Model):
user = models.ForeignKey(User)
That will result in creating UserProfile model that have hidden OneToOne relation to User model, it won't duplicate user model.
After doing that change, your code will work. There are some changes under the hood, like UserProfile no longer have it's own ID, you can access fields from User inside UserProfile and it's hard to swap User model using settings.AUTH_USER_MODEL (that will require creating some custom function returning proper type and changing migration by hand) but if this is not a problem for you, it may be good solution.

Django admin panel doesn't work after modify default user model

I was trying to extend user profile. I founded a few solutions, but the most recommended was to create new user class containing foreign key to original django.contrib.auth.models.User class. I did it with this so i have in models.py:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
website_url = models.URLField(verify_exists=False)
and in my admin.py
from django.contrib import admin
from someapp.models import *
from django.contrib.auth.admin import UserAdmin
# Define an inline admin descriptor for UserProfile model
class UserProfileInline(admin.TabularInline):
model = UserProfile
fk_name = 'user'
max_num = 1
# Define a new UserAdmin class
class MyUserAdmin(UserAdmin):
inlines = [UserProfileInline, ]
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
And now when I'm trying to create/edit user in admin panel i have an error:
"Unknown column 'content_userprofile.id' in 'field list'" where content is my appname.
I was trying to add line AUTH_PROFILE_MODULE = 'content.UserProfile' to my settings.py but with no effect.
How to tell panel admin to know how to correctly display fields in user form?
After some effort I found working solution:
the AUTH_PROFILE_MODULE = 'content.UserProfile' is required
please drop your database (auth_user, yourapp_userprofile tables should be enough)
finally python manage.py syncdb

Categories

Resources