Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django:Commenting with Ajax doesn't work properly
I am trying to comment on a post with ajax. it successfully saves to the database. There is no problem with the comment process. but after reviewing it takes me to the action url of the form. It's url path('upload/<int:id>/<str:model_type>/<str:options>',views.django_image_and_file_upload_ajax,name="upload") It's views.py def django_image_and_file_upload_ajax(request,id,model_type,options): if request.method == 'POST': form = CommentForm(request.POST or None, request.FILES or None) obj = get_object_or_404(Thing, id=id) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user if model_type == "comment": comment.is_parent = True else: comment.is_parent = False comment.content_type = ContentType.objects.get_for_model(obj.__class__) comment.object_id = obj.id comment.save() comment_html = render_to_string("includes/comment/comment-list-partial.html", context={ "thing": obj }) return JsonResponse({'error': False, 'message': 'Uploaded Successfully',"thing_comment_html": comment_html}) else: return JsonResponse({'error': True, 'errors': form.errors}) else: form = CommentForm() return render(request, 'pie_thing/deneme.html', {'form': form}) It's ajax code $(document).ready(function () { var $window=$(this); var $thing_comment_list=$window.find("#thing-comment-list") $('#id_ajax_upload_form').submit(function(e){ e.preventDefault(); $form = $(this) var $url =$form.attr("action") var formData = new FormData(this); $.ajax({ url: $url, type: 'POST', data: formData, success: function (response) { console.log(response) $thing_comment_list.html(response.thing_comment_html) }, cache: false, contentType: false, processData: false }); }); It's comment form in html <form enctype="multipart/form-data" id="id_ajax_upload_form" method="POST" novalidate="" action="{% url "pie_thing:upload" thing.id "thing" options %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" /> This is the page I see after commenting page image -
Get user from multiple auth backend
Django 2.2, python 3.6 I'm using 2 authentication backends in my application : GRAPHENE = { 'SCHEMA': 'my_main_app.all_schemas.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] I can get user info from graphql queries method like : @login_required def resolve_curr_user(self, info, parent_id): user = info.context.user But I cannot get user from a view : def curr_user(request): request.user # user is None I'm passing the correct headers to the view request : const headers = new Headers(); headers.append('Authorization', `JWT ${auth_token}`); const init = { method: 'GET', headers: headers, mode: 'cors', cache: 'default' }; const response = await fetch(`/curr_user_route`, init); When authenticating for graphql query, django calls authenticate method from JSONWebTokenBackend class. How do I tell django to call the same method for regular views ? -
Jinja 2 Recursive loop to make html tree
I have a JSON dictionary which can have n depth. I am making an HTML collapsing tree out of it. Its almost done but gives a slight error. Here is the dictionary and the code. { "aaa": { "bbb": { "ccc": { "ddd1": {}, "ddd2": {}, "ddd3": {} } } } } {% for k,v in data.items() recursive %} <ol> <li> <label for="{{k}}">{{k}}</label> <input type="checkbox" checked id={{k}} /> {% if v %} {{ loop(v.items()) }} {% endif %} </li> </ol> {% endfor %} It Displays ddd2 and ddd3 under bbb, but it should display it under ccc -
django-private-chat syntax error with updated websockets
I am trying to integrate django-private-chat into my web application but I keep getting the following syntax error when I run python3 manage.py run_chat_server. asyncio_ensure_future = asyncio.async # Python < 3.5 ^ SyntaxError: invalid syntax I am using Python 3.7 and I understand that this is usually due to websockets not being updated but I have already upgraded it to version 8.1. I ran pip3 install --upgrade websockets and it now looks like this in my requirements.txt file. websockets==8.1 Could someone please advise me on how I can fix this? Thank you. -
Why is it the html showing the ID not the text? using Django
I've just finish to create my table in my views.py, if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = EmployeeUser.objects.get(Username=request.POST['p_user'], Password=request.POST['p_pass'], My_Position=request.POST['position']) #print(request.POST['position']) if m.My_Position.id != request.POST['position']: request.session['member_id'] = m.id aa = request.POST['p_user'] ss = EmployeeUser.objects.all().filter(Username=aa) teacher = SubjectSectionTeacher.objects.filter(Employee_Users__id=m.id) student_subject = Subject.objects.filter(id__in=teacher.values_list('Subjects')).distinct().order_by('id') student_section = Section.objects.filter(id__in=teacher.values_list('Sections')).distinct().order_by('id') student_gradelevel = EducationLevel.objects.filter( id__in=teacher.values_list('Education_Levels')).distinct().order_by('id') cate = gradingCategories.objects.all() studentenrolledsubject = StudentsEnrolledSubject.objects.filter( Subject_Section_Teacher__in=teacher.values_list('id')).distinct().order_by('id') period = gradingPeriod.objects.filter( Grading_Periods_Setting__Education_Levels__in=student_gradelevel.values_list('id')).distinct().order_by( 'id') students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter(Grading_Categories__in=cate.values_list('id')).filter(GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records', 'Grading_Categories', 'Grade').distinct() Categories = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = cate.values_list('id')).order_by('Grading_Categories') table = [] student_name = None table_row = None columns = len(Categories) + 1 # # # table header table_header = ['Student Names'] table_header.extend(Categories) table.append(table_header) for student in students: if not student['Students_Enrollment_Records'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = student['Grade'] table.append(table_row) This is the models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) _dates = models.CharField(max_length=255,null=True, blank=True) Grade = models.FloatField(null=True, blank=True) @property def dates(self): # you have Year-month-day dates … -
upload photos from the database to the carousel using ajax
How can I upload photos from the database to the carousel using ajax? And then you have to update the page when changing in the database. views.py def index(request): time_change = Time.objects.get(id=1).time_for_change_slied * 1000 image_list = Image.objects.filter(bool_field=True).order_by('number_of_slaid') return render(request, 'prezents/index.html', {'image_list': image_list, 'time_change':time_change}) index.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide carousel-fade" data-ride="carousel" data-interval="{{time_change}}" data-pause="false"> <div class="carousel-inner"> {% for a in image_list %} {% if forloop.first %} <div class="carousel-item active "> {% if a.image_prezents %} <img class="d-block " src="{{a.image_prezents.url}}" alt="first"> {% endif %} </div> {% else %} <div class="carousel-item"> {% if a.image_prezents %} <img class="d-block " src="{{a.image_prezents.url}}" alt="second"> {% endif %} </div> {% endif %} {% endfor %} </div> {% endblock %} -
Overwrite field in queryset annotate
I have a django model with the fields name (string) and value (integer). Say I need to return a queryset of {name:..., value:...} objects, with each value doubled. What I am trying to do now is: queryset.annotate(value=F('value') * 2) However, django tells me that the field value already exists. I also tried using extra: queryset.annotate(value_double=F('value') * 2).extra(select={'value': 'value_double'}) but that also does not work since value_double is not a valid field. Of course, in this case I could use something like queryset.extra(select={'value': 'value * 2'}), but I have some other, more complicated cases involving a lot of functions where I really don't want to write sql, but I'd rather find a solution in django. Again, in all of my cases, annotate works perfectly fine as long as I give the result a new name. -
Django/Python, append json with for loops
I collect data from some django models in a very specific order and output them in json to use in React. quiz = LessonQuiz.objects.filter(lesson=details).order_by('position') quizdata = [] if quiz.count() > 0: for a in quiz: qz = LessonQuiz.objects.get(id=a.id) item = {'id': qz.id, 'title': qz.title} if qz.linkbutton_set.count() > 0: buttons = qz.linkbutton_set.all() for b in buttons: item[b.id] = { "id": b.id, "type": b.qtype, "text": b.text, "link": b.link, "color": b.color } quizdata.append(item) at the moment it returns all the data I want as follows, [ { "id": 3, "title": "Do you agree?", "1": { "id": 1, "type": "btn", "text": "I agree", "link": "/lesson/welcome/completed", "color": "#e2574c" }, "2": { "id": 2, "type": "btn", "text": "I'm not sure I agree", "link": "/contact", "color": "#e2574c" }, "3": { "id": 3, "type": "btn", "text": "I have a suggestion", "link": "/contact", "color": "#e2574c" } } ] However, ideally, I would like to have array 1, 2 & 3 in it's own array eg data. [ { 'id': 3, 'title': 'Do you agree?', 'data': [ 1: { 'id': 1, 'type': 'btn', 'text': 'I agree', 'link': '/lesson/welcome/completed', 'color': '#e2574c' }, 2: { 'id': 2, 'type': 'btn', 'text': "I'm not sure I agree", 'link': '/contact', 'color': '#e2574c' }, 3: { … -
getting all the instances of a model into an oblect
I have a model called sickness, which I have used to create multiple instances like malaria, typhoid and others. model class Sickness(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name please, how can I get this into a dictionary form like this where the name will be gotten into the dictionary. duration_choices = { 'malaria':'malaria', 'typhod':'typhod', 'cough':'cough', 'headache':'headache', 'stomach gas':'stomach gas', } -
How to use the context variables passed from Django in javascript? Already changed to Json type
I want to make a table in HTML by using javascript. Now I'm done with the header and displayed correctly. Now I would like to add the content in the table by adding from the database. However, once I declare the context variable from the view.py I created, the table will disappear. How can I call the data correctly from the view.py I made into javascript? I knew it should be JSON style. How can I fix it? thanks in advance. views.py @csrf_exempt def test(request): return render(request, 'test.html') def testJS_page(request): context_list = {} customers = Customer.objects.all() carts = Cart.objects.all().select_related('customer').order_by('customer_id') goods = Good.objects.select_related('cart__customer').order_by('cart_id') context_list['Cart'] = carts context_list['Good'] = goods context_list['Customer'] = customers context = {"Customer_status": json.dumps(context_list)} return render(request, 'test.html', context) test.js var customer_status = ({{ Customer_status|safe }}); function createTable() { var myTableDiv = document.getElementById("myDynamicTable"); var table = document.createElement('TABLE'); var thread = document.createElement('THREAD'); thread.className = "thead-dark"; table.appendChild(thread); var tr1 = document.createElement('TR'); thread.appendChild(tr1); var th1 = document.createElement('TH'); var th2 = document.createElement('TH'); var th3 = document.createElement('TH'); var th4 = document.createElement('TH'); th1.appendChild(document.createTextNode("Product")); th2.appendChild(document.createTextNode("Count")); th3.appendChild(document.createTextNode("Price")); th4.appendChild(document.createTextNode("Subtotal")); tr1.appendChild(th1); tr1.appendChild(th2); tr1.appendChild(th3); tr1.appendChild(th4); myTableDiv.appendChild(table); } createTable(); once I write the code "var customer_status = ({{ Customer_status|safe }});", It seems going wrong. -
Model constants not available in data migrations?
I want to change the data format in my model and replace a char field with an int choice. The old field is called objective and the new field is called objective_new Here is the model definition (excerpt): from django.db import models from django.utils.translation import gettext_lazy as _ class Timer(models.Model): # (...) OBJECTIVE_HOSTILE = 1 OBJECTIVE_FRIENDLY = 2 OBJECTIVE_NEUTRAL = 3 OBJECTIVE_UNDEFINED = 4 OBJECTIVE_CHOICES = [ (OBJECTIVE_HOSTILE, _('Hostile')), (OBJECTIVE_FRIENDLY, _('Friendly')), (OBJECTIVE_NEUTRAL, _('Neutral')), (OBJECTIVE_UNDEFINED, _('Undefined')), ] objective_new = models.SmallIntegerField( choices=OBJECTIVE_CHOICES, default=OBJECTIVE_UNDEFINED, verbose_name='objective', ) objective = models.CharField( max_length=254, default="", blank=True, help_text='This field is no longer in use', ) # (...) To convert the existing data to the new format I want to use a data migration that maps the text from the old field to the new choice field. And here is my problem: It seams that the model class that I get in the data migration does not contain any constants, e.g. OBJECTIVE_CHOICES which I need to make the mapping. Here is my data migration code (excerpt): def migrate_forward(apps, schema_editor): Timer = apps.get_model('timerboard', 'Timer') objective_map = {x[1]: x[0] for x in Timer.OBJECTIVE_CHOICES} # (...) I am getting the following error: AttributeError: type object 'Timer' has no attribute 'OBJECTIVE_CHOICES' Of course … -
How to set repeat interval time in background-tasks using django?
I tried to run the background task code in Django. its working fine but interval time is not working. it working every second how to fix it anyone gives some solution. views.py from django.shortcuts import render from django.http import HttpResponse from background_task import background from django.core.mail import send_mail @background(schedule=5) def hello(): print('hello_world') # Create your views here. def index(request): hello() return HttpResponse('<h1> Hello World </h1>') I tried to pass repeat parameter also from django.shortcuts import render from django.http import HttpResponse from background_task import background from django.core.mail import send_mail @background(schedule=5) def hello(): print('hello_world') # Create your views here. def index(request): hello(repeat=10) return HttpResponse('<h1> Hello World </h1>') I tried many ways. But still is not working.I need every One hour to print hello world. -
How to access other field value from ModelSerializer?
I need to return some computed value using request param. To get computed result, I need login user(which could successfully restive) and access to Post model field(favorited_users). How can I get access to self.favorited_users from ModelSerializer class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() spot = SpotSerializer() is_login_user_favorite = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' read_only_fields = ('owner',) def get_is_login_user_favorite(self, validated_data): login_user = self.context['request'].user # I need to do something like below. # return self.favorited_users.contains(login_user) class PostListAPIView(generics.ListAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.all().order_by('-pk') permission_classes = [IsAuthenticated] -
Setting pre-hook for docker-compose file
I am running a dockerized django app and I am looking for a way to run (a) directive(s) every time before I build a docker container. More concretely, I would like to run docker-compose -f production.yml run --rm django python manage.py check --deploy each time before I either build or up the production.yml file. Like a pre-hook. I know I could achieve this with a bash-script, yet I was wondering if there is a way of doing this inside the docker-compose file. I can't find anything in the docker documentation (except events, but I don't understand if they serve for what I want to achieve) about it and I assume that this is not possible. Yet, maybe it is in fact possible or maybe there is a hacky workaround? Thanks in advance for any tips. -
Django DRY Models
In general, how can I keep my models DRY when I have to repeat several attributes multiple times? For example: class Event(models.Model): title = models.CharField(max_length=255) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) street = models.CharField(max_length=50) street_nr = models.CharField(max_length=5) class Person(models.Model): name = models.CharField(max_length=50) postal_code = models.CharField(max_length=5) city = models.CharField(max_length=50) street = models.CharField(max_length=50) street_nr = models.CharField(max_length=5) -
File "/app/.heroku/python/lib/python3.6/tkinter/__init__.py", import _tkinter # If this fails your Python may not be configured for Tk
Im working on heroku and i trying to deploy my django application on heroku but i got this error ECONNREFUSED: connect ECONNREFUSED 50.19.103.36:5000. This is caused by network issue soI disconnected my lan and connected in my mobile wifi and i gave migrate then the migrate command ran and showing tkinter error, and i think is any problem in python version because in my normal command prompt my python version is 3.7, if i check version in anaconda prompt it showing the python version 3.6. In that error also it showing in screenshot. -
How to make your own custom hasher Django?
I need to make my own custom MD5 hasher in Django in order username + password. I create hashers.py import hashlib from django.contrib.auth.hashers import MD5PasswordHasher from jd.models import AdvUser, Users, create_user from django.contrib.auth.models import UserManager class JDMD5PasswordHasher(MD5PasswordHasher): def encode(self, password, salt=None): assert password is not None hash = hashlib.md5(password.encode()).hexdigest() return hash I get username from forms.py def save(self, commit=True): user = super().save(commit=False) username = self.cleaned_data.get('username') user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, instance=user) return user But I cant find solution how to hash username too. Something like: logpass = str(username) + str(password) hash = hashlib.md5(logpass.encode()).hexdigest() -
How to use an optional parameter in django URL
I want solution for how Django URL work without any optional parameter or with optional parameter see my url structure that I want path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>-vs-<slug:brand_slug3>/',views.compare_brand) now, I want something like 1st two slugs for comparison is compulsory so, as per the above URL path('<slug:category_slug>-comparison/<slug:brand_slug1>-vs-<slug:brand_slug2>',views.compare_brand) this is working fine because this are compulsory url parameter but i want to pass optional url from 2nd 'vs' to brand_slug3. can anyone help me in this? -
Make Django REST to call create method of first class from retrieve method of another class
Below code calls the retrieve method and works fine class SomeWorkflow(ViewSet): serializer_class = SomeWorkflowSerializer def retrieve(self, request, pk): response = OtherWorkflowSerializer.as_view({'get': 'retrieve'})(request._request, 'some_id').data Now I want to call the OtherWorkflowSerializer class's create method. The create method also takes some parameters like {'id': 1, 'file_path': '/foo/bar/file.txt'} -
Django build in error runtime translation
i want to translate Django buildin errors in different languages on runtime. Is it possible to translate django error for requested user according to his region. -
How to request param inside ModelSerializer
I need to return some computed value using request param. It seems that I need to get access to request param from inside ModelSerializer. How can I do this? class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() spot = SpotSerializer() is_login_user_favorite = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' read_only_fields = ('owner',) def get_is_login_user_favorite(self, validated_date): return True # I need change this dynamically class PostListAPIView(generics.ListAPIView): serializer_class = serializers.PostSerializer queryset = Post.objects.all().order_by('-pk') permission_classes = [IsAuthenticated] -
Geo Django GDAL: Unable to open EPSG support file gcs.csv
I recently did a clean window installed. I installed OSGeo4W via: https://trac.osgeo.org/osgeo4w/ I installed GDAL by downloading the pip wheel GDAL-2.3.2-cp36-cp36m-win_amd64.whl I also configured my django settings.py to: if os.name == 'nt': import platform import sys OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = sys.path[6] + r'\osgeo\gdal203.dll' This configuration worked on my previous machine but when trying to edit a django model with a Point field I would get this error: GDAL_ERROR 4: b'Unable to open EPSG support file gcs.csv. Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.' Error transforming geometry from srid '4326' to srid '3857' (OGR failure.) GDAL_ERROR 4: b'Unable to open EPSG support file gcs.csv. Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.' Internal Server Error: /admin/event/event/31/change/ I followed the same configuration as my previous setup. Same machine but new OS so I'm a bit stomped. How can I configure the GDAL_DATA env variable? I tried the suggestion: https://stackoverflow.com/a/52597276/9469766 setting … -
Which one is better for online market Djnago or Flask?
I and my partner are working on an online market, we want the website to take the customer's information, his order details and send it to us and the supplier company. Basically, we will be the connect between them and the supplier. Which is better for this type of things flask or django? In addition, we may include some AI to help us see what the customer want. -
null entries in databse and when i click them i get TypeError at /admin/users/personal_detail/90/change/ __str__ returned non-string (type NoneType)
this is how my base.html looks like,everything was working fine until i did some changes adding jquery {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type ="text/css" href="{% static 'pmmvyapp/main.css' %}"> <link href="{% static 'js/jquery.js' %}" rel="stylesheet"> {% if title %} <title> PMMVY-{{ title }}</title> {% else %} <title>PMMVY</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4"><img src="{% static 'images/left-logo.png' %}" width="83" height="89" class='d-inline-block' alt=""/> <span style="color:white"> Ministry of Women &amp; Child Development | GoI</span> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> {% if user.is_authenticated %} <a class="btn btn-primary mr-4" href="{% url 'aganwadi' %}">Aganwadi</a> <a class="btn btn-primary mr-4" href="{% url 'applyonline' %}">Apply online</a> {% else %} <div class="navbar-nav mr-auto"> <a class="navbar-brand mr-4"><img src="{% static 'images/emblem-dark.png' %}" width="60" height="80" class='d-inline-block' alt=""/> <span style="color:white" >Pradhan Mantri Matru Vandana Yojana</span> </a> </div> {% endif %} <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <div class="navbar-nav mr-auto"> <a class="btn btn-primary mr-4" href="{% url 'admin:index' %}"> Admin site … -
Creating user on the basis of schema name
I'm building webapp using django and there are multiple users and each user have their own schema, Each schema contains its auth models. Now I want to create new superuser on the basis of schema name , My main requirements is to create new super user user when ever new tenants is created. Is there any django orm or create new user. Any suggestion would be appreciated. for more info please follow Auto Create new User for new teanants in django I'm looking features somethings like https://github.com/Corvia/django-tenant-users/tree/master/tenant_users/permissions