Can Django Tenant Schema work with Django Rest Framework? - python

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
]

Related

AuthToken in Django Rest FrameWork: non_field_errors

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 ?

Migration fails when extending Django User Model

I'm trying to extend django User model by inheriting AbstractBaseUser so i can be able to manipulate the authentication process of the project.
Here is what my model looks like.
class AccountManager(BaseUserManager):
... create_user
... create_superuser
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
objects = AccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
And here is my settings INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'rest_framework',
'compressor',
'authentication'
]
AUTH_USER_MODEL = 'authentication.Account'
The problem here i notice the migration process that django is bypassing the auth.0001_initial and it jumped directly creating the admin.0001_initial making my migrations to fail with
django.db.utils.IntegrityError: (1215, u'Cannot add foreign key constraint')
How can i fixed this please help?
I was able to solve my issue, by this simple steps:
run python manage.py makemigrations authentication - because when using AUTH_USER_MODEL it will replace the migration of auth_user table of django.contrib.auth altering the migration process. Thus if we fail to provide migration file for authentication app migration will no doubt fails.
run python manage.py migrate.
Binggo!

Django 1.8: Model doesn't appear in admin panel

I am following Django official tutorial and I got stuck at the second part. In particular, I can't have my newly created model displayed in the admin panel. Step by step:
I created a new app;
I add it to settings.py (see below);
I edited the models.py file (see below);
I ran my first migration, succesfully;
(I check on MySQL and everything was created ok);
I change the admin.py file (see below);
I refreshed maniacally the admin panel with no results.
myproject/myproject/settings.py:
[...]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
[...]
myproject/myapp/models.py:
from django.db import models
class Question(models.Model):
body = models.CharField(max_length=200)
myproject/myapp/admin.py:
from django.contrib import admin
from .models import Question
admin.site.register(Question)
What I am doing wrong?
How do you start the debug-server? Did it restarts after your changing the code? Try to stop the debug server and start over again with --nothreading option.
This works for me
from django.contrib import admin
from .models import Role
class RoleAdmin(admin.ModelAdmin):
class Meta:
model = Role
admin.site.register(Role,RoleAdmin)
Does it make sense for you?
Try killing or restarting your WSGI server. Also check if there are no WSGI processes stucked in background.

Django allauth session JSON serializable error after login

I have installed django-allauth, after that this is my settings.py
Django_apps = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
Third_party_apps = (
'avatar',
'allauth',
'allauth.account',
'allauth.socialaccount',
'bootstrapform',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.twitter',
)
My_apps = ()
INSTALLED_APPS = Django_apps + Third_party_apps + My_apps
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
"django.core.context_processors.request",
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
ACCOUNT_ADAPTER ="allauth.account.adapter.DefaultAccountAdapter"
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_USERNAME_MIN_LENGTH = 3
and i believe i also correctly set my urls.py. And also i have two Social app from django admin with correct twitter and github api keys and secrets.
But then problem is whenever i click to login via twitter it shows me the correct twitter auth page and after i authorize the app it gives me this error..
<allauth.socialaccount.models.SocialLogin object at 0x7feb5875a650> is not JSON serializable
and also i get almost the same error with github. like
<allauth.socialaccount.models.SocialLogin object at 0x7feb5877a590> is not JSON serializable
, So please help me to understand what's the problem
In Django 1.6 you have to change the SESSION_SERIALIZER parameter to pickle. Put this in your settings.py:
SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'
I don't know when allauth will become compatible with this new Django serialization format. See Django 1.6 release notes.

Django not recognizing django admin urls

I just registered my models my models with django admin.
I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far.
But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying
The current URL, admin/auth/user/, didn't match any of these.
Its really weird because in my urls.py I have it mapped correctly
(r'^admin/', include(admin.site.urls)),
I have all the required middleware enabled and have these in my installed apps
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
anyone have any idea? Thanks.
Do you have this one in your urls.py?:
from django.contrib import admin
admin.autodiscover()
But in fact without this you shouldn't even see models from django.contrib.auth... weird, can you post complete urls.pt file?

Categories

Resources