django custom user model groups and permissions - django

I am trying to implement custom user model in my django application.
If I just copy and paste the code from this article, it works great. But I wish this custom user model to have permissions and groups. So I added this inheritance to models.py:
class MyUser(AbstractBaseUser, PermissionsMixin):
and these fields into the admin.py MyUserAdmin(UserAdmin) class:
('Permissions', {'fields': (
'is_admin', 'is_staff', 'is_active', 'groups', 'user_permissions',
)}),
But it looks strange for me:
As I know, it must be two containers: left (that I have) that shows all available groups and permissions and right (that I don't have) that shows all current user's groups and permissions.
P.S. I tried google for it and found only one post on reddit which is 10 month old but doesn't have a solution.

Deleting this line in MyUserAdmin class fixed the problem up.
filter_horizontal = ()

You must set argument in filter_horizontal(ARGUMENT),
the argument is your field manyToMany in model.
Example:
class CustomUser(PermissionsMixin, AbstractBaseUser):
custom_groups = models.ManyToManyField('CustomUserGroups', blank=True)
class CustomUserAdmin(UserAdmin):
filter_horizontal = ('custom_groups', )

Related

Django - Display User Email in User Profile Admin

This may be a very simple question, but I haven't been able to find it in SO.
I created a User Profile Model for additional user info via OnetoOneField. Now for the Admin of the User Profile Model, I want to display the email field found in the User model. I tried:
# models.py
def email(self):
return self.user.email
# admin.py
fieldsets = [
('', {'fields': [
...
'email',
...
]})
]
list_display = (
...
'email',
...
)
This worked for the list_display section, but for fieldsets, the following error popped up:
Unknown field(s) (email) specified for UserProfile. Check fields/fieldsets/exclude attributes of class UserProfileAdmin.
Is there a way to work around this? Thank you in advance!
From the documentation:
fields can contain values defined in readonly_fields to be displayed
as read-only.
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.
So you need to add:
readonly_fields = ('email',)
to your model admin class, and then it will be available in the fieldset.
Put this
def email(self, obj):
return obj.user.email
in your admin class of userprofile and you will be able to use it in fieldsets.

Django auth - Adding user fields - displaying in admin

I'm a complete n00b to django & python. I come from a PHP background so you'll have to accept my apologies for that :p.
I'm trying to use the admin panel functionality in django to show different options to different people.
The system should allow admins to add "projects" to a list. "Developers" should then be able to view only projects assigned to them, and only change certain fields.
So I guess the question is two fold:
1) Is allowing the "Developers" to login to the admin system the best method of doing it?
1.a) If so, How do I get a boolean field to display on the admin's user form? I just want to flag is_developer. I've added it as a userProfile but don't understand how to make it display on the form
2) Should I disallow them to login (to the admin panel) and make "frontend" whereby they can only see what they're allowed?
I hope that made sense. I'm a bit all over the place at the moment as it's a complete departure to what i'm used to!
Thanks in advance for any help you can offer me :)
There's a lot going on here, so I'm going to piecemeal my answer.
Is allowing the "Developers" to login to the admin system the best method of doing it?
That depends on your setup. Generally, the admin should only be available to "staff": people that are employed by or directly related to your organization. In fact, in order to login to the admin, a user must have is_staff=True. If all of the users belong to your organization (and can be considered "trusted" as a result), then yes, it's fine to allow them to all access the admin. Otherwise, it's not a good idea, as you're opening yourself up to security risks.
If so, How do I get a boolean field to display on the admin's user form?
In the most simplistic sense, you can add a field to a form by literally adding it to the form class, even if it's a ModelForm which pre-populates its fields from the fields on the model.
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
is_developer = forms.BooleanField(default=False)
I've added it as a userProfile but don't understand how to make it display on the form
UserProfile is a different model, obviously, so its fields are not made available on a form for a User. However, Django does provide the ability to add/edit related models inline with edit form for another model. This is done through inline formsets. In the admin, these are just called "inlines".
class UserProfileInlineAdmin(admin.StackedInline):
model = UserProfile
max_num = 1
can_delete = False
class UserAdmin(admin.ModelAdmin):
inlines = [UserProfileInlineAdmin]
The view you get from an inline admin is clearly distinct from the main form (in this case, that of User), though. You can try it out to see what I mean. It's not horrible, but it's still a noticeable break in the form. The reason I mentioned how to add a field to a form earlier, is that if you wanted, you can make it look all like one form with a little bit of clever misdirection.
class UserAdminForm(forms.ModelForm):
class Meta:
model = User
is_developer = forms.BooleanField(default=False)
def save(self, commit=True):
user = super(UserAdminForm, self).save(commit=commit)
if user.pk:
profile = user.get_profile()
profile.is_developer = self.cleaned_data.get('is_developer')
profile.save()
That's a simplistic example, but the idea is that you add the field(s) manually to the form, and then use them to actually update the other object manually when the main object being edited is saved.
Special notes related to User
Now, since you're dealing with User here, there's a lot more sticky details. First, User already has a UserAdmin and its own forms -- yes plural, forms. If you want to add new functionality, you need to make sure you keep the existing Django functionality in the process.
from django.contrib.auth.admin import UserAdmin
form django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
# do stuff
class CustomUserChangeForm(UserChangeForm):
# do stuff
class CustomUserAdmin(UserAdmin):
form = CustomUserChangeForm
add_form = CustomUserCreationForm
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
Also, UserAdmin has its own set of fieldsets defined. The defaults are:
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
(_('Groups'), {'fields': ('groups',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2')}
),
)
If you want to add a field or fields, you'll need to redefine those two attributes with your fields added where you want them.

Django admin, foreign key field in list_editable

Hi fellow django users,
How can I add a field from a related object in the list_editable admin property?
# models.py
class Order(Model):
reference = CharField(max_length=25)
class Product(Model):
name = CharField(max_length=50)
order = ForeignKey(Order)
# admin.py
class ProductAdmin:
list_display = ('name', 'order_reference')
list_editable = ('name', 'order__reference') # <--- THIS !
def order_reference(self, obj):
return obj.order.reference
I tried it this way, but it won't work. I also tried to add a property in the Product class, but nope, it won't work either. Any clue?
Thanks.
From the documentation:
list_editable interacts with a couple of other options in particular
ways; you should note the following rules:
Any field in list_editable must also be in list_display. You can't edit a field that's not displayed!
The same field can't be listed in both list_editable and list_display_links -- a field can't be both a form and a link.
You'll get a validation error if either of these rules are broken.
Notice that you use *order_reference* and *order__reference* in list_display and list_editable, respectively. So in short, I don't think you can do this easily. If you want to have inspiration, you could check out the implementation of pageadmin.py in django-cms, but it's NOT straightforward!!

Django admin - how to hide some fields in User edit?

How can I hide fields in admin User edit? Mainly I want to hide permissions and groups selecting in some exceptions, but exclude variable doesn't work :/
I may be late to answer this question but any ways, here goes. John is right in concept but I just wanted to do this because I know django admin is truly flexible.
Any way's the way you hide fields in User model form is:
1. exclude attribute of the ModelAdmin class can be used to hide the fields.
2: The should allow blank in model.
3: default attribute on model field is an advantage or you might get unexpected errors.
The problems I had was that I used to get a validation error. I looked at the trace back and found out that
the error was because of UserAdmin's fieldsets grouping, the default permission field set has user_permission override this in your sub-calassed model admin.
Use the exclude attribute in get_form where you can access request variable and you can set it dynamical depending on the user's permission or group.
Code:
admin.py:
class MyUserAdmin(UserAdmin):
list_display = ("username","first_name", "last_name", "email","is_active","is_staff","last_login","date_joined")
## Static overriding
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
def get_form(self, request, obj=None, **kwargs):
self.exclude = ("user_permissions")
## Dynamically overriding
self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff','is_superuser','groups')
form = super(MyUserAdmin,self).get_form(request, obj, **kwargs)
return form
The django admin is not designed for very fine grained control so their are no automated variables designed to allow this type of control.
If you need this type of control you're going to have to go it your own. You'll need to override the default admin templates. You'll probably want to use the permissions system to track what users are allowed to do.
Keep in mind the level of customization you're making. At some point working to far outside the intended purpose and limitations of the admin app will be more work than simply rolling your own more fine grained CRUD system.

extending satchmo user profile

I'm trying to extend the basic user registration form and profile included in satchmo store, but I'm in problems with that.
This what I've done:
Create a new app "extendedprofile"
Wrote a models.py that extends the satchmo_store.contact.models class and add the custom name fields.
wrote an admin.py that unregister the Contact class and register my newapp but this still showing me the default user profile form.
Maybe some one can show me the correct way to do this?
It sounds like you are doing it right, but it would help if you post your source. When I take this route, I treat the extended profile as an inline to the user model:
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
max_num = 1
fieldsets = [
('User Information', {'fields': ['street', 'street2', 'city', 'state', 'country', 'latitude', 'longitude']}),
('Site Information', {'fields': ['sites']}),
('User Account', {'fields': ['account_balance']}),
]
class NewUserAdmin(admin.ModelAdmin):
inlines = [UserProfileInline, ]
admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)
Hopefully that helps you.
Wrote a models.py that extends the
satchmo_store.contact.models class and
add the custom name fields.
wrote an admin.py that unregister the
Contact class and register my newapp
but this still showing me the default
user profile form.
This is related to overriding the django registration User class; the satchmo project creates a foreign key to the User class (as of 0.9.2). But what you want to do is create an extended profile class with new fields.
So, in this specific case you're going to need to do a few things to override the profile template that shows the Contact information:
Write your own models that subclass the Contact class (you already did this)
Write your own view(s) to use your new model class (base on satchmo_store.contact.views but use your own class instead of the Contact class)
Override the urlpatterns for the satchmo_store.contact application to point at your new view
Extend the satchmo_store.contact.forms.ExtendedContactInfoForm form class with entries for your editable form fields.
Modify the contact/view_profile.html template to include the custom name fields.
Then you may want to unregister the Contact class as above, admin.site.unregister(Contact), and only admini your new subclass.