Is a position of adding #csrf_exempt wrong? - python

I wanna connect my Swift app & Python Django Server in sending Image(I wanna send images from Swift app to Server) When I tried to do it,I got an error in Xcode
<div id="info">
<h2>Help</h2>
<p>Reason given for failure:</p>
<pre>
CSRF cookie not set.
</pre>
<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href="https://docs.djangoproject.com/en/1.10/ref/csrf/">Django's
CSRF mechanism</a> has not been used correctly. For POST forms, you need to
ensure:</p>
<ul>
<li>Your browser is accepting cookies.</li>
<li>The view function passes a <code>request</code> to the template's <code>render</code>
method.</li>
<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>
<li>The form has a valid CSRF token. After logging in in another browser
tab or hitting the back button after a login, you may need to reload the
page with the form, because the token is rotated after a login.</li>
</ul>
<p>You're seeing the help section of this page because you have <code>DEBUG =
True</code> in your Django settings file. Change that to <code>False</code>,
and only the initial error message will be displayed. </p>
<p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>
</div>
</body>
</html>
So,I think adding csrf decorators to Django Server is needed. I added it to my codes like
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST
from .forms import RegisterForm
from django.contrib.auth import authenticate, login
from .models import Post
from .forms import UserImageForm
from .models import ImageAndUser
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def upload_save(request):
photo_id = request.POST.get("p_id", "")
if (photo_id):
photo_obj = Post.objects.get(id=photo_id)
else:
photo_obj = Post()
files = request.FILES.getlist("files[]")
photo_obj.image = files[0]
# photo_obj.image2 = files[1]
# photo_obj.image3 = files[2]
photo_obj.save()
# return render(request, "registration/accounts/photo.html")
photos = Post.objects.all()
context = {
'photos': photos,
}
return render(request, 'registration/accounts/photo.html', context)
But when I did same thing in Swift app,totally same error happened.
I think the position of adding #csrf_exempt is wrong,but I do not know how to fix this.And maybe the position of #csrf_exempt is ok,another point is wrong,I do not know.
My sending url is written in Swift is http://localhost:8000/admin/accounts/post/42/change/ .
In Django side,MyAPP's urls.py is
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'^api/', include('UserToken.urls')),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^ResultJSON/', include('ResultJSON.urls')),
url(r'^api/1.0/', include('accounts.api_urls', namespace='api')),
url(r'^api/1.0/login/', include('accounts.apitoken_urls', namespace='apilogin')),
] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
accounts's urls.py is
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
from django.views.generic import TemplateView
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
url(r'^kenshinresults$', TemplateView.as_view(template_name='registration/accounts/kenshin_result.html'),
name='kenshinresults'),
url(r'^tcresults$', views.tc,name='tcresults'),
]
Please tell me what is wrong.

/admin/accounts/post/42/change/ is a URL in the Django admin. Your upload_save view which uses the csrf_exempt decorator is hooked up to /accounts/upload_save/ in your URL config.

Related

I am getting a 404 error when using login_required

I'm new to Django and I'm trying to make a learning log website.
When I try to restrict my topics with login_required function I get a 404 error.
Here is my code:
from django.contrib.auth.decorators import login_required
#login_required(login_url='/users/login/')
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
I get this error whenever I use the decorator in my code:
Using the URLconf defined in learning_log.urls, Django tried these URL
patterns, in this order:
admin/
users/ login [name='login']
users/ logout [name='logout']
users/ registration [name='register']
learning_logs/¨
The current path, users/login/, didn't match any of these.
The url works fine but when I use the decorator it breaks.
that means you have not defined the django builtin login in your url to solve it you can just past that inside you urls.py
##urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('users/login/', auth_views.login, name='login'),
path('users/logout/', auth_views.logout, name='logout'),
path('admin/', admin.site.urls),
]
if you have already done that you need to do the following in views
##views.py
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
#login_required(login_url=reverse_lazy("login"))
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
It looks like your users urls don't have trailing slashes. Make sure that the URLS in your users/urls.py end with slashes. For example:
urlpatterns = [
url(r'^login/$', LoginView.as_view(), name='login')
]

Can't display new html page with href from homepage

The only examples I find. are related to issues with login page and iteration to other pages but not in the way I have the problem, so here is the issue I have to deal with -
I want to display a form for creating an account with multiple steps, using modals, when a user access the button "subscribe"
on my homepage.html I have this:
<a onClick="window.location.href='account'" target="_blank">
<input type="submit" value="account">
</a> `
...which is supposed to go to a new account.html page, in the same folder as my homepage.html
in my app's urls.py, where the apps' name is homepage I have:
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
url(r'^account$', views.account, name='account'),
)
and in my views I have:
from django.shortcuts import render
from homepage.models import Email
def tmp(request):
latest_email_list = Email.objects.order_by('-pub_date')[:0]
context = {'latest_email_list': latest_email_list}
return render(request, 'home_page/homepage.html', context)
def homepage(request):
return render(request, 'home_page/homepage.html')
def account(request):
return render(request, 'home_page/account.html')`
when I click on the button I get
Not Found
The requested URL /account was not found on this server.
I am a complete beginner in django and python so I really haven't yet wrapped my mind on how to work properly with the urls, views, and models together but I assume I have something wrongly defined in my views
would be grate if someone could help me setting this up,
Thanks
I only want to thank all those who took time to check my question and tried to give a solution.
I think it was my mistake that I did not post the code I have in my main urls.py file, so here it is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', include('home_page.urls', namespace="homepage")),
url(r'^admin/', include(admin.site.urls)),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Apparently, the problem was in that first prefix of the first url in the list:
I changed
url(r'^$'
for
url(r''
and now it calls whatever links I provide in my html pages.
Thanks all again

Custom url for django admin

For an extra little bit of security I want to change the default django admin url to the custom one, e.g. change mysite.com/admin/ to mysite.com/mysecretadmin/ so that admin is completely unaccessible via default url.
I tried some solutions from the internet, for example I changed urls.py like this:
from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('api.views',
...,
...,
url(r'^secret-admin-url/', include(admin.site.urls)),
)
Nothing worked for me, sadly. Does anyone know the solution? I use django 1.5.4.
Refer to the section 'Hooking AdminSite instances into your URLconf' in the url
below
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-to-urlconf
For those who find this question in recent times. Based on the Django 3.1 docs:
register the default AdminSite instance django.contrib.admin.site at the URL /admin/:
# main project urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path("admin/", admin.site.urls),
]
you can simply change the admin/ url to anything you wish:
urlpatterns = [
path("my_custom_url/", admin.site.urls),
]
If you do not want to use the default page /admin you can add a secret key to admin. So in urls.py
urlpatterns = [
path('admin_eTiOmEthelInEwathbace/', admin.site.urls,),
]
If in your template you have a link
Admin
then this will reference to the above site with url: http://127.0.0.1:8000/admin_eTiOmEthelInEwathbace/
Now you do not want to publish this secret_key, therefore get it from an environment variable with for example decouple, so urls.py then becomes
from decouple import config
SECRET_ADMIN = config('SECRET_ADMIN')
urlpatterns = [
path(f'admin_{SECRET_ADMIN}/', admin.site.urls,),
]
If you want to prevent brute force or dictionary attack and your admin login page not accessible for unauthorized user,normal user. please follow this step:
First install django admin honeypot and signal
pip install django-admin-honeypot(inastall in settings.py)
pip install django-honeypot-signals(inastall in settings.py)
override this .txt file(because future tag is deprecated):
templates/honeypot_signals/notification.txt:
{% load i18n %}
{% blocktrans with site_name=site.name %}
{% endblocktrans %}
Invalid login attempt from your duplicate ADMIN panel..
• Review entry at http://{{ site.domain }}{% url "admin:admin_honeypot_loginattempt_change" object.id %}
Username: {{ object.username }}
IP: {{ object.ip_address }}
Timestamp: {{ object.timestamp }}
django-admin-honeypot make a fake admin login page and django honeypot signal send email to admin with credentials if any person try to access your fake admin login page.
How to access main admin login page?:
pip install django-decorator-include
Your main urls.py:
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from . import settings
from decorator_include import decorator_include
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import PermissionDenied
from django.core.mail.message import EmailMessage
from datetime import datetime
from django.views.generic.base import RedirectView
def only_user():
def check(user):
if user.is_authenticated and user.is_superuser or user.is_staff:
return True
time = datetime.now()
message = f'----------------------------------\nName: {user.username}\nEmail: {user.email}\nTime: {time}.\n----------------------------------\n • {user.username} is not a staff user or admin.For some security reasons..Please block this user from your admin panel(Blacklist).'
email = EmailMessage(
f'📛📛📛Alert!! {user.username} is try to accessing your admin panel!!',
message,
settings.EMAIL_HOST_USER,
[settings.EMAIL_HOST_USER],
)
email.fail_silently = False
email.send()
raise PermissionDenied
return user_passes_test(check)
urlpatterns = [
path('', include('product.urls')),
#This is all fake admin urls...
path('admin/', include('admin_honeypot.urls',
namespace='admin_honeypot')),
path('site/admin/',RedirectView.as_view(url='/admin')),
path('user/admin/',RedirectView.as_view(url='/admin')),
path('secure/admin/',RedirectView.as_view(url='/admin')),
path('mysite/admin/',RedirectView.as_view(url='/admin')),
path('admin/secure',RedirectView.as_view(url='/admin')),
path('real/admin/',RedirectView.as_view(url='/admin')),
#This is real admin login page url
path('custom_url/',
decorator_include([login_required, only_user()],
admin.site.urls)),
]
For this way you can not access directly your admin login page.. first you need to login your website and then accessible your admin panel..
How to protect website's login page from the attackers?:
- Use django defender (https://django-defender.readthedocs.io/en/latest/)
---------------------OR-------------------------
- Use google hidden(ReCaptchaV2Invisible) recaptcha field
(https://pypi.org/project/django-recaptcha/)
If any unauthorized users terrible activity detected.You block their IP address or username by using this django package:
pip install django-blacklist
Read docs : django-blacklist
•sorry for my English

Login page displayed even if the user is already logged in

I use Django's authentication view django.contrib.auth.views.login to log in my users.
urls.py
urlpatterns = patterns('',
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
)
Here is the doc regarding this functionality.
My problem: The login page is displayed even if the user is already connected.
For django 2.x, you can simply do this
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]
You can just use the contrib login view with your own modifications in your own view. Just change the login url to point to your own view, then check if they are already logged in:
views.py
from django.contrib.auth.views import login as contrib_login
def login(request):
if request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
return contrib_login(request)

custom views within Djangocms?

I haven't found a satisfactory way of doing this: I have a djangocms setup that is working fine. But I need to add content from a table outside the CMS to my homepage and render that content on the template. I can do this, but editing the urls.py within CMS to use my views like so...
url(r'^', 'myapp.views.slideshow_info'),
... excludes any content from CMS. I understand that I just get my custom views to accommodate what CMS' views is doing, but how do I achieve this?
at the moment my app's views says:
from myapp.models import model1, model2
def slideshow_info(request):
return render_to_response('index.html', {'slideshow_list' : model1.objects.all()})
Many thanks
You can hook a custom app instance to any Django-CMS page. Here's the documentation on how to do so: http://docs.django-cms.org/en/2.1.3/extending_cms/app_integration.html#app-hooks You shouldn't need to alter the base url patterns to specifically re-route / to your view.
Before custom app-hooks were available, I would accomplish what you're trying to do with template tags.
Hope that helps you out.
Followup
Ok, in a recently completed site, I had to hook an app titled "portfolio" to display images on the home page of a Django-CMS site.
Here are the relevant portions of the code:
#portfolio/cms_app.py
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class PortfolioAppHook(CMSApp):
name = _('Portfolio')
urls = ['portfolio.urls']
apphook_pool.register(PortfolioAppHook)
#portfolio/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('portfolio.views',
url(r'^(?P<slug>[-\w]+)/$', 'project_detail', name='project_detail'),
url(r'^$', 'portfolio_index', name='portfolio_index'),
)
#portfolio/views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from portfolio.models import Project
def portfolio_index(request):
project_objects = Project.for_public if request.user.is_anonymous() \
else Project.objects
projects = project_objects.all().select_related(depth=1)
return render('portfolio/index.html',
{'projects' : projects}, request)
def project_detail(request, slug):
project = get_object_or_404(Project, slug=slug)
if not project.public and request.user.is_anonymous():
return HttpResponseRedirect('/?login=true')
return render('portfolio/project_detail.html',
{'project' : project}, request)
#urls.py (base urls)
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from views import login_user, logout_user
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^login/$', login_user, name='login_user'),
url(r'^logout/$', logout_user, name='logout_user'),
(r'^', include('sorl.thumbnail.urls')),
(r'^', include('cms.urls')),
)
if settings.SERVE_STATIC_MEDIA:
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL.lstrip('/'), include('appmedia.urls')),
) + urlpatterns
As you can see from this working example, I haven't altered my base URLs to accommodate the home page view, rather I've provided the URLs for my Portfolio app to Django-CMS through cms_app.py
Hope that gets you going.

Categories