AuthToken in Django Rest FrameWork: non_field_errors - python

I m trying to integrate token based authentication in DRF(Django version 1.10) but when I hit api-token-auth/ using {"username":"test","password":"123456789"} as mentioned in the doc it is required to return me the Token but I m getting
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
I have used rest_framework.authtoken in my installed apps also token is getting generated once the user is registered and save in authtoken_token table .
Also in my urls.py of root I m using
urlpatterns += [
url(r'^api-token-auth/', authviews.obtain_auth_token),
]
Any help would be appreciated. Also attaching the code
urls.py
urlpatterns += [
url(r'^api-token-auth/', authviews.obtain_auth_token),
]
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.authtoken',
'users'
]
users/urls.py
from rest_framework.routers import DefaultRouter
from . import views as user_views
from django.conf.urls import url ,include
router = DefaultRouter()
router.register(r'user', user_views.UserViewSet,base_name="user")
urlpatterns = router.urls

You are probably not hashing your password and saving it as it is. In your view, you should save password like this.
user = User.objects.create(usename='test', first_name='first_name', email='test#abc.com')
user.set_password('password')
user.save()
user.set_password will hash password.

Thanks Hassan! The issue is resolved . I have used USERNAME_FIELD = 'email' & was using actual username in the post data. Also one more thing I wanted to clarify if anyone can...I m using make_password to hash my password also I can use user.set_password to hash my password in both the cases I m getting token successfully using api-token-auth. Which hashing algorithm or library does DRF authtoken actually using then? or we can hash using any library available Django will automatically decode it ?

Related

Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ The current path, hello/, didn’t match any of thes

I am new to using Django and following a tutorial (https://video.cs50.io/w8q0C-C1js4?screen=gytX_rSwZRQ&start=1160).
So far this course has been great! However, now I am stuck at successfully creating a new app using Django.
Here is the result of my efforts: [Lecture3 Page not found
Here is what the result should be: Hello, World page when found tutorial
As far as I know I've done everything correctly, perhaps I am missing something?
Below is the code I am using, which results in Django returning the error in the title:
urls.py lecture3:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', include("hello.urls"))
]
urls.py hello:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index")
]
views.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("Hello, World!")
settings.py:
INSTALLED_APPS = [
'hello',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
I am currently using: Python 3.9.4, and Django 3.2.3
Any and all help that can be provided will be greatly appreciated.
Thanks in advance, Richardson
The issue is coming from ‘attempttwo.urls’ so revise your settings file.
the path you provided is path('hello/', include("hello.urls")) you need to add "/hello" at the end of the url in the browser, when you run python3 manage.py runserver.

Can Django Tenant Schema work with Django Rest Framework?

I am creating a SaaS app with Django, Django Tenant Schema and Django Rest Framework. Everything works fine without an API but I have issues with sending a get request to different Tenants via an API call. It returns users from all the tenants in the database even if I specify the subdomain.
However, a get request to a none API endpoint works fine, in fact, everything done outside the API endpoint works great.
For Example:
http://goldlimited.localhost:8000/dashboard/api/users
Returns the same information as
http://missinglinkgm.localhost:8000/dashboard/api/users
The view is a basic ModelViewSet
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.filter()
serializer_class = UserSerializer
And the Serializer
class UserSerializer(ModelSerializer):
class Meta:
model = User
exclude = ("password",)
And Route
router = routers.DefaultRouter()
router.register('user', UserViewSet, 'user')
I am wondering if there is a configuration I am missing to make DRF work with Django Tenant Schema.
Yes it does work, little bit of tweaking to settings.py would work. Make sure you add rest_framework to INSTALLED, TENANT APPS.
SHARED_APPS = [
'tenant_schemas',
'Client',
'django.contrib.contenttypes',
# include below if you need admin panel on main site(public schema)
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
# include other apps here
# 'rest_framework' # if needed or if you're handling auth
]
TENANT_APPS = [
'django.contrib.contenttypes',
# include below if you need admin panel on every tenant
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
# include other apps here
'rest_framework', # mandatory
]

Django urls.py mechanism

Recently I started my web project using Django with reference to some youtube tutorials. I have created a project named admin and created an app named user. From many tutorials they have created separate urls.py for both project and app. But in my case only the project's urls.py is working.
For example, I have defined the index view (my home page) in project's urls.py and login view in app's urls.py. When I try to access the login as it shows:
The current path, login, didn't match any of these
Can anyone help me to find out the solution for this?
Django only checks the URLs of the project's ROOT_URLCONF e.g. urls.py. If you want to include the URLs of a certain app, you can do the following:
In your projects urls.py:
from django.urls import include, path
urlpatterns = [
path('user/', include('user.urls')),
# others...
]
Then, if you go to url yoursite.com/user/, it will find the URLs specified in the app's urls.py. For more information see the docs.
Also make sure that your app user is in the INSTALLED_APPS of your settings.py, like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
...
'user',
...
]
So that django knows about your app.

Python- How do I get a Facebook users friend list, status updates, etc. using Django?

I'm having a bit of trouble finding out how to get data back from the facebook user after they accept all permissions. Right now I'm just trying to make my Django app log them in (accomplished), and print their friend list to a webpage just to make sure that it's working properly. I've tried the methods posted on these webpages-
http://axiacore.com/blog/how-retrieve-facebook-extra-info-from-django/
How to retrieve Facebook friend's information with Python-Social-auth and Django
Here is the code that I have so far-
from django.shortcuts import render_to_response, render
from django.template.context import RequestContext
import urllib2
from urllib2 import urlopen
import json
def friendlist(request):
social_user = request.user.social_auth.filter(
provider='facebook',
).first()
goodies = []
if social_user:
#print social_user
url = u'https://graph.facebook.com/{0}/' \
u'friends?fields=id,name,location,picture' \
u'&access_token={1}'.format(
social_user.uid,
social_user.extra_data['access_token'],
)
request = urllib2.Request(url)
friends = json.loads(urllib2.urlopen(request).read()).get('data')
for friend in friends:
goodies.append(friend.get('name'))
return render_to_response('thirdauth/friendlist.html', {'friends': goodies})
def home(request):
context = RequestContext(request,
{'request': request,
'user': request.user})
#print request.user
return render_to_response('thirdauth/home.html',
context_instance=context)
Then, when I make it print out goodies it has no data at all. I'm just wondering what I'm doing wrong.
My settings.py file probably doesn't need to be tampered with, but this is what I've done with it.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social.apps.django_app.default',
'thirdauth',
)
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.tz',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'social.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_FACEBOOK_KEY = '1*************'
SOCIAL_AUTH_FACEBOOK_SECRET = '43************************'
FACEBOOK_EXTENDED_PERMISSIONS = ['email']
SOCIAL_AUTH_FACEBOOK_SCOPE = [
'publish_actions',
'email',
'user_friends',
'user_birthday',
'public_profile',
'user_about_me',
'user_likes',
'user_location',
'user_photos',
'user_posts',
'user_relationships',
'user_status',
'user_tagged_places',
'user_work_history',
]
urls.py looks like this-
from django.conf.urls import patterns, include, url
from django.contrib import admin
from thirdauth import views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'thirdauth.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'thirdauth.views.home', name='home'),
url('', include('social.apps.django_app.urls', namespace='social')),
url('', include('django.contrib.auth.urls', namespace='auth')),
url('^friends/', views.friendlist, name="friendlist"),
)
Thank you so much for the help!
Facebook have changed their API (it is now v2 only, v1 is not supported any more) so that you can no longer get a list of friends through the API. The only thing you can do is get a list of users that use your app. To test this is working ensure that BOTH users have added the app.
If you still need to get a list of users you can do it via exporting to Yahoo by following the instructions at this link: http://iag.me/socialmedia/how-to-transfer-your-facebook-friends-to-twitter-and-other-networks-an-update/
I had trouble getting that working but found this:
http://www.techgainer.com/import-facebook-contacts-gmail-google-contacts/

Apps won't show in Django admin

I've read all the other threads but I still don't get why my apps are not showing up in Django admin. Everything else works fine.
My apps are in settings.py
I have admin.autodiscover in my root urls.py file
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', direct_to_template, {
"template": "homepage.html",
}, name="home"),
url(r'^admin/invite_user/$', 'signup_codes.views.admin_invite_user', name="admin_invite_user"),
url(r'^account/signup/$', "signup_codes.views.signup", name="acct_signup"),
(r'^account/', include('account.urls')),
(r'^profiles/', include('basic_profiles.urls')),
(r'^notices/', include('notification.urls')),
(r'^announcements/', include('announcements.urls')),
(r'^tagging_utils/', include('tagging_utils.urls')),
(r'^attachments/', include('attachments.urls')),
(r'^comments/', include('threadedcomments.urls')),
#
(r'^wayfinder/', include('wayfinder.urls')),
(r'^site/', include('jsite.urls')),
(r'^kiosk/', include('kiosk.urls')),
(r'^navigator/', include('navigator.urls')),
(r'^location/', include('location.urls')),
(r'^event/', include('event.urls')),
#(r'^news_reader/', include('news_reader.urls')),
#(r'^weather_reader/', include('weather_reader.urls')),
(r'^admin/(.*)', admin.site.root),
)
if settings.SERVE_MEDIA:
urlpatterns += patterns('',
(r'^site_media/', include('staticfiles.urls')),
)
All my apps have an admin.py file containing something like
from django.contrib import admin
from event.models import Event
class EventAdmin(admin.ModelAdmin):
list_display = (
'short_name',
'long_name',
'locations',
'categories',
'description',
'phone',
'email',
'url_source',
'url_location',
'external_ref',
'show_event'
)
admin.site.register(Event, EventAdmin)
And I have restarted the server over and over ;-)
I am building on top of Pinax, but from my reading, it shouldn't change anything. Any clue what might be wrong ?
Do you have your apps in the INSTALLED_APPS section in settings.py?
Make sure it has your apps listed there. My section reads
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'squick.items',
'cowsite.search',
'cowsite.posts',
)
for instance. I'm pretty sure for security, they won't show up in the admin unless they are in installed apps. I think I had this same issue, where I couldn't get cowsite to show up in the admin.
The Django docs say about the admin page: "By default, it displays all the apps in INSTALLED_APPS that have been registered with the admin application, in alphabetical order"
By coincidence I had the same problem this morning. Briefly, this is what worked for me (see references for details):
In the top level directory of MyApp (ie same directory as models.py, etc.) I added a python module admin.py, containing:
from models import ThisModel, ThatModel
from django.contrib import admin
admin.site.register(ThisModel)
admin.site.register(ThatModel)
Then in mysite directory I did syncdb and runserver, and ThisModel and ThatModel were in the admin interface.
Does that work for you?
Best wishes
Ivan
** References
(I am a new member so I am allowed to post one hyperlink only!)
Django tutorial: Make the poll app modifiable in the admin
There was also a query on the Pinax google group recently titled, "How to add my app to Admin in a Pinax project?"
Are you logging in to admin as a superuser? If not, it could be a permissions problem.
Not sure which version of django you're using but the current docs suggest including the admin urls.
('^admin/', include(admin.site.urls))
For other's coming across this, I had the same issue due to grappelli.dashboard being in the installed apps but not actually installed in the virtualenv, so do a pip freeze and ensure all your requirements are actually installed.
add your app name in "settings.py" file installed app.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
If the other solutions did not work for you, try to load your admin dashboard in a different browser. One of my apps was not displaying on the admin dashboard while I was using Google Chrome. After trying multiple answers others suggested, I decided to use Firefox instead. Voila! I was finally able to see my app on the admin dashboard.
You didn't answer Antony's question. Are you logging in as a superuser, or at least with a user with add/edit rights for the applications? If not, you won't see them.
I had the same problem, what worked for me was changing this line in urls.py:
url(r'^admin/', include(admin.site.urls)),
to
url('^admin/', include(admin.site.urls)),
(Removing the r in the first bit of code)
For some reason I am not aware of, the Polls became visible in admin after that.

Categories

Resources