Django Rest Auth - python

I'm trying to authenticate a client using Django Rest Framework by an admin user.
In the urls.py file where I specified the path to get the login form I write:
urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include("quotesapi.api.urls")),
path('api-auth/', include("rest_framework.urls"))
]
Here there is the setting.py file (Installed APPS only):
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'quotesapi'
]
And Im trying to do a POST request with the credential from a python client using requests but I receive a 403 forbidden error
This is the client:
import requests
def client():
# payload = dict(key1='admin', key2='admin')
URL = 'http://127.0.0.1:8000/api-auth/login/'
response = requests.post(URL, json={"username": "myadmin", "password":"mypass"})
print("Staus code:", response.status_code)
print(response.text)
if __name__ == "__main__":
client()

Related

Show the main page in the django multi-tenant

I am studing the djanto multi-tenant package (https://github.com/django-tenants/django-tenants).
When i try to access the main page (landing page) at http://127.0.0.1:8000/, I got the following message:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Raised by: core.views.home
No tenant for hostname "127.0.0.1"
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to
False, and Django will display a standard 404 page.
How do I get the landing page to show correctly?
URL FILE
from core.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
THE VIEW OF LANDINGPAGE
from django.shortcuts import render
def home(request):
return render(request, 'core/index.html')
PARTIAL SETTINGS FILES
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
SHARED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_tenants',
'customer',
'core', //landing page
]
TENANT_APPS = [
# The following Django contrib apps must be in TENANT_APPS
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
# your tenant-specific apps
'myclientapp',
]
INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS))
Thank you very much!
The issue there is with the Django Tenants middleware. By default, django_tenants will show a Page 404 error if you go to a tenant that does not exist. You can change this behavior by over-modifying the middleware and having your own local copy or (the easiest solution) you can just provide a default case by adding SHOW_PUBLIC_IF_NO_TENANT_FOUND = True in your project's settings.py file. This will route to the public schema hence other url routes will work as they should.

Page not found (404) in Django view

I am trying to wire up a view based on the Django tutorial (1.8), and am for some reason not getting a basic url to work:
Page not found (404)
Settings
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'events',
)
In the main folder, I have these_events/these_events/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^/', include('events.urls')),
]
In the events app, I have these_events/events/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^$", views.search_db, name='search-db')
]
these_events/events/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def search_db(request):
return HttpResponse("hello, world")
This has me befuddled as I followed the example, and this is the way I remember using Django in the past.
In these_events/these_events/urls.py
try changing
url(r'^/', include('events.urls')),
to
url(r'', include('events.urls')),

ImproperlyConfigured error with include to other url file

I'm using django-cookiecutter to bootstrap my project which will include api paths. Following the steps in Two Scoops of Django 1.11 to configure my urls to follow a similar pattern to this:
api/foo_app/ # GET, POST
api/foo_app/:uuid/ # GET, PUT, DELETE
api/bar_app/ # GET, POST
api/bar_app/:uuid/ # GET, PUT, DELETE
When I try to setup my project like this I'm getting the following error:
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'my_project.core.api_urls' from /Users/username/Development/my_project/my_project/core/api_urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
My current setup:
my_project.config.settings.base.py
ROOT_URLCONF = 'config.urls'
DJANGO_APPS = [
# Default Django apps:
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Useful template tags:
# 'django.contrib.humanize',
# Admin
'django.contrib.admin',
]
THIRD_PARTY_APPS = [
'crispy_forms', # Form layouts
'allauth', # registration
'allauth.account', # registration
'allauth.socialaccount', # registration
'rest_framework',
]
# Apps specific for this project go here.
LOCAL_APPS = [
# custom users app
'my_project.users.apps.UsersConfig',
'my_project.core.apps.CoreConfig',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
my_project.config.urls.py
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r'^users/', include('my_project.users.urls', namespace='users')),
url(r'^api/', include('my_project.core.api_urls', namespace='api')),
]
my_project.core.api_urls.urls
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpattenrs = [
url(
regex=r'^users/$',
view=page_not_found,
),
]
The core app does not contain any models right now. It's just where I'm organizing all the URLs
"urlpattenrs" should be "urlpatterns" (in my_project.core.api_urls.urls) ;)

How to get xml format in Django Rest Framework

I'm trying to get xml format in Django Rest FrameWork,I tried the tutorial provided by Django Rest Framework, I'm new to django, I did the following.
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'books',
'users',
]
urls.py
from django.conf.urls import url
from django.contrib import admin
from books.views import *
from users.views import *
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/all/$', all_books),
url(r'^user/', get_user)
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html','xml'])
views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from books.serializers import *
from books.models import *
# Create your views here.
#api_view(['GET'])
def all_books(request):
books = Book.objects.all()
serializers = BookSerializer(books,many=True)
return Response(serializers.data)
When I try to access the xml data, I Get this error by doing ?format=xml
{"detail":"Not found."}
the tutorial link http://www.django-rest-framework.org/api-guide/format-suffixes/
Actually your settings.py is missing the xml parser config.
install rest_framework_xml : pip install djangorestframework-xml
Update INSTALLED_APPS in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_xml',
'books',
'users',
]
Add xml parser in settings.py:
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework_xml.parsers.XMLParser',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework_xml.renderers.XMLRenderer',
),
}

Django Social WrongBackend Error

I am pretty new into django and fully noob into django-social-auth.
My settings.py code is this (From installed app to social_auth_config) :
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
)
THIED_PARTY_APPS = (
#'south',
'captcha',
'social_auth',
)
MY_APPS = (
'account',
'dashboard',
)
INSTALLED_APPS = DJANGO_APPS + THIED_PARTY_APPS + MY_APPS
#------------------------------------------------- Social auth -------------------
LOGIN_URL = 'account/login/'
LOGIN_REDIRECT_URL = 'dashboard/'
LOGIN_ERROR_URL = '/login/'
AUTHENTICATION_BACKENDS = (
'social_auth.backends.contrib.github.GithubBackend',
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"social_auth.context_processors.social_auth_by_type_backends",
"django.contrib.auth.context_processors.auth",
)
SOCIAL_AUTH_DEFAULT_USERNAME = 'nal_auth_user'
SOCIAL_AUTH_UID_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = 16
SOCIAL_AUTH_NONCE_SERVER_URL_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_SERVER_URL_LENGTH = 16
SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH = 16
SOCIAL_AUTH_ENABLED_BACKENDS = ('github',)
GITHUB_API_KEY = '2f1129e79efd4263bf88'
GITHUB_API_SECRET = '6f4cea73e6100d0a994fa5bfff44f7220432c87d'
In urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'website.views.index', name='index'),
url(r'auth/',include('social_auth.urls')),
url(r'account/',include('account.urls',namespace="account")),
url(r'dashboard/',include('dashboard.urls',namespace="dashboard")),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
In account.models login page i have this to show login url..
Login with GitHub
But problem is when ever i click that link it gives me this error
WrongBackend at /auth/login/github/
Incorrect authentication service "github"
Request Method: GET
Request URL: http://127.0.0.1:8000/auth/login/github/
Django Version: 1.5.4
Exception Type: WrongBackend
Exception Value:
Incorrect authentication service "github"
I tried to use google and its gives me the same error except in github its google. I also tried similar questions in stackoverflow.
Please help me if you can :)
check the version of the library of django_sociao_auth, as "THIS LIBRARY IS DEPRECATED IN FAVOR OF python-social-auth. RIGHT NOW THIS LIBRARY DEPENDS DIRECTLY ON python-social-auth AND SHOULD BE CONSIDERED AS A MIGRATION STEP".
Also check if SETTINGS_KEY_NAME = 'GITHUB_APP_ID' SETTINGS_SECRET_NAME = 'GITHUB_API_SECRET' are in class GithubAuth
then try to add this
SOCIAL_AUTH_PIPELINE = (
'social_auth.backends.pipeline.social.social_auth_user',
'social_auth.backends.pipeline.associate.associate_by_email',
'social_auth.backends.pipeline.misc.save_status_to_session',
'social_auth.backends.pipeline.user.create_user',
'social_auth.backends.pipeline.social.associate_user',
'social_auth.backends.pipeline.social.load_extra_data',
'social_auth.backends.pipeline.user.update_user_details',
'social_auth.backends.pipeline.misc.save_status_to_session',
)

Categories

Resources