Django 1.5 custom user model plus admin.autodiscover() breaks app - python

I have a custom user model (it's actually named User as I didn't see any need to name it otherwise) in my Django 1.5c1 project (currently running on the latest from the Django 1.5 branch on github). AUTH_USER_MODEL is defined in my settings properly, so the auth module works correctly and I can log in etc. fine.
However, with the custom user module enabled, the admin site doesn't work. When I add admin.autodiscover() to my urls.py, every page on the site (not just admin pages) throws a NotRegistered exception and says The model User is not registered. The traceback shows that admin.autodiscover() is trying to call admin.site.unregister(User), apparently before it has registered that model.
I tried renaming my user model to something other than User, but it didn't seem to work. I also tried creating my own admin.py for that app, and then I tried manually registering my custom User model with the custom UserAdmin model specified in admin.py before admin.autodiscover() ran, but that actually caused a separate exception saying that User was already registered.
What should I try next in order to get admin.autodiscover() working?

It looks like you need to jump through a few extra hoops if you want your custom User model to work with the admin. From the documentation:
...your User model must define some additional attributes and methods.
These methods allow the admin to control access of the User to admin
content:
class models.CustomUser
is_staff True if the user is allowed to have access to the admin site.
is_active True if the user account is currently active.
has_perm(perm, obj=None) True if the user has the named
permission.
has_module_perms(app_label) True if the user has perm
to access models in the given app.

I set up a brand new empty project with a custom user model and attempted to recreate the situation, which led to a diagnosis: we had added the django-usertools package to the project, which has not been updated for Django 1.5 and apparently conflicts with custom user models. Removing that package from the installed apps list in settings resolved the issue.

Related

How to get current app when user is in Django admin?

I need to get from which admin page(app) current request is from in django admin.
Currently request.resolver_match.app_name only returns "admin" which is not what I want.
I have noticed that my app name is in 'view_name' and 'url_name' but is it reliable to parse these variables to access current app name?
Django 1.11 LTS
EDIT: For example, when a user enters admin page for my course app with the above method I still only get 'admin' in my request which should be 'course' not 'admin'. My ultimate goal is to hide some of my app model fields in admin page based on user group.
Thanks
From a ModelAdmin you have access to the model via self.model. In a ModelAdmin method you can thus get the app name using self.model._meta.app_label.
I you need to access it from the template rather than the ModelAdmin, self.model._meta is passed to the context as opts. You can thus access it via {% if opts.app_label == "some_app" %}.
you can simply do this by tracking requested.user i.e who is logged in currently.
something like this
if(requested.user=='admin'):
(show all fields)
else:
(show mentioned fields)
here you are restricting access of your's models fields based on currently logged in user

Created User from django custom admin page can't login

I have a custom admin page:
class StripeAdminSite(admin.AdminSite):
...
pass
I have registered django.contrib.auth.models to this admin site:
stripe_admin_site = StripeAdminSite(name='Stripe')
stripe_admin_site.register(User)
Now User show up in the admin page, it also let me create users (as stuff), but after creation when I try to log in using them to dashboard it does not allow me to do that.
After switching back to default admin site, I got this written in my old users password fields:
Invalid password format or unknown hashing algorithm.
Now what can be done?
More/Extra information: How to bring default add user page at django custom admin page?
The problem is that you did not register the User model with Django's UserAdmin. This means that the password was not hashed properly when the user was created, so they can't log in.
To use Django's UserAdmin, change your code as follows.
stripe_admin_site = StripeAdminSite(name='Stripe')
from django.contrib.auth.admin import UserAdmin
stripe_admin_site.register(User, UserAdmin)
Once you have done this, you will not get this problem for new users that you add in future.
Use the change password link to reset the password for any existing users, and then they should be able to log in.

Read only usernames in django admin site

I'm using django and its built in admin site for the project I'm working on. (Python 3.4, django 1.7)
For the current project I'm working on I require usernames to be fixed after object creation. I have made a small test project, which literally contains one app, and that app only contains this admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class MyAdmin(UserAdmin):
def get_readonly_fields(self,request, obj=None):
ro_fields = list(super().get_readonly_fields(request, obj))
if obj is not None:
ro_fields.append('username')
return ro_fields
admin.site.unregister(User)
admin.site.register(User, MyAdmin)
As expected, the Username can be set in the Add page and is Read Only in the change page. However, I cannot save when on the change page, I receive the message "please correct the errors below" but no field is highlighted. Can anyone suggest a way to work round this problem?
EDIT: as a diferent option I attempted to replace the username with a widget that didn't allow input - no luck there either

How to write tests that account for custom User model in Django?

TL;DR:
I don't wanna use #skipIfCustomUser What can I do?
Django allows a custom user model to be defined in settings.py, and says we should use get_user_model() to reference the current (swapped) User model, in the docs.
Forthermore, the docs are kind to say:
If you are writing an application that interacts with the User model, you must take some precautions ...
To ensure that your test suite will pass in any project configuration, django.contrib.auth.tests.utils defines a #skipIfCustomUser decorator. This decorator will cause a test case to be skipped ...
To me it seems reasonable to expect more and more Django projects have a custom user model, and so I'd like to be able to test my app agains these projects too.
But how can I do that?
For reference, here is where it all fails:
def setUp(self):
from django.contrib.auth import get_user_model
User = get_user_model()
user = User.objects.create_user(
'test_username',
'test_username#example.com',
'da_password') # BAM!
That last line will fail if user model does not define a username field. That is the case for CustomUser example from Django's own tests.

Connect user login views, form with pre-exist user which is created by Django admin

I have install Django admin & created some active user & group by admin page.
I need to do login form & views, which will check if user is valid or not do task in the basis of permission.
I have tried following steps.(for reference)
Copied admin login.html for testing & paste it foo_project/templates/registration/login.html
Added in urls.py
from django.contrib.auth.views import login
url(r'^login/', login),
Now by running 127.0.0.1:8080/login
When I am entering valid user-name & password its trying to open /accounts/profile/ & it's not found in urls.py. And if I am entering invalid username or password its doing nothing.
So I simple need to link a page if login successful(user created by admin) & check which type of permission & group he is.Admin created auth_user table in my db.sqlite3
I am new to Django & using version 1.6.
I read document & tried built-in login() in views.py. Got unsuccess.
Is there any built-in for above need. Please describe in depth if possible.
In settings.py create this entry:
LOGIN_REDIRECT_URL = "your_redirect_url"
The user will be redirected to this page after login. Then on the url you will create which will respond to "your_redirect_url" (and should be defined somewhere in your urls.py), you can check the permissions, or groups. For more help about checking permissions, groups, you can find it here.
The login_required decorator can be really useful on implementing your view for your "redirect_url", because you don't want anonymous users accessing to this part of the site, right?

Categories