I am putting together a Django app that has forms on the site, but I am rendering those forms manually (i.e. actually typing out each field and submitting them with AJAX).
How can I integrate Recaptcha into my forms? Thanks for the help!
recaptcha-client doesn't work with python3. I ended up using django-recaptcha (https://pypi.python.org/pypi/django-recaptcha/1.0). The brief documentation explains how to implement recaptcha using the formfield 'ReCaptchaField', but you can just use the submit function from captcha.client like this:
import captcha.client
[...]
recaptcha_response = captcha.client.submit(
request.POST.get('recaptcha_challenge_field'),
request.POST.get('recaptcha_response_field'),
'[[privatekey]]',
request.META['REMOTE_ADDR'],)
Then you check whether recaptcha_response.is_valid.
No need to add recaptcha to your INSTALLED_APPS or anything.
I am just using this python client for recaptcha:
http://pypi.python.org/pypi/recaptcha-client
then my view looks like this:
captcha_key = get_config('RECAPTCHA_PUB_KEY',None)
recaptcha_challenge_field = request.POST.get('recaptcha_challenge_field', None)
recaptcha_response_field = request.POST.get('recaptcha_response_field', None)
check_captcha = captcha.submit(recaptcha_challenge_field, recaptcha_response_field, settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
if check_captcha.is_valid is False:
log.info('captcha_error : %s' % check_captcha.error_code)
return {'TEMPLATE':template_name,'captcha_error': True,'register_form': f,'captcha_key':captcha_key ,'next':redirect_to}
Related
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.
For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"
My url pattern for this is:
url(r'^<slug:url>', views.item, name='products')
with the view:
def item(request, url=""):
products = product.objects.get(url=url)
return render(request, 'shop\product.html', {'products', products})
As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?
If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.
Also I'm on django 1.11.7 for this project.
The url pattern you are trying to use (slug:url) is only valid in Django 2.
If you are on Django 1.11 then you need to use a regular expression - something like this:
url(r'^?P<url>[\w-]+', views.item, name='products')
Always make sure you're looking at the documentation for your version of Django ;-).
Please change url pattern to:
url(r'^?P<url>[\w-]+', views.item, name='products')
I have been looking online for localization of error messages and labels of pyramid forms but so far without any luck. I have worked on both pyramid_simpleform and pyramid_deform. Has anyone worked on something similiar. The docs are not much of help.
The example given on this page does not work for me.
I also tried the docs of pyramid_deform and pyramid_simpleform.
I do not care which form library I use. I want something that has straightforward support for localization.
This is what has worked for me.
from pyramid.i18n import get_locale_name
from pyramid_simpleform import Form,State
from formencode import api as formencode_api
def includeme(config):
config.scan(__name__)
config.add_route('login', '/login')
#view_config(route_name='login',renderer='website/login.mak')
def login(request):
formencode_api.set_stdtranslation(languages=[get_locale_name(request)])
form = Form(request,
defaults=dict(request.params),
schema=MySchema,
state=State()
)
form.state._ = ''
This is my code :
class MobileMiddleware(object):
def process_request(self, request):
if request.path.startswith('/core/mypage/'):
request.path='/core/mypage/?key=value'
print request.path,'aaaa'
I want to add a param key when the page url is /core/mypage/,
and the url of the web browser would be changed to http:www.ss.com/core/mypage/?key=value
However, the url in the browser is not changed.
What can I do?
For googlers - I tested with request.path_info. If you want to change URL in middlware, change request.path_info in process_request.
request.path_info = <change request.path_info>
Please Note that I do not suggest or forbid to use this. I'm just saying if you want to change urls, this is the way you can.
The problem is that HttpRequest.path is a plain attribute. Changing it does not make any new instructions for the browser. You're probably looking for the redirect method which will actually force the browser to go somewhere else.
Try This
return HttpResponseRedirect('/core/mypage/?key=value')
The request.path_info did not change the url in the browser address bar for me but this redirect did:
from django.shortcuts import redirect
class DomainRedirectMiddleware(object):
def process_request(self, request):
if request.path.startswith('/core/mypage/') and not request.GET:
return redirect('/core/mypage/?key=value') # works!
#request.path_info = '/core/mypage/?key=value' # works, but does not change url in browser address bar
Django also provides a "Redirects App" since Django 1.3, which includes the following middleware: 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' . See the redirects app documentation, it lets you create redirects from the admin interface.
I tried the same redirect using the app and it worked. Cheers!
I haven't tested this, but try something like request.GET["key"] = val
Edit: or maybe use request.path_info instead of request.path
I am looking into adding RSS feeds to one of my Django apps and I would like to be able to have them be authenticated.
I want to use the new syndication framework in Django 1.2. I've read the docs on how to do this and have the basic feeds setup.
I am new to authenticating feeds, so I am not sure what the best approach to take is or what my options really are.
Each user has a unique sub domain and I would like the URL structure to look something like this: http://mysubdomain.mysite.com/myapp/rss/ if possible.
I don't want the feeds to be publicly available, is it possible to use the users username and password for the authentication? Have you found that most feed readers support this? If it's not possible to authenticate for each user, should I try to use a uuid to give them a unique url or is that not secure enough?
As you can probably tell I am not sure what direction to take with this, so any advice on the best way to do this would be very much appreciated.
Thanks
This is an old thread, but I recently encountered the same question. I solved it by overloading the __call__ method of the Feed object:
from django.http import HttpResponse
class ArticleFeed(Feed):
"snip [standard definitions of title, link, methods...]"
def __call__(self,request,*args,**kwargs):
if not request.user.is_authenticated():
return HttpResponse(status=401)
else:
return super().__call__(request,*args,**kwargs)
Have you tried wrapping the syndication view django.contrib.syndication.views.feed into a view that requires login? RSS feeds should normally be fetched over HTTP, so this should work!
# Import Django's standard feed view.
from django.contrib.auth.decorators import login_required
from django.django.contrib.syndication.views import feed
# Wrap it in a new feed view that requires authentication!
private_feed = login_required(feed)
Caveat: I've never tried this!
Edit!
To be safe with RSS readers that don't support redirection, return a HTTP 401 status code with the following:
authentication_url = '/accounts/login'
def feed_safe_login_required ( view ):
def _ ( request, *args, **kwargs ):
if not request.user.is_authenticated:
return HttpResponseNotAuthorized, authentication_url
return _
feed = feed_safe_login_required(django.contrib.syndication.views.feed)
Where HttpResponseNotAuthorized is as defined in this django snippet.
I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/controlpanel/login')
Question is: how can I run this code at the beginning of every view, without repeating it every time?
If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization:
include("redirect_if_not_logged_in.inc.php");
The solutions I found was:
inclusion tags - doesn't do,
because I can't redirect anywhere
from there
custom function -
also doesn't do, because of the same
reason.
The task seems trivial, but I can't find a solution. I would be very grateful for any help.
Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.
BTW, why don't you use the built-in auth? You can use it with custom authentication backends...
I found the answer I was looking for. Function decorators allow to run a peace of code at the beginning of a function.
You must define a decorator function
def login_please_decorator(view_func):
"""
Redirect if admin was not logged in
"""
def _decorated(request, *args, **kwargs):
#Check authorization
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
return view_func(request,*args, **kwargs);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/cp/login?ret=' + request.path);
return _decorated
And decorate a view using this function name:
#login_please_decorator
def some view(request):
# do something ...
# ...
Ludwik Trammer, bugspy.net, thank you for your help.
Function decorators comes to mind
Take a look at the User authentication page here http://docs.djangoproject.com/en/dev/topics/auth/
Read on to "The login_required decorator".
from django.contrib.auth.decorators import login_required
#login_required
def my_view(request):
...
You can setup where the user is to be redirected if not authenticated via the setting "settings.LOGIN_URL".
At the page there is also an example for a special authentication template you can style to anything you like!