Django 2.0.6 manage.py getting runserver error - django-2.0

I'm new on python and also try to learn a Django version 2.0.6 , so when i try to write the code with the documentation of Django here:
If faced a problem, specifically when I want to run the code, could help me to solve that issue please.
1- code (urls.py)folder polls:
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name= 'index'),
]
2- code (urls.py) folder mysite:
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/',include('polls.Urls'))
]
3- code (views.py) folder mysite:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hi world, you are walcome")

Related

djangorestframework-simplejwt not working

I'm following a Udemy Course with user administration and I need to install this
pip install djangorestframework-simplejwt
After its installed, I need to add this to settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
But its gives me this error
ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'pkg_resources'.
So far I haven't been been able to find anything on google
INSTALLED_APPS = [
...
'rest_framework_simplejwt',
...
]
It should be added in INSTALLED_APPS
Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html

Postman asking for login credentials even though I am using a Bearer token

I have a Django Rest Framework backend that uses a Bearer token to authenticate a user for all APIS, while testing it on POSTMAN, it displays a Django admin login form
link to POSTMAN screenshot
I don't understand why it's asking me to authenticate as an admin on POSTMAN.
As requested I've added urls.py for base and user:
Base urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', admin.site.urls),
path('user/v1/', include(('user.v1.urls', 'user'), namespace='user_v1')),
path('second-opinion/v1/', include(('second_opinion.v1.urls', 'second-opinion'), namespace='second-opinion_v1')),
path('utils/v1/', include(('utils.urls', 'utils'), namespace='utils_v1')),
]
User urls.py
from django.urls import path
from django.conf.urls import url, include
from rest_framework import routers
from user.v1.views import UserView, NotificationView, PhysicianDetailView, PhysicianProfileRequestsView, \
ProfileInviteView, create_cognito_user, get_physician_detail
router = routers.DefaultRouter()
router.register(r'profile', UserView, basename='profile')
router.register(r'notification', NotificationView, basename='notification')
router.register(r'physician-detail', PhysicianDetailView, basename='physician-detail')
router.register(r'profile-request', PhysicianProfileRequestsView, basename='profile-request')
router.register(r'profile-invite', ProfileInviteView, basename='profile-invite')
urlpatterns = [
url(r'^', include(router.urls)),
path(r'create_default_user/', create_cognito_user),
path(r'physician/detail/<int:user_id>', get_physician_detail)
]
Rest Framework dictionary:
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticated',],
'DEFAULT_PAGINATION_CLASS': 'utils.pagination.CustomPagination',
'DEFAULT_AUTHENTICATION_CLASSES': (
'django_cognito_jwt.JSONWebTokenAuthentication',
),
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER': 'utils.custom_exception_handler.custom_exception_handler'
}
In your Base urls.py can you try moving path('', admin.site.urls), at the end of urlpatterns list instead of the very first.
Because django resolves urls in sequence and due to '' in your path for admin sites all your urls are resolving to admin page.

Authentication credentials were not provided - Django

I'm having trouble with this error. Tried almost all available solutions but nothing working for me. At frontend side I am using Angular 6 and I am pretty sure it's not error from it. Hoping for a response soon and thanks in advance guys.
register/url.py
from django.urls import path, include
from rest_framework import routers
from . import views
from rest_framework.authtoken.views import ObtainAuthToken
router = routers.DefaultRouter()
router.register('users', views.UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
#path('auth/', include('rest_framework.urls', namespace='rest_framework')),
path('auth/', ObtainAuthToken.as_view()),
]
serialier.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = { 'password' : { 'write_only' : True , 'required':True } }
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
view.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from .serializers import UserSerializer
from rest_framework.permissions import IsAuthenticated
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
authentication_classes = (TokenAuthentication, SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
setting.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.authtoken',
'register',
'corsheaders',
]
The following error is displayed in the browser's console:
{“detail”:“Authentication credentials were not provided.”}
Your viewset has the IsAuthenticated permission class. In other words, an user must be authenticated in order to retrieve, update or even create an instance. Make sure that the appropriate headers are included in your requests.
For example, for a token authentication, as stated by Django Rest Framework documentation
For clients to authenticate, the token key should be included in the
Authorization HTTP header. The key should be prefixed by the string literal
"Token", with whitespace separating the two strings. For example:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
In the particular case of an account creation, I'm not sure that it is intended for your application to require an user authentication.

vendor.js bundle in fusebox not working

I'm configuring my angular app with fusebox instead of webpack and I want to have 3 separated bundles (polyfills.js, vendor.js and app.js).
In webpack I'm using this:
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
being polyfills.ts
import 'core-js/es6';
import 'core-js/es7/reflect';
require('zone.js/dist/zone');
if (process.env.ENV === 'production') {
// Production
} else {
// Development and test
Error['stackTraceLimit'] = Infinity;
require('zone.js/dist/long-stack-trace-zone');
}
and vendor.ts
import '#angular/platform-browser';
import '#angular/platform-browser-dynamic';
import '#angular/core';
import '#angular/common';
import '#angular/compiler';
import '#angular/http';
import '#angular/router';
import '#angular/forms';
import 'rxjs';
import './rxjs-extensions';
with rxjs-extensions.ts
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
Now I changed this to fusebox
fuse.bundle('polyfills').instructions('> polyfills.ts');
fuse.bundle('vendor').instructions('~ main.ts vendor.ts');
fuse.bundle('app').instructions('!> [main.ts]').watch().hmr();
In this case polyfills is fine, and vender has all 3rd party dependencies from the app (~main.ts) plus all in vendor.ts, while app has only what is in the project.
It seems to compile fine but then when I execute the code I get a ERROR TypeError: this.http.get(...).map is not a function in my service.get(...).map()
My feeling is that vendor.ts is not importing rxjs-extensions.
Anyone knows how to fix this?
If I use just
fuse.bundle('polyfills').instructions('> polyfills.ts');
fuse.bundle('vendor').instructions('> vendor.ts');
fuse.bundle('app').instructions('> main.ts').watch().hmr();
it works, but then my app.js bundle includes too many things and goes from 303K to 2.4MB
Make sure you got the order right. Try WebIndexPlugin it helps to automatically inject scripts. If you post your configuration file it might be able to tell you what's wrong

Dajaxice 0.5.1 - Can't seem to make the tutorial work

I've checked over my stuff repeatedly and I cannot find the issue.
Here's the layout of my project:
project
allthings
init.py
admin.py
settings.py
models.py
views.py
tests.py
static
css
dajaxice
dajaxice.core.js
images
js
templates
testing.html
project
ajax.py
init.py
settings.py
urls.py
views.py
wsgi.py
manage.py
settings.py
DEBUG = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL =/static/
STATICFILES_DIRS = (
'C:/Python27/djcode/project/static',
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'dajaxice.finders.DajaxiceFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
)
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',
)
ROOT_URLCONF = 'project.urls'
WSGI_APPLICATION = 'project.wsgi.application'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages'
)
TEMPLATE_DIRS = (
"C:/Python27/djcode/project/templates"
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'allthings',
'dajaxice',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from project.views import hello, testing
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
('^hello/$', hello),
('^testing/$', testing),
url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += staticfiles_urlpatterns()
views.py
from django.shortcuts import render_to_response, HttpResponse
from django.template import RequestContext
from dajaxice.core import dajaxice_autodiscover
dajaxice_autodiscover()
def hello(request):
return HttpResponse("Hello world!")
def testing(request):
return render_to_response('testing.html', context_instance = RequestContext(request))
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def sayhello(request):
return simplejson.dumps({'message':'Hello World'})
testing.html
<!DOCTYPE html/>
{% load dajaxice_templatetags %}
<html>
<head><title></title>
{% dajaxice_js_import %}
<script>
function my_callback(data){
alert(data.message);
}
</script>
</head>
<body>
This is to test stuff
<input type="button" onclick="Dajaxice.project.sayhello(my_callback)" value="Get Message from Server"></input>
</body>
</html>
All it does it make a button that puts out an alert. It should be incredibly simple and yet I get nothing. What am I doing wrong?
Because dajaxice.core.js is a non-static template file, DajaxFinder will find it and 'render' to a temp folder as a static file.
So your STATICFILES_DIRS settings should not contain the file path to dajaxice.core.js otherwise the file will be found by FileSystemFinder rather than DajaxFinder.
You can run findstatic to check it is found correctly or not:
manage.py findstatic dajaxice\dajaxice.core.js
or maybe:
manage.py findstatic dajaxice/dajaxice.core.js
The output result should be in some temp folder (depending on your OS) and should not be in any folder of your app.

Resources