I have a weird issue when I try to save a new user through the admin interface.
I get a 403 HTTP status code error.
I've changed nothing in the auth application.
Here are my middlewares:
MIDDLEWARE_CLASSES = (
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
#'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'django.middleware.cache.FetchFromCacheMiddleware',
)
I've no idea where to look, or either have any idea of what could provocate this. Any clue is welcome.
Your user probably has not permissions to add new users. It's a normal behaviour to return 403 code in this case. View the doc, please: https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.permission_required.
And (in this case) your user can have permission to delete users because it's the decoupled permissions.
You can view permissions of the user it: http://yoursite.com/admin/auth/user/{user_id}/ ( from superuser or user that can view permissions of other users).
Update. The author of the question found the decision: the situation was because of Apache settings (switching mod_security off fixed the problem). Unfortunately I have not deep knowledge about the module and I can't give more detailed information.
Related
I am trying to use oauth for authentication and authorization in a project. I want to use the client credentials grant type as this project is about a middleware/api that will be consumed by a client application. I have created one corresponding client_id and client_secret. The token generation is working, however as soon as I am trying to do a request with the generated token against the api endpoint i am being forwarded to the accounts/login page by django:
<td>http://127.0.0.1:8000/accounts/login/?next=/api/mp/</td>
my settings are:
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]
AUTHENTICATION_BACKENDS = (
'oauth2_provider.backends.OAuth2Backend',)
And this the top of my only function in my views:
#csrf_exempt
#require_http_methods(['POST', 'GET'])
#login_required()
def getUserContext(request):
I am not really understanding where this additional authentication is coming from or resp. how i can tell django to only use oauth for the view.
Found the answer very short after posting the questions. However, had been following a howto that stated #login_required to be used. However, the correct decortator to be used is:
#protected_resource()
I added django-user-language-middleware package but it only change language when I manually change it at admin or DB.
When I use set_language link, it doesn't update language.
Before adding that middleware, it was working without any problem but I need to save language for user.
The middleware order:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'user_language_middleware.UserLanguageMiddleware',
...
}
Wrote a simple custom view that change language of current user
I am working on a dJango web and follow the tutorial to protect it against CSRF, I did something and not sure is it write now install or not, how can I see or check it?
From the docs, to enable CSRF protection for your views, follow these steps:
Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES in your settings.py. (It should come before any view middleware that assume that CSRF attacks have been dealt with.)
In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL, e.g.:
<form action="." method="post">{% csrf_token %}
In the corresponding view functions, ensure that the 'django.core.context_processors.csrf' context processor is being used.
Following these steps will check that CSRF tokens are included properly.
By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
See the Docs for more info.
Check the MIDDLEWARE_CLASSES tuple in settings.py contains this
'django.middleware.csrf.CsrfViewMiddleware',
If this is there in the tuple , then csrf is installed.
Some like this:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
I am new to Django.
I am trying to run an app and I need to add a new user to admin. The server is running. When I enter the info fir the new user and hit "save" I get the error below. I am using django-trunk.
MessageFailure at /admin/auth/user/add/
You cannot add messages without installing
django.contrib.messages.middleware.MessageMiddleware
Request Method: POST
Request URL: http://localhost:8000/admin/auth/user/add/
Django Version: 1.6.dev20130403090717
Exception Type: MessageFailure
Exception Value: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
Any ideas of what might be happening?
For me the problem was specific to unit testing. It turns out that some middleware won't work in some kinds of unit tests, more info here:
https://code.djangoproject.com/ticket/17971
and here:
Why don't my Django unittests know that MessageMiddleware is installed?
My solution was to just mock out the messages framework for those tests, there may be better solutions (the django test client?)
Check if you have django.contrib.messages in INSTALLED_APPS and django.contrib.messages.middleware.MessageMiddleware in MIDDLEWARE_CLASSES.
If you are running normal django code, you should add
django.contrib.messages.middleware.MessageMiddleware to your middlewares as others have suggested
If you are running a test case and using request factory then as #hwjp answered above, it's a bug (that won't be fixed). The request factory doesn't call the middlewares and developers don't intend to change this behaviour.
There is however a simple solution.
in your test settings file (i.e settings/test.py) add the following line
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
in your test code you can write code like this
request = RequestFactory().get("/")
# Add support django messaging framework
request._messages = messages.storage.default_storage(request)
and that's it. Passing this request object to any code that uses django messages will work without a problem.
Check if it is
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
instead of
MIDDLEWARE = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Tuple name should be MIDDLEWARE_CLASSES
MIDDLEWARE_CLASSES depreciated https://docs.djangoproject.com/en/2.1/releases/1.10/#id3
2018 update
In django 2.0+ name in settings was changed.
Right now use MIDDLEWARE instead of MIDDLEWARE_CLASSES name of list in settings!
If the request is needed in tests, it can be mocked as suggested by #Ramast.
I found the solution mentioned in the bug ticket (closed, won't fix) to be helpful.
from django.contrib.messages.storage.fallback import FallbackStorage
from django.test import RequestFactory
def dummy_request():
"""Dummy request for testing purposes with message support."""
request = RequestFactory().get('/')
# Add support django messaging framework
setattr(request, 'session', 'session')
setattr(request, '_messages', FallbackStorage(request))
return request
Probably you put a wrong WSGI_request when usually called request as a parameter to add_message() method
I met the same error.
You have to notice the order of middleware in MIDDLEWARE_CLASSES.
Insert the corresponding middleware in the final.Like this,
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Note the order arrangement.
If your issue is simulating these middlewares during unit testing, you can spoof this by writing a couple of little helpers:
def add_session_to_request(request: HttpRequest) -> HttpRequest:
"""Adds session support to a RequestFactory generated request."""
middleware = SessionMiddleware(get_response=lambda request: None)
middleware.process_request(request)
request.session.save()
return request
def add_messages_to_request(request: HttpRequest) -> HttpRequest:
"""Adds message/alert support to a RequestFactory generated request."""
request._messages = FallbackStorage(request)
return request
You can then call these in your test function at the point your request needs to have the middleware bound and just pass in the request you're using, which should keep your tests happy. :)
# To suppress the errors raised when triggering .messages through APIRequestFactory(),
# we need to bind both a session and messages storage on the fly
add_session_to_request(replacement_request)
add_messages_to_request(replacement_request)
I am with some trouble in Django...
After login I am losing auth session for some pages.
If I access "accounts/login/","accounts/logout/",""accounts/register/" the session always will be there, but if I access different page I cant access the user variable.
This is strange because I am using the same "base.html" for all pages and inside has the logic "if user.is_authenticated", how I said this condition is true just when I access pages that have "accounts" in the URL.
in the settings file I enabled theses three middleware:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
Thanks
Just a guess here: are you including RequestContext in your context in the views that you cannot access user?
In other words, if you call generic views the RequestContext is automatically included but if you are using render_to_response() then you need to call it like this:
return render_to_response('template_name',
{ your context dict },
context_instance=RequestContext(request))