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.
Related
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
I want to customize Django Admin to have specific section for objects of my models (Such as Post or Product models) that use as an archive section.
I now that, I need one field in my models that shown status of objects (Such as is_archive field), but I don't have any idea about how to display them in Django Admin.
Does anyone have an opinion on this?
Create Proxy model for model you need
Create separate section in your admin panel for this proxy model
Override get_queryset() for it.
models.py
from django.db import models
class Post(models.Model):
...
is_archive = models.BooleanField(default = False)
...
class PostProxy(Post):
class Meta:
proxy = True
admin.py
from django.contrib import admin
from .models import *
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
...
#admin.register(PostProxy)
class PostProxyAdmin(admin.ModelAdmin):
...
def get_queryset(self, request):
return super().get_queryset(request).filter(is_archive=True)
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.
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.
Any suggestion on this please?
Initially I had class Customer(): in models.py
This is how the code in admin.py looked
from django.contrib import admin
from booknowapp.models import Customer
# Register your models here.
admin.site.register(Customer)
Now that I have added two new classes to models how do I register in admin for other new two classes to appear in the app? I am not sure of the syntax to be used.
If your added two new classes of models are ModelClass1 and ModelClass2 then you can register multiple models in admin.py like :
from django.contrib import admin
from booknowapp.models import Customer, ModelClass1, ModelClass2
myModels = [Customer, ModelClass1, ModelClass2] # iterable list
admin.site.register(myModels)
OR
You can repeat admin.site.register for other two new classes just like your Customer .
If you extend the syntax that you have already used, it would simply be:
from django.contrib import admin
# wrap the line if it's too long
from booknowapp.models import (
Customer,
SecondModel,
ThirdModel
)
# Register your models here.
admin.site.register(Customer)
admin.site.register(SecondModel)
admin.site.register(ThirdModel)
However, this will only give you the default admin model list views - which you will probably want to extend.
class CustomerAdmin(admin.ModelAdmin):
"""Specialised admin view for the Customer model."""
# set the fields to display
list_display = ('name', 'address', 'registered')
# register your Customer model, using the CustomerAdmin view
admin.site.register(Customer, CustomerAdmin)
The ModelAdmin has lots more functionality that you can leverage - search fields, filtering, custom fields, custom actions ('Activate customer'), which you can read about here - http://www.djangobook.com/en/2.0/chapter06.html#custom-modeladmin-classes