*I implemented Google's reCAPTCHA to my site with the django-recaptcha plugin. All works well. But when I validate the captcha and launch the form I get this error <urlopen error [Errno 11001] getaddrinfo failed>.
I would like to know how to interpret it and display a correct message to the user. Thanks in advance.*
here is the error:
URLError at /connexion/
<urlopen error [Errno 11001] getaddrinfo failed>
Request Method: POST
Request URL: http://127.0.0.1:8000/connexion/
Django Version: 4.1.2
Exception Type: URLError
Exception Value:
<urlopen error [Errno 11001] getaddrinfo failed>
Exception Location: C:\Python310\lib\urllib\request.py, line 1351, in do_open
Raised during: connexion.views.index_connexion
Python Executable: C:\Users\User\Documents\Travail\sms-chapchap-2022\env\Scripts\python.exe
Python Version: 3.10.4
Python Path:
['C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\src',
'C:\\Python310\\python310.zip',
'C:\\Python310\\DLLs',
'C:\\Python310\\lib',
'C:\\Python310',
'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env',
'C:\\Users\\User\\Documents\\Travail\\sms-chapchap-2022\\env\\lib\\site-packages']
Server time: Fri, 18 Nov 2022 16:19:54 +0000
Connexion.Views :
def index_connexion(request):
if request.user.is_authenticated:
return redirect('index_accueil')
if request.method == 'POST':
form = UserLoginForm(request.POST)
email = request.POST['email']
password = request.POST['password']
user = auth.authenticate(email=email, password=password)
if form.is_valid():
if user is not None:
if user.is_active:
auth.login(request, user)
return JsonResponse(True, safe=False)
else:
messages.error(request, 'Votre compte n\'est pas activé, consultez vos Email!!')
return JsonResponse(False, safe=False)
else:
messages.error(request, 'Email ou mot de passe invalide!')
return JsonResponse(False, safe=False)
else:
for key, error in list(form.errors.items()):
if key == 'captcha':
messages.error(request, "Vous devez réussir le test reCAPTCHA")
return JsonResponse(False, safe=False)
form = UserLoginForm()
return render(request, "connexion/connexion.html", {"connexion": 1, "form": form})
Connexion.Form:
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
class UserLoginForm(forms.Form):
captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox())
Related
I want to raise a custom exception that will:
return 503 status
not send Django admin email
I can do one of them, but not both together:
return 503 status: by using DRF APIException, or custom exception handler to handle response, but I won't get the exception type in the logging record to filter.
not send email: by checking exception type in a custom email handler class, but this returns 500.
Code example of 503 handling by adding a custom middleware:
class CustomMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
if isinstance(exception, MyCustomException):
return JsonResponse({"detail": "Error try later"}, status=503)
Code example to not send email:
class CustomAdminEmailHandler(AdminEmailHandler):
def emit(self, record):
...
reporter = ExceptionReporter(request, is_email=True, *exc_info)
if reporter.exc_type and issubclass(reporter.exc_type, MyCustomException):
return
Django sends email for any 5xx status response. When I use the middleware, I can't filter on reporter.exc_type since there's no exceptions trace (exc_info) anymore as the exception was handled in the process_exception.
Attach exc_info to request in CustomMiddleware and access it in CustomAdminEmailHandler.
class CustomMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
if isinstance(exception, MyCustomException):
# For CustomAdminEmailHandler # Add this
request.exc_info = sys.exc_info() # Add this
return JsonResponse({"detail": "Error try later"}, status=503)
class CustomAdminEmailHandler(log.AdminEmailHandler):
def emit(self, record):
request = record.request
if record.exc_info:
exc_info = record.exc_info
elif hasattr(request, 'exc_info'): # Add this
# From CustomMiddleware # Add this
exc_info = request.exc_info # Add this
else:
exc_info = (None, record.getMessage(), None)
reporter = ExceptionReporter(request, is_email=True, *exc_info)
if reporter.exc_type and issubclass(reporter.exc_type, MyCustomException):
return
I am trying to authenticate user with the system username but I am getting below error:
AttributeError at /
'str' object has no attribute '_meta'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.1.15
Exception Type: AttributeError
Exception Value:
'str' object has no attribute '_meta'
if getpass.getuser() != None:
login(request, getpass.getuser())
if user.user_type == "1":
print("Admin")
return HttpResponseRedirect(request, '/admin_home')
elif user.user_type == "2":
print("staff")
return HttpResponseRedirect(request, reverse("staff_home"))
else:
return HttpResponseRedirect(request, reverse("student_home"))
else:
# messages.error(request,"Invalid Login Details")
messages.error(
request, "You Do No Have Access To This Application")
return HttpResponseRedirect("/")
I'm trying to authenticate users using a custom MyUser model in Django version 2.0.4. However, when the code hits the check_password line in my custom backend module, I get this error:
Error
Traceback:
Traceback:
File "D:\Python\lib\site-packages\django\core\handlers\exception.py" in inner
35 response = get_response(request)
File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response
128 response = self.process_exception_by_middleware(e, request)
File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response
126 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "d:\Programs\Python\Django\test2\accounts\views.py" in login_user
52 user = authenticate(request=request, email=email, password=password)
File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in authenticate
70 user = _authenticate_with_backend(backend, backend_path, request, credentials)
File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in _authenticate_with_backend
116 return backend.authenticate(*args, **credentials)
File "d:\Programs\Python\Django\test2\accounts\backends.py" in authenticate
29 if MyUser.check_password(password):
Exception Type: TypeError at /accounts/login/
Exception Value: check_password() missing 1 required positional argument: 'raw_password'
Here is my custom backend from backends.py:
class EmailAuthenticationBackend(ModelBackend):
def authenticate(self, request, email=None, password=None):
MyUser = get_user_model()
try:
# Check the email/password and return a user
user = MyUser.objects.get(email=email)
# BUG
if MyUser.check_password(password):
return user
except MyUser.DoesNotExist:
return None
This is how the password come in. Login user view:
def login_user(request):
template_name = 'registration/login.html'
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(request=request, email=email, password=password)
While the error seems to be somewhat self explanatory, all the combos I've tried have failed. I've read the docs and searched other similar approach: nothing.
You should be calling that method on your instance, not the class.
if user.check_password(password):
Is it possible to add server response code to JsonResponse ? I need server to reply with 404 in some circumstances.
I have following view
def CreateOrAuth(request):
try:
username = request.POST.get("username")
queryset = User.objects.get(username=username)
except Exception as e:
return JsonResponse({'status': 'user with {} not exist'.format(username)})
And I want to add 404 server code here
Yes, you can. Just pass additional parameter status to JsonResponse:
return JsonResponse({'status': 'user with {} not exist'.format(username)}, status=404)
So I have login view, that works great and returns a token.
#csrf_exempt
def login(request):
if request.method == 'POST':
username = request.POST.get('username', None)
password = request.POST.get('password', None)
if username is not None and password is not None:
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
token, created = Token.objects.get_or_create(user=user)
if not created:
created = datetime.datetime.now()
return json_response({
'token': token.token,
'username': user.username
})
else:
return json_response({
'error': 'Invalid User'
}, status=400)
else:
return json_response({
'error': 'Invalid Username/Password'
}, status=400)
else:
return json_response({
'error': 'Invalid Data'
}, status=400)
elif request.method == 'OPTIONS':
return json_response({})
else:
return json_response({
'error': 'Invalid Method'
}, status=405)
The curl line is:
curl -X POST -d "username=root&password=myPassword" http://localhost:80/api/login/
and the result of that line is great:
{"username": "root", "token": "3dfdcd6b2abeb432131c734f82a737505ee3110d"}
After i login via that httprequest I would like to send GET request to the server to get a view.
My view example
from django.contrib.auth.middleware import get_user
def list_orders(request):
# check if authenticated else will exit
if not get_user(request).is_authenticated():
return ResponseError('authentication or permission failure')
...
...
this view always returns the not authenticated error :(
my http request exmple:
curl http://localhost:80/orders/ -d "csfrmiddletoken=3dfdcd6b2abeb432131c734f82a737505ee3110d"
returns:
{"status": "failed", "details": "authentication or permission failure"}
It is very importent to me to NOT use cookies ! so please dont suggest to add -b -c params to my curl line.
what should i do to use the token from my login view to get requests?
Thank you !
EDIT:
I solved that problem by 2 streps:
one i used another function to make sure i get a token:
def token_required(func):
def inner(request, *args, **kwargs):
if request.method == 'OPTIONS':
return func(request, *args, **kwargs)
auth_header = request.META.get('HTTP_AUTHORIZATION', None)
if auth_header is not None:
tokens = auth_header.split(' ')
if len(tokens) == 2 and tokens[0] == 'Token':
token = tokens[1]
try:
request.token = Token.objects.get(token=token)
return func(request, *args, **kwargs)
except Token.DoesNotExist:
return json_response({
'error': 'Token not found'
}, status=401)
return json_response({
'error': 'Invalid Header'
}, status=401)
return inner
second, i changed my httprequest:
curl -X GET http://127.0.0.1:80/orders/ -H 'Authorization: Token 3dfdcd6b2abeb432131c734f82a737505ee3110d'
BUT now even when Im logged to django over the web interface and I try to access to that link I get an error that I dont have valid header.
How can I make sure that both ways (web interface) and token via httprequest will work together?
The token returned by your login view is not a csrf token, so I am not sure why you have csfrmiddletoken in your request.
Secondly, the rest framework docs say that the token should be sent as a header, not as data in the request.
Try the following:
curl -X POST http://127.0.0.1:8000/orders/ -H 'Authorization: Token 3dfdcd6b2abeb432131c734f82a737505ee3110d'