As mentioned in the documentation, authenticated user's object is stored within user variable in templates. i need where django stored user variable in apps file thanks:
user = request.user
request['user'] = user #where is?
thanks for help
It's in the AuthenticationMiddleware.
The official doc mentioned it:
link:
AuthenticationMiddleware associates users with requests using
sessions.
link:
class AuthenticationMiddleware
Adds the user attribute, representing
the currently-logged-in user, to every incoming HttpRequest object.
See Authentication in Web requests.
source code(django.contrib.auth.middleware.py):
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
request.user = SimpleLazyObject(lambda: get_user(request))
Make sure you're using RequestContext. Otherwise user is not available in the templates.
Related
I have a Django app that gets it's data completely from apis. so I don't have to use database. Session data is stored on signed cookies. I tried to code a custom User model and a custom auth backend like on the docs, but I get the following error:
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'my_app.MyUser' that has not been installed
My settings.py:
AUTH_USER_MODEL = 'my_app.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
'my_app.backends.LoginAuthBackend',)
models.py:
class MyUser(object):
def save(self):
pass
objects = None
username = ""
Here, If a try use the AbstractUser from django instead of Object I got the following error: AttributeError: 'NoneType' object has no attribute '_meta' or the db table doesn't exit.
backends.py
class LoginAuthBackend(object):
def authenticate(self, username=None, password=None):
if username and password:
try:
response = my_auth_function(username, password)
if response.status_code == 200:
token = response.get('my_key')
user = MyUser()
return user
except MyCustomException:
return None
It's drives me crazy. Looks like Django that's not easy to use without a DB.
EDIT
After several of tries, a simple way to solve this is remove 'django.contrib.auth.backends.ModelBackend' from AUTHENTICATION_BACKENDS and AUTH_USER_MODEL from settings. The model continues basically the same way. works smoothly
The default set of authentication back-end processors is defined in the AUTHENTICATION_BACKENDS setting. See the Django documentation for Customizing authentication.
By default, AUTHENTICATION_BACKENDS is set to:
['django.contrib.auth.backends.ModelBackend']
That’s the basic authentication backend that checks the Django users database and queries the built-in permissions.
So, if you don't want the django.contrib.auth.backends.ModelBackend authentication method, remove that from the list. You'll probably want to find (or create) a different one and add that to the list.
I am working through the Pyramid authorization tutorial and I have noticed the pattern where
logged_in = request.authenticated_userid
is added to each view dictionary. Can it be avoided? I.e. is there a configuration which automatically ads user id to each view. Or is there a way to create a base, abstract view with the user id and inherit from it?
Part of the code from the tutorial:
#view_config(context='.models.Page', renderer='templates/view.pt', permission='view')
def view_page(context, request):
# not relevant code
return dict(page = context, content = content, edit_url = edit_url,
logged_in = request.authenticated_userid)
#view_config(name='add_page', context='.models.Wiki', renderer='templates/edit.pt',
permission='edit')
def add_page(context, request):
# not relevant code
return dict(page=page, save_url=save_url,
logged_in=request.authenticated_userid)
It's been awhile since I last looked, but I think logged_in in the samples is just an example to use to conditionally check if there is a logged on user or not. You could probably just as easily refer to request.authenticated_userid within any of your views or templates, too, and get the same behavior and not have to explicitly add a status to the response dict. The request object should be available to be referenced in your view templates, too.
Alternatively, I've used their cookbook to add a user object to the request to make a friendly request.user object that I can use to both check for logged in status where needed, plus get at my other user object details if I need to as well.
I have written a authorization backend class that implements a authenticate method and a get_user method as per the django docs. I've added
AUTHENTICATION_BACKENDS = ('src.lib.auth_backend.MyBackend',)
to my settings.py file. Through print statements I can see that my code is being run and that it is returning a user object of the class I defined with AUTH_USER_MODEL in my settings.py.
By the time I get the request object within my django-rest-framework has_object_permsion function, request.user is always set to AnonymousUser.
Am I missing a step?
I've tried this with and without django.contrib.auth.middleware.AuthenticationMiddleware installed and get the same outcome.
This failure is happening in the following unit test
def test_get_user(self):
client = APIClient() # rest_framework.test.APIClient
client.login(username='user1',password='user1Password')
res = client.get('/websvc/users/' + str(user.user_id) + '/') # request.user will be AnonymousUser
self.assertEqual(res.status_code, 200) # it will be 403, which is appropriate for AnonymousUser
A couple of things may be wrong.
Have you created the user, before runnign the test?
What returns client.login?
Show us the whole test, to tell you what's wrong.
In django, I use the authenticate() function to log users in. Using request.user, I can access the logged in user's information which is pulled from the users table. If I do request.user.id, I can get the user's id. In any template, on any request, I can do user.username to get the username.
Is there a way by which I can add values to the request.user variable so that I can use them throughout my application and in templates?
For example, I would like to have this: request.user.timezone set when the user logs in to the site; I should be able to access this variable in templates and in my views.
You can write a simple middleware:
class UserTZMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if request.user.is_authenticated():
request.user.timezone = evaluate_tz()
and then append this into MIDDLEWARE_CLASSES in your settings.py file:
MIDDLEWARE_CLASSES = (
....,
'myapp.UserTZMiddleware',
)
Would you like to let the user change it time-zone and force a specific time-zone ? I assume you would, if so you would like to keep the timezone configurable in your database. Therfore I would suggest you to make a UserProfile model which has one to one relations with the User Object.
You can do :
class UserProfile(models.Model):
user = models.OneToOneField(User)
time_zone = models.whateverField()
... add anything else you would like to extend your profile ...
On your templete you will be able to get the timezone by doing that :
{{ request.user.userprofile.time_zone }}
Simple and very clean.
If you would like to have an automatic creation of your userprofile whenever you save a User object, you can use signals for that.
Add the request context processor to your TEMPLATE_CONTEXT_PROCESSORS. This processor adds the request to the context, in your template you can do {{request}} or {{ request.user }}
see: https://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request
Use sessions, which are designed to keep variables in the context.
You should not change request.user as this is something that other applications will rely on and one that is populated by django's own auth machinery.
If you need to keep track of the timezone specifically, you should read up on the timezone support in django 1.4. In the documentation it provides examples for setting and managing timezones for users.
I am using Django 1.3 and python 2.7 .I am using Django admin app.What I want is when a superuser logs-in it should be shown admin/index.html with all models which is default behaviour but if any other user logs-in that is not superuser then it should be shown a totally different template with my data (like 'abc.html').What should I do to accomplish this?I guess I need to override some admin view to do this but have no idea?
Please help.If you want more information plz comment :)
I would create a middleware that checks if the user is a superuser or not. If the user is not supeuser you redirects him/her to the custom admin page instead of the default one.
class SuperUserMiddleware(object):
def process_request(self, request):
user = request.session.user
if not user.is_superuser:
return HttpResponseRedirect(NON_SUPERUSER_URL)
...
You create a modified AdminSite class definition with additional permission rules.
class SuperUserAdminSite( AdminSite ):
def has_permission(self, request):
return request.user.is_active and request.user.is_staff and request.user. is_superuser
Now you can create two AdminSite objects, one for ordinary users, one for super users.
You can have two paths in your URLs for the two admin sites.
Superusers can use both paths.
Ordinary users will only be able to use the ordinary user path in the URL.
https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#adminsite-objects
You have to change the view of the admin site. Django Documentation mention all in detail. Please check that https://docs.djangoproject.com/en/1.3/ref/contrib/admin/ if you have any error then please write back with some code details.