Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filtering in Django use specific user
I try to filtering django some specific user. I try with list but it not working. Do you have any solution. list = ['bill gates','elon musk','aamir khan','larry page'] allPosts = Post.objects.filter(author=list) When I change list filter can work dynamically -
Why ajax returns the latest variable of a loop in html template?
I have a html file as bellow: <div id="preview_updated_notifications"> {% for lst in unread_list %} <div > <span data-notification-item="{{ lst.id }}" id="_mark_as_read_id"> ●</span> </div> {% endfor %} </div> and in js file: $(document).on('click', "#_mark_as_read_id", function() { var object_id = $('#_mark_as_read_id').data('notification-item'); console.log('--------------object_id:------------') console.log(object_id) console.log('--------------------------') $.ajax({ type: "GET", url: "{% url '_mark_as_read' object_id %}", dataType: 'json', data: { 'object_id': object_id, }, dataType: 'json', success: function (data) { $('#preview_updated_notifications').html('**TEST**'); } }); event.preventDefault(); }); But the problem is that this always prints the latest value of loop, while I expect after clicking on each item ● retrieve the relative id! -
Why is the delete button for a Heroku app greyed out?
I want to delete an Django app and found two solutions: Use the delete button in settings, or from the command line. The delete button doesn't work (the "prohibited" icon shows up). I started a console from within the app to use the command heroku destroy apps --app MyApp, but the command "isn't found". This app has never been set up, so I get lots of "failed" notifications. So I want to remove it. How can I delete this app? -
Upload file at Wagtail bakerydemo
I can't make file upload form field work. My references are: https://github.com/lb-/bakerydemo/blob/stack-overflow/61289214-wagtail-form-file-upload/bakerydemo/base/models.py https://dev.to/lb/image-uploads-in-wagtail-forms-39pl The field was added to admin and appear correctly on my site, but when I try to send the form: if the field is required, the form is reloaded without any error if the field is not required, the form is sent but the file is not uploaded What am I doing wrong? I've been working on this for 3 days and can't find any error message pointing what's wrong. When I get some error message it's always too generic. Please help! :) My models.py inside bakerydemo/bakerydemo/base from __future__ import unicode_literals import json from os.path import splitext from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.utils.html import format_html from django.urls import reverse from django import forms from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel, ) from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Collection, Page from wagtail.contrib.forms.forms import FormBuilder from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormSubmission, AbstractFormField, FORM_FIELD_CHOICES from wagtail.contrib.forms.views import SubmissionsListView from wagtail.images import get_image_model from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.fields import WagtailImageField from wagtail.search import index from wagtail.snippets.models import register_snippet from .blocks import BaseStreamBlock from django.core.validators … -
Django DEBUG = True xlsx files do not work
I have faced a strange problem. I have a button that creates xlsx file. For example, firstly file is empty and when I press the button it becomes full of information from the database( PostgreSQL ). And now what is wrong: When DEBUG is TRUE in settings.py file everything works pretty fine and the document creates. When DEBUG is FALSE it do not change the file. I really appreciate all answers, thanks! -
how i can handel date in path
i want test api of my project. i have model Article that have DateField that fill automatic and certainly each time save date.today() so if i run this line of test code today it run correctly but future days will run incorrectly response=self.client.get("/api/v1.0.0/blog/archive/en-2021-01/") how i can change the date part of above line of code dynamically.I mean part "en-2021-01" of the above code .I also tested it with a variable but it did not work.like this edate=str(date.today()) response=self.client.get("/api/v1.0.0/blog/archive/en-edate/") i do not know how changed it to work Thanks for trying to help me -
How could I show placeholder inside html inputs?
I want to set placeholder inside text inputs, and I still don't know how to do this. I tried to add attributes but they didnt work and text is still showing above inputs. Here's my code: forms.py class LoginForm(forms.Form): username = forms.Charfield(widget = forms.TextInput), password = forms.Charfield(widget = forms.PasswordInput) and that form is creating something like this: html <div class="row"> <div class="col-8"> </div> <div class="col-4"> <p><span style="font-size:50px; color:#ac3b61;">Welcome!</span></p> <form action="/account/login/" method="post"> <p><label for="id_username">Username:</label> <input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" maxlength="150" required="" id="id_username"></p> <p><label for="id_password">Password:</label> <input type="password" name="password" autocomplete="current-password" required="" id="id_password"></p> <input type="hidden" name="csrfmiddlewaretoken" value="gkh34TNSATaWHP3f3c9Qmp1msf6nazSd9hAoKsTPlHtMWFN4nNIYOwkpx9iXcCer"> <input type="hidden" name="next" value="/account/"> <p><input type="submit" value="Login"></p> <p><a href="/account/password_reset/">Forgot your password?</a></p> <p>Don't have an account? Register <a href="/account/register/">here</a>. </p> </form> </div> </div> -
Django testing (TestCase) with multiple database is failing
I use 2 databases on my django app - the first is MySQL and the second is Mongo (using the [djongo][1] engine). I started writing some tests using the TestCase and i want to use sqlite3 engine. My DBs configuration: (You can see that i have assigned TEST DBs on sqlite] #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DEFAULT_NAME, 'USER': DEFAULT_USER, 'PASSWORD': DEFAULT_PASSWORD, 'HOST': 'my-host-here', 'PORT': '3306', 'TEST': { 'NAME': 'test_dev' } }, 'mongoDB': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://{}:{}@{}/?retryWrites=true&w=majority'.format( username, password, host), 'username': username, 'password': password, 'name': name, 'authSource': authSoruce, 'ssl':ssl, 'authMechanism': 'SCRAM-SHA-1', } } } # If django runs unittests - run on a local sqlite DB if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', 'SUPPORTS_TRANSACTIONS': True } DATABASES['mongoDB'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase2', 'SUPPORTS_TRANSACTIONS': True } When i run the tests, I get failures when Django is trying to create the mongoDB TEST database. error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: release_notes_releasenotesformmodel (release_notes_releasenotesformmodel is the only model i have in the mongoDB) test script: databases = '__all__' def SetUp(self): self.client = Client() self.dummy_test = EdisonAbTestsListModel.objects.create( test_id=DUMMY_TEST_ID_1 ) def run_test(self): ## here is my test logic...``` [1]: https://github.com/nesdis/djongo -
Get certain parameter on a fetch request
I'm developing a twitter-like app where users are able to make posts. I want to make a div containing the Username posting, the post content, and the date. Since the username is a ForeignKey, I had some errors until I was able to fetch the whole User table. I only need to get the username field, which seems to be a dictionary inside and list, as I'll show below. Below, you may find the codes: The Models class User(AbstractUser): pass class PostData(models.Model): active = models.BooleanField(default=True) # In case I want to add a delete feature in the future post_content = models.CharField(max_length=360) date_post_created = models.DateTimeField(auto_now_add=True) user_posting = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userposting") def __str__(self): return f"{self.post_content}" def serialize(self): return { "post_content": self.post_content, "user_posting":serializers.serialize("json", User.objects.all()), "date_post_created": self.date_post_created } The views.py def all_posts(request): # Get posts. posts = PostData.objects.all() #Return in reverse chronological order posts = posts.order_by("-date_post_created").all() return JsonResponse([post.serialize() for post in posts], safe=False) The posts.js (which has the code to feed the html) function load_posts(){ fetch('allposts') .then(response => response.json()) .then(posts => { posts.forEach(element => { console.log(element.post_content); console.log(element.user_posting); console.log(element.date_post_created); (...) The current output: from console.log(element.post_content); teste teste teste ** from console.log(element.user_posting); ** [ {"model": "network.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$216000$C13hJOjD4ojv$AW5a0AFEisWO7IG0MkVNQ8k6+OnfN0CljEV8lnfEaKE=", "last_login": "2021-01-29T00:01:37.127Z", "is_superuser": false, "username": … -
django extended page not rendering values from registration page (User django Model)
I extended the user model and created one to one relationship from users to a Customer model. However, whenever I'm calling the Customer Page the fields from the user model are not rendered there. It's only rendering one field, the username in the Customer Model in the field name instead of rendering the first name as name, last name and email address, and so on. How can I achieve that? I need the customer form to fill in using information from the user's registration whichever is available. Makes sense? Or the implementations I'm trying to do is wrong. Thank you in advance. Please see below the code for models.py and views.py models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import Group # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) address_1 = models.CharField(max_length=200, null=True) zip_code = models.CharField(max_length=5, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) #return self.name # Using signals to post_save data def customer_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='customer') instance.groups.add(group) Customer.objects.create( user=instance, name=instance.username, ) … -
convert json string to datetime format dd/mm/yyyy in django template
After using json.loads to get data and show it on django template, it give these results Contract Name Debt Createat 20150307-500000-0009 AAA 2 2020-12-13T14:25:35Z 20170221-0007429 BBB 3 2020-12-13T14:25:35Z I try to convert date time on createat column to dd/mm/yyyy, like this Contract Name Debt Createat 20150307-500000-0009 AAA 2 13/12/2020 20170221-0007429 BBB 3 13/12/2020 In my view contract_posts = serializers.serialize('json', Contracts.objects.all()) contract_posts = json.loads(contract_posts) request.session['contract_posts'] = contract_posts context = {'contract_posts': contract_posts} return render(request, 'customer2.html', context) in my template {% for contract in contract_posts%} <tr> <td>{{ contract.fields.contract }}</td> <td>{{ contract.fields.name }}</td> <td>{{ contract.fields.debt }}</td> <td>{{ contract.fields.created_at}} </tr> {% endfor %} I try <td>{{ contract.fields.created_at|date:"d m Y"}} or <td>{{ contract.fields.created_at|date:"SHORT_DATE_FORMAT"}} But it just show empty cell in result Contract Name Debt Createat 20150307-500000-0009 AAA 2 20170221-0007429 BBB 3 -
How to get current user information in django admin template?
I have the following Profile model which relates the user using a OneToOneField and also has a theme field with two choices light & dark. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') theme = models.CharField(max_length=20, choices=USER_THEME, default='light') history = HistoricalRecords() def __str__(self): return self.user.username I access the current logged In user theme in my templates using the following: {{ user.user_profile.theme }} Now I want to access the same thing in my overriden django admin template named base_site.html. I did the following but even though the theme of the current user is light it still loads the dark.css file from /static/css/admin/. base_site.html {% extends "admin/base.html" %} ...... {% block extrahead %} <!-- Problem is here --> {% if user.is_authenticated %} {% if user.user_profile.theme == 'dark' %} <link href="{% static '/css/admin/dark.css' %}" rel="stylesheet"> {% endif %} {% endif %} {% endblock %} I don't know what I'm doing wrong here and I appreciate some help. I'll improve my question if more information needed. Thanks in Advance! -
Matching cards in Django, html and js
good evening everyone. I have a list of random questions and answers, they're not very much different than matching cards. I'm making them using Django library in python. And I can't manage to make it to work, using html, js. I tried couple of scripts but they all failed. Here's the code: views.py: def homePage(request): objects = QuestionsAndAnswers.objects.values('question', 'answer', 'id') objects = sample(list(objects), 10) context = { 'QuestionsRandom' : sample(list(objects), 10), 'AnswersRandom' : sample(list(objects), 10), } return render(request, 'homepage.html', context=context) homepage.html: <div class='column1'> {% for result in QuestionsRandom %} <p><button class="questionCard" id="Q{{result.id}}" onclick="setColorQuestion('Q{{result.id}}')"> <p style="color:black;margin: center;">{{forloop.counter}}</p> <p style="color:#4CAF50;font-size: 23px;text-align: center;">{{result.question}}</p> </button></p> {% endfor %} </div> {% for result in AnswersRandom %} <p><button class="answerCard" id="A{{result.id}}" onclick="setColorAnswer('A{{result.id}}')"> <p style="color:black">{{forloop.counter}}</p> <p style="color:rgb(228, 72, 72); font-size: 23px;padding: inherit;">{{result.answer}}</p> </button></p> {% endfor %} I make the question's id and the answer's id invisible, so I can call them in the js script to check if they're the same then count a point to the team that opened the question card and the answer card correctly. <script> function checkingCard(choosedCardID) { var button = document.getElementById(choosedCardID); var style = getComputedStyle(button); var color = style['background-color']; if (choosedCardID.startsWith('Q') && color == 'rgb(0, 0, 0)') { console.log('entering question, rgb is black'); … -
How do I pass in a value (kwargs?) through the URL for Django DayArchiveView?
Okay, So I have a club model which has many booking slots. I want to be able to use Django DayArchiveView but pass in additional parameters which correspond to the club. This is what I tried but I get the error "NoReverseMatch at /book/club/5/2021/jan/1/ Reverse for 'archive_book_day' with keyword arguments '{'year': '2020', 'month': 'dec', 'day': '31'}' not found. 1 pattern(s) tried: ['book/club/(?P[0-9]+)/(?P[0-9]+)/(?P[^/]+)/(?P[0-9]+)/$']" urls.py urlpatterns = [ # Example: club/5/2012/nov/10/ path('club/<int:clubid>/<int:year>/<str:month>/<int:day>/', BookingArchiveView.as_view(), name="archive_book_day"), ] views.py class BookingArchiveView(DayArchiveView): ..... You see it works perfectly fine when I only use 'int:year/str:month/int:day/' but I want to be able to add a parameter to represent the club. Can anyone help me or tell me how I should go about doing this. -
Django showing {% block title %} if {% content.meta_title %}
I need help with displaying django template block. In base.html I have block with default value. <title>{% block title %}Default Title{% endblock %}</title> In page.html I have if statement with a block inside. {% extends 'base.html' %} {% if homeContent.meta_title %} {% block title %}Title for this Page{% endblock %} {% endif %} Currently content.meta_title is None. However, in rendered html the title is shown as: <title>Title for this Page</title> I have tried to have different conditions like != '' or != None. But it still does not work. Please help me to find way around. I am confused. -
Email Verification Fail in Django webapp hosted on Elastic Beanstalk
I was making a web app on Django. I tried to send an email verification link to any new user who registers on my website. The thing works fine when I am hosting it on localhost but upon hosting on AWS Elastic Beanstalk the email verification shows an invalid token. models.py from django.contrib.auth.models import User from django.db import models # Create your models here. from django.utils.safestring import mark_safe class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) PINcode = models.IntegerField(blank=True, null=True) country = models.CharField(blank=True, max_length=50) image = models.ImageField(blank=True, default="Users/profile.png", upload_to='images/users/') def __str__(self): return self.user.username def user_name(self): return self.user.first_name + ' ' + self.user.last_name + ' [' + self.user.username + '] ' def image_tag(self): return mark_safe('<img src="{}" height="50"/>'.format(self.image.url)) image_tag.short_description = 'Image' forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django.forms import TextInput, EmailInput, Select, FileInput from user.models import UserProfile class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30,label= 'User Name :') email = forms.EmailField(max_length=200,label= 'Email :') first_name = forms.CharField(max_length=100, help_text='First Name', label= 'First Name :') last_name = forms.CharField(max_length=100, help_text='Last Name', label= 'Last Name :') class Meta: model = User fields = ('username', 'email','first_name','last_name', 'password1', 'password2', ) def __init__(self, *args, … -
Django, enabling html tag in the return value of admin.ModelAdmin class
For example, the code below. I want to use <pre> tag in the django's admin.ModelAdmin class MyJsonDataAdmin(admin.ModelAdmin): list_display = ['show_jsondata'] def show_jsondata(self,obj): temp = json.dumps(obj.jsondata, indent=2) return "<pre>" +temp + "</pre>" Is there any practice??? -
Postgres server does not support SSL, but SSL was required - CircleCI
I'm creating a build-test-deploy pipeline using CircleCI for a Django application. With image: circleci/postgres:13.1, the build fails with: psycopg2.OperationalError: server does not support SSL, but SSL was required ... ... django.db.utils.OperationalError: server does not support SSL, but SSL was required (Complete traceback here) As a workaround, I'm using this image, which has Postgres with SSL certificate. (Complete config.yml here) Is there a better way to this? Possibly with a CircleCI container image of more recent versions of postgres? I haven't found anything in the CircleCI documentation regarding this. -
django template "grouped" tag don't gives me the grouped records as I wan't
I'm working on a project on django, I'm using the built in view ArchiveListView, and I want to sort records to be grouped by a common attribute. So django ORM don't have a group by query, so I tried to do this on the template using regroup tag, but I think it take a long time and it doesn't give me the grouped record as I want this is the models I have : class Vehicle(models.Model): serie = models.CharField(max_length=18, unique=True, blank=True, null=True) matricule = models.CharField(max_length=18, unique=True, blank=True, null=True) ww = models.CharField(max_length=18,blank=True, null=True) marque_id = models.ForeignKey('Marque', blank=True, null=True, on_delete=models.SET_NULL) entry_into_service = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) mouchard = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) extinguisher = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text="extincteur expiratiOn date") city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL) driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL) class Meta: ordering = ['serie','matricule'] def __str__(self): return (self.matricule) class GazStation(models.Model): name = models.CharField(max_length=128, blank=True) city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) geo_localization = gis_models.PointField(blank=True, null=True) class Meta: ordering = ['city_id','name'] def __str__(self): return '%s %s' % (self.name, self.city_id.city) class Refuel(models.Model): vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL) driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL, limit_choices_to ={'is_driver':True}) Controlor_id = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='controlor_refuel', on_delete=models.SET_NULL, limit_choices_to ={'is_controlor':True}) … -
How to show search results of different models without refreshing the whole page
I have added search in my project but I am having a problem with one thing. When I write something in search field it returns me results of users, but when I click on tags to see tag results according to my search then my search text gets disappeares due to refresh or reloading of the page. I just want something by which my search stays there just like instagram. Here you can see I searched with the snap and got results of users and if I click on tags then it will show me tags results without again writing snap on search field for tags. I hope you understand what I'm asking for. -
WebSocket DISCONNECT after handshake with Django-EEL
I am trying to use EEL + Django. i found this solution in this GitHub link. I managed to make Django find the eel.js. but the issue it disconnect just after making WebSocket handshaking. as below:- You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, content types, sessions. Run 'python manage.py migrate' to apply them. January 31, 2021 - 17:22:47 Django version 3.1.5, using settings 'demo.settings' Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. HTTP GET /example/operations 200 [0.03, 127.0.0.1:57173] HTTP GET /eel/eel.js 200 [0.01, 127.0.0.1:57173] Not Found: /favicon.ico HTTP GET /favicon.ico 404 [0.01, 127.0.0.1:57173] WebSocket HANDSHAKING /eel [127.0.0.1:57177] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 160, in __call__ send, File "D:\Python Projects\V1830Center\venv\lib\site-packages\asgiref\compatibility.py", line 33, in new_application instance = application(scope) File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\generic\websocket.py", line 23, in __init__ super().__init__(*args, **kwargs) TypeError: object.__init__() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /eel [127.0.0.1:57177] Project Tree: Settings.py """ Django settings for demo project. Generated by 'django-admin startproject' using Django … -
maximum recursion depth exceeded in ElasticSearch document
My BookingDocument (Elasticsearch Document) has an object type field, visitor: class VisitorDocument(InnerDoc): id = Integer() name = Text() def __init__(self, id, name): self.id = id self.name = name class BookingDocument(Document): visitor = Object(VisitorDocument) .... def setVisitor(self, id, name): self.booked_by = VisitorDocument(id, name) ... When I try to save: document = BookingDocument(meta={'id':id}) document.setVisitor("Visitor Name", visitor_id) I get: RecursionError at /booking maximum recursion depth exceeded while calling a Python object I don't see any loop in this code, why am I falling into this recursion limit? -
Heroku error during Django website deployment
I'm still getting this error after all the steps follow trying to solve. Can anyone help me pls. this is the error obtained from my PowerShell: heroku ps:scale web=1 Scaling dynos... ! ! Couldn't find that process type (web). Scaling dynos... ! ! Couldn't find that process type (web). This is the content of my Procfile located in my root: ��web : gunicorn grouppublishingindia.wsgi --log-file - The error I'm getting from my browser: -
Populate textarea after submit form
I have a small form created with Django forms.Form, consisting of title and description. After "submit", if there was an error, I go back to the form page. I would like the description field (a textarea) to be filled in with the text written before the "submit". -
django cache manager method (with arguments)
So I have a few models and a manager like this. class Member(BaseModel): objects = models.Manager() permissions = api_managers.PermissionManager() box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE) roles = models.ManyToManyField('api_backend.Role', through='api_backend.MemberRole') REQUIRED_FIELDS = [box, user] class Role(BaseModel): objects = models.Manager() positions = api_managers.PositionalManager() name = models.CharField(default='new role', max_length=100, validators=[MinLengthValidator(2)]) permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True) is_default = models.BooleanField(default=False, db_index=True) position = models.PositiveSmallIntegerField(db_index=True, default=0) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE) REQUIRED_FIELDS = [name, box] class MemberRole(BaseModel): objects = models.Manager() member = models.ForeignKey('api_backend.Member', on_delete=models.CASCADE) role = models.ForeignKey('api_backend.Role', on_delete=models.CASCADE) REQUIRED_FIELDS = [member, role] class Overwrite(BaseModel): objects = models.Manager() allow = BitField(flags=permission_flags, null=True, blank=True, db_index=True) deny = BitField(flags=permission_flags, null=True, blank=True, db_index=True) channel = models.ForeignKey('api_backend.Channel', on_delete=models.CASCADE, editable=False) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE, editable=False) role = models.OneToOneField('api_backend.Role', on_delete=models.CASCADE, db_index=True) REQUIRED_FIELDS = [role, channel, box] from memoize import memoize class PermissionManager(models.Manager): def __init__(self): super().__init__() @transaction.atomic @memoize(timeout=3600) def get_overwrites(self, channel): assert channel.box == self.model.box, 'invalid channel given' permissions = self.get_base_permissions if channel.box.owner == self.model.user: return permissions try: # get the default everyone role's overwrite default_role = self.model.box.roles.get(is_default=True) default_overwrite = default_role.overwrite_set.get(channel=channel) except ObjectDoesNotExist: pass else: permissions &= set(~default_overwrite.deny) permissions |= set(default_overwrite.allow) member_role_ids = [role.id for role in self.model.roles.all()] overwrite_roles = channel.overwrites.filter(role__id__in=member_role_ids) deny, allow = None, None for overwrite in overwrite_roles: deny |= set(overwrite.deny) allow |= set(overwrite.allow) permissions …