Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Register an application automatically in Django OAuth Toolkit
Is there any way to register an Application Automatically in Django OAuth Toolkit? I have watched how register an user in Django OAuth Toolkit - Register a user and Application settings Django Oauth Toolkit Application Settings However, I did not find the way to create an Application when a User is registered, and create the Client ID and Client Secret automatically. In the documentation I only found it: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-3-register-an-application in Step3. -
POST method not allowed in django requests
I'm trying to call an API using django request.post but getting error 405 'Method Not Allowed (POST)' urls: path('ciu_consume/<str:br>/<int:qty>/', CiuConsumeView.as_view()) view: class CiuConsumeView(APIView): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get(self, request, br, qty): import pdb;pdb.set_trace() Response = requests.put('http://inv****.***.***.c***y.in/**/**/***/***/', data={'br': br, 'qty': 1}) return HttpResponse('Success') In this I'm getting error 404 If instead of 'def get()' I call 'def post' then also I'm getting same error. Really stuck on this. Any help for this will be helpful. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 6: invalid continuation byte
So this started when I upgraded my mint 19 to 20. The full error: Traceback (most recent call last): File "/home/notification/views.py", line 206, in get .select_related("history__definition") File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/models/query.py", line 653, in first for obj in (self if self.ordered else self.order_by('pk'))[:1]: File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1133, in execute_sql cursor.execute(sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 192, in execute return self._record(self.cursor.execute, sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/debug_toolbar/panels/sql/tracking.py", line 126, in _record return method(sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/sentry_sdk/integrations/django/__init__.py", line 469, in execute return real_execute(self, sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/MySQLdb/cursors.py", line 321, in _query self._post_get_result() File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/MySQLdb/cursors.py", line 355, in _post_get_result self._rows = self._fetch_row(0) File "/home/linuxbrew/.linuxbrew/opt/python/lib/python3.7/site-packages/MySQLdb/cursors.py", line 328, in _fetch_row return self._result.fetch_row(size, self._fetch_type) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 11: invalid continuation byte The … -
Django Ajax is not working in infinite scroll
I have posts page with infinite scroll. For every post there is a like button, which works via ajax. For first 3 posts like button is working (I have 3 posts defined in pagination options). But for another post, wich are loading with infinite scroll like button is not working. I found a similar questions and answers, but solutions there are not working in my case. I would be grateful for any suggestions. The view functions, displaing user's posts: def user_detail(request, pk): main = Main.objects.get(pk=1) user = CustomUser.objects.get(pk=pk,is_active=True) posts = user.posts_set.all().order_by('-created_at') paginator = Paginator(posts, 3) page = request.GET.get('page') supporters = CustomUser.objects.filter(team = user.team) try: posts = paginator.page(page) context = {'section': 'people','user':user, 'posts':posts, 'main':main,'supporters':supporters} except PageNotAnInteger: # Если переданная страница не является числом, возвращаем первую. posts = paginator.page(1) context = {'section': 'people','user':user, 'posts':posts, 'main':main,'supporters':supporters} except EmptyPage: if request.is_ajax(): # Если получили AJAX-запрос с номером страницы, большим, чем их количество, # возвращаем пустую страницу. return HttpResponse('') posts = paginator.page(paginator.num_pages) context = {'section': 'people','user':user, 'posts':posts, 'main':main,'supporters':supporters} if request.is_ajax(): return render(request, 'users/posts_ajax.html', context) return render(request, 'users/user-detail2.html', context) And the Ajax code for the infinite scroll and Like button: {% block domready %} //infinite scroll code var page = 1; var empty_page = false; var … -
return HttpResponse object as None
'''def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order= Order.objects.get(user=self.request.user , ordered = False) if form.is_valid(): use_default_shipping = form.cleaned_data.get('use_default_shipping') if use_default_shipping: address_qs = Address.objects.filter(user=self.request.user, address_type = 'S', default = True ) if address_qs.exists(): shipping_address = address_qs[0] else: messages.info(self.request, 'No default shipping address is available') return redirect('src:checkout') else: print('User is entering new shipping address') shipping_address1 = form.cleaned_data.get('shipping_address') shipping_apartment_address = form.cleaned_data.get('shipping_apartment_address') shipping_country = form.cleaned_data.get('shipping_country') shipping_zip = form.cleaned_data.get('shipping_zip') payment_option = form.cleaned_data.get('payment_option') if is_valid_fields(['shipping_address1','shipping_apartment_address','shipping_zip']): shipping_address = Address.objects.create(user=self.request.user, street_address=shipping_address1, apartment_address=shipping_apartment_address, country=shipping_country, address_type = 'S', zip=shipping_zip ) shipping_address.save() order.shipping_address = shipping_address order.save() set_default_shipping = form.cleaned_data.get('set_default_shipping') if set_default_shipping: shipping_address.default = True shipping_address.save() else: messages.warning(self.request, 'You need to fill the required fields') return redirect('src:checkout') use_default_billing = form.cleaned_data.get('use_default_billing') same_billing_address = form.cleaned_data.get('same_billing_address') if same_billing_address: billing_address = shipping_address billing_address.pk = None billing_address.save() order.billing_address = billing_address order.save() if use_default_billing: address_qs = Address.objects.filter(user=self.request.user, address_type = 'B', default = True ) if address_qs.exists(): billing_address = address_qs[0] else: messages.info(self.request, 'No default billing address is available') return redirect('src:checkout') else: print('User is entering new shipping address') billing_address1 = form.cleaned_data.get('billing_address') billing_apartment_address = form.cleaned_data.get('billing_apartment_address') billing_country = form.cleaned_data.get('billing_country') billing_zip = form.cleaned_data.get('billing_zip') payment_option = form.cleaned_data.get('payment_option') if is_valid_fields(['billing_address1','billing_apartment_address','billing_zip']): billing_address = Address.objects.create(user=self.request.user, street_address=billing_address1, apartment_address=billing_apartment_address, country=billing_country, address_type = 'B', zip=billing_zip ) billing_address.save() order.billing_address = billing_address order.save() set_default_billing = form.cleaned_data.get('set_default_billing') if set_default_billing: billing_address.default … -
How can I get the value of my select using Django into html?
Hello I have this code : <select name="test1" class="form-control"> <option value=""></option> {% for test in tests %} <option value="{{ test.id }}">{{ test.name }}</option> {% endfor %} </select> I would like to know how can I do to get the value of my select using django I mean I would like to have someting {{ value_selected }} Thank you very much -
filters package in django giving an error
I'm trying to add a filter function for my project. But I have been getting this error " line 281, in get_fields assert not (fields is None and exclude is None), \AssertionError: Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed. Add an explicit 'Meta.fields' or 'Meta.exclude' to the OrderFilter class." I have tried searching for a solution, but those solutions couldn't solve it. filter.py import django_filters from .models import Order class OrderFilter(django_filters.FilterSet): class Meta: model = Order fileds = ['status', 'date_created', 'manu_date'] views.py def order_list(request): if request.user.is_superuser: order_list = Order.objects.all() paginator = Paginator(order_list, 10) else: order_list = Order.objects.filter(user=request.user) paginator = Paginator(order_list, 10) page = request.GET.get('page') try: order = paginator.page(page) except PageNotAnInteger: order = paginator.page(1) except EmptyPage: order = paginator.page(paginator.num_pages) myFilter = OrderFilter(request.GET) context = { 'object_list':order, 'order': order, 'myFilter':myFilter } return render(request, "order_list.html", context) order_list.html <form method="get"> {{myFilter.form}} </form> settings.py INSTALLED_APPS = [ 'django_filters', ] -
Mongoengine Django Custome User Authentication
I am trying to handle my authentication and user system, with django restframework, using mongodb as my database. I've searched the whole internet for a good sample of code for my purpose to work. But you may know that any article which is published in this issue doesn't work and you have so many errors while running the code. does anyone know a good piece of code or an article that may help? -
How can I get an id from a JSON response in jsGrid?
I have a jsGrid that has rows of products. I have a button that adds a product to the cart but this button needs a product id. How can I get the product id? $(function() { $('.jsGrid').jsGrid({ height: "500px", width: "50%", filtering: true, sorting: true, paging: true, autoload: true, pageSize: 10, pageButtonCount: 5, deleteConfirm: "Do you really want to delete client?", controller: { loadData: function(filter) { var d = $.Deferred(); $.ajax({ url: "{% url 'shop:get' %}", type: "GET", dataType: "json", data: filter, }).done(function(response) { var fields = []; for (let i = 0; i < response.length; i++) { fields.push(response[i].fields); } d.resolve(fields); }); return d.promise(); } }, fields: [{ name: "name", title: "Наименование", type: "text", width: 100 }, { name: "prime_cost", title: "Себестоимость", type: "number", width: 100 }, { name: "sell_price", title: "Цена для продажу", type: "number", width: 100 }, { name: "stock", title: "На складе", type: "number", width: 100 }, { type: "control", width: 100, editButton: false, deleteButton: false, itemTemplate: function(value, item) { var $result = jsGrid.fields.control.prototype.itemTemplate.apply(this, arguments); var $customButton = $("<button>").attr({ 'data-target': "#exampleModal", 'data-toggle': 'modal', class: 'cartAdd' }).on('click', function() { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let td = $(this).parents('td'); let productID = td.children('.product_id').val(); console.log(data); $('#product_id').val(productID); }); return $result.add($customButton); }, }] … -
Django forms sends invalid HTML sytnax | invalid form
I have a Django project where I use the integrated forms. But it sends my client wrong HTML syntax. This shouldn't be that big of a deal since browsers nowadays clean up such errors. But when the form gets send back to the server the form isn't able to validate because firefox sends back the cleaned version. I have a form with an multiple select: class ProjectForm(forms.Form): # [...] project_leaders = forms.ModelChoiceField(widget=forms.SelectMultiple, queryset=User.objects.all(), initial=0) This form is integrated in the respective html file: {{ project_form.as_p | linebreaks }} This is the source code from it (via Firefox Page Source): <p>[...] <select name="project_leaders" required id="id_project_leaders" multiple><br> <option value="test">test</option></p> <p></select></p> Firefox cleans it up oc but it should be send and accepted by django. Does anybody know how I can django to do that? -
Django admin - extend mode edit page
I have a problem extending a djnago admin page. I already did this for email templates and the index admin and it worked fine, but i can not extend it for a specific model. Currently i have copied the file i want to extend everywhere but still it wont load anything on the edit option. This is how my folder structure looks. This is my "code" inside change_form.html {% extends "admin/change_form.html" %} {% load static %} <p>AAAAAAAAA</p> Im following documentation from: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/ But obviously I'm missing something -
How to return Django response from nested function?
Let say I want to test several data before proceeding and if it fails return an error response directly to the person who made the request. I have this: def gerUserInfo(request): if request.user.is_authenticated: data = json.loads(request.body.decode('utf-8')) info1 = data.get("info1") if data.get("info1") else "" if info1.strip() == "": JsonResponse({"status":"fail"}) else: #proceed... info2 = data.get("info2") if data.get("info2") else "" if info2.strip() == "": JsonResponse({"status":"fail"}) else: #proceed... ... I want this: def gerUserInfo(request): def secureGetData(data): try: data = data if data else "" if data.strip() == "": JsonResponse({"status":"fail"}) else: return data except: JsonResponse({"status":"fail"}) if request.user.is_authenticated: data = json.loads(request.body.decode('utf-8')) info1 = secureGetData(data.get("info1")) info2 = secureGetData(data.get("info2")) ... # i can proceed with out worring... I want the server response the request from secureGetData(), but never do. -
How can I create a if using the value of select?
Hello I have the following code : <select name="test1" class="form-control"> <option value=""></option> {% for test in tests %} <option value="{{ test.id }}">{{ test.name }}</option> {% endfor %} </select> Then I want to do something like this ; {% if test.id %} => I think the problem comes from this line, in fact I want this condition is realised if test.id is not empty else the condition is not realised. {% endif %} How can I do this ? -
slug path is breaking swagger structure
When I add the last url to my project/urls.py file, my structure in swagger is completely gone. This started to happen when implementing NamespaceVersioning. I'm using drf-yasg - Yet another Swagger generator for swagger. urlpatterns = [ # alphabetically ordered for faster lookup path("api/v1/", include("backend.api.v1", namespace="v1")), path("api/v2/", include("backend.api.v2", namespace="v2")), path("<slug:integrator>/", include("backend.integrators_urls"),), ] This is my structure without the slug (for v1) This is the structure if I add the slug path: -
How can I restrict django PasswordResetView from redirecting to PasswordResetDoneView after submission of email?
I don't want to redirect to PasswordResetDoneView after submitting the form in PasswordResetView instead I want to show a small modal in the PasswordResetView itself. How do I restrict from redirecting to PasswordResetDoneView? -
Django: Stop redirecting URL to another page
For some reason in my Django app I used a redirect path as in my urls.py file, such that whenever someone visits example.com they would be redirected to example.com/blog urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), path('', lambda request: redirect('blog/', permanent=True)), ] Now I have constructed my site fully and added views for example.com. In order to visit that page I removed the line that redirects path from my code base so that it no longer redirects to /blog whenever I try to visit example.com. path('', lambda request: redirect('blog/', permanent=True)) But the problem is that I'm still being redirected to /blog even after removing that above line. I think it is happening due to some thing related with permanent=True. Any help would be appreciated in reversing that effect. Thanks in advance. -
Django API Testing : csrf exempt
I'm getting a "Forbidden (CSRF cookie not set.): /user/admin/sign-up" error whenever I test class based views. When I change those views to functional based views with @csrf_exempt on top of the function declaration, it works. Postman POST Request: localhost:8000/admin/sign-up body : {'email' : 'email@gmail.com', 'password' : 123123} URL path patterns: ... path(‘/admin/sign-up’, views.AdminSignUpView), ... Views.py @csrf_exempt def token_verification(request,**kwargs): if request.method == “POST”: id = kwargs.get(‘id’) token = kwargs.get(‘token’) user = User.objects.get(id = id) redirect_url = ‘/eval/intro’ is_valid = user_activation_token.check_token(user,token) if is_valid: user.is_active = True user.save() return HttpResponseRedirect(redirect_url,status = 200) else: return HttpResponse(status = 403) class AdminSignInView(View): @csrf_exempt def post(self,request): data = json.loads(request.body) try: if User.objects.filter(name = data[‘email’]).exists(): user = User.objects.get(name=data[‘email’]) if bcrypt.checkpw(data[‘password’].encode(‘utf-8’),user.password.encode(‘utf-8’)): token = jwt.encode({‘email’:data[‘email’]}, SECRET, algorithm = HASH).decode(‘utf-8’) return JsonResponse({ ‘token’ : token }, status = 200) return JsonResponse({ ‘message’ : ‘INVALID_USER’ }, status = 401) return JsonResponse({ ‘message’ : ‘INVALID_USER’ }, status = 401) except KeyError: return JsonResponse({ ‘message’ : ‘INVALID_KEYS’ }, status = 400) class AdminSignUpView(View): @csrf_exempt def post(self,request): try: data = json.loads(request.body) if not User.objects.filter(email = data[‘email’]).exists: password = bcrypt.hashpw(data[‘password’].encode(‘utf-8’),bcrypt.gensalt()) crypted = password.decode(‘utf-8’) User.objects.create( name = data[‘name’], password = bcrypt, email = data[‘email’], auth_id = data[‘auth_id’] ) return HttpResponse(status = 200) except KeyError: return JsonResponse({ ‘message’ … -
Django query list of characters from a Many-to-Many related Model
I am trying to get a list of names from a model that has a many-to-many relationship with my user model. Here is the model # models.py class AvailableTime(models.Model): time = models.TimeField() class CustomUser(models.Model): available_times = models.ManyToManyField('AvailableTime', blank=True) When I perform a query like this, the server returns the following list to the client # views.py doctor_list = User.objects.all().values('available_times__time') return JsonResponse({'doctor_list': list(doctor_list}, status=200) { "id": 30, "first_name": "Doctor", "last_name": "Test", "available_times__time": "9:00", }, { "id": 30, "first_name": "Doctor", "last_name": "Test", "available_times__time": "9:00", }, Is there a way to return a list of available_times instead of returning two separate objects? -
how to set tabindex for django autocomplete?
in my forms I have some fields (name, places and job). Places is a foreign key. so i used autocomplete for that field. if I press tab after entering name the cursor moves to the autocomplete. after choosing the place when I press the tab key it moves to the search bar in the theme. i guess its because of the tab-index of autocomplete is -1. Then for the second thoughts, if that's the reason the cursor wouldn't have moved to the autocomplete, right? any way I gave that search input tabindex = -2 . this time the cursor moved to the logo which is a link to the homepage then to the next a tag. After some more tabs I finally reached to the beginning of the form. how can I solve this problem -
Django celery periodic task interval change is not updating in database
I'm using Django 2.2 and Celery's periodic task to create a cron job which was earlier set to run at an interval of 2 hours like @periodic_task(name='authentication.periodic_task.custom', run_every=timedelta(hours=2)) Now, I changed it to run every day at 2 PM instead of running every two hours and updated schedule is @periodic_task( name='authentication.periodic_task.custom', run_every=crontab(hour=2, minute=0) ) Replace timedelta with crontab but the task is still executing every 2 hours. When I checked the Django admin, it has a listing in Periodic Tasks table with the following data Why the change in the period in the code is not updated in the database? -
Django url pattern is not not detected in js file
I'm using main.js file for java script logic in Django project. When i'm writing this logic inside script tag in base.html, it's working as expected. But, if I separate the logic in .js file, i'm getting Uncaught SyntaxError: Unexpected token '% by pointing url : {% url 'like-post' %}, in browser console. base.html: <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://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'blog/main.js' %}" type="text/javascript"></script> <title>Blog</title> </head> main.js: $(document).ready(function(event){ $(document).on('click', '#like', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type : 'POST', url : {% url 'like-post' %}, data : {'id' : pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : 'json', success : function(response){ $(".like-section").load(" .like-section") }, error : function(rs, e){ console.log(rs.responseText); }, }); }); }); I have few other js logic in main.js file, it's working as expected if i comment out above portion in main.js file. -
Islamic Black Magic Spells on Clothes for Lost Love Back
Love marriage Specialist basheer khan is give the solution for all your love, family, marriage, business, money, relationship, career and etc. problems solution. basheer khan says that when there is astrological movement in the planer position they will effect the life of persons that can be negative or positive. They use power of Mantra and Yantra to control a person’s mind, thoughts, action and behavior. You No Need To Worry About Your Matter .basheer khan Will Surely Help You . Email : basheerkhanji786@gmail.com https://lovespellsfree.wordpress.com/ Call us : +91-8741836760 WhatsApp : +91-8741836760 -
No installed app with label 'dappx' error Django
I want to migrate 'dappx'. When trying to do so however I get the error that there is no installed app with label 'dappx' The maps and project are made as follows and all works fine (denvx) C:\Users\ MyPath\djangox>django-admin startproject dprojx (denvx) C:\Users\ MyPath\djangox>cd dprojx && django-admin startapp dappx (denvx) C:\Users\ MyPath\djangox\dprojx>mkdir templates media static media\profile_pics templates\dappx (denvx) C:\Users\ MyPath\djangox\dprojx>python manage.py migrate However when I try to migrate dappx I get the error that dappx does not exist. (denvx) C:\Users\ MyPath\djangox\dprojx>python manage.py makemigrations dappx No installed app with label 'dappx'. how would I go about fixing this? -
Group and Permissions Assignment Missing when using Custom User Model
I am building an app with multiple roles defined through Django Groups. I started with a custom user model, defined as below from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser, BaseUserManager, PermissionsMixin import random import string from slugify import slugify # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("You must have an email address") user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), ) user.set_password(password) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user #custom user account model class User_Account(AbstractUser): email = models.EmailField(verbose_name='email', max_length=60, unique = True) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) username = models.CharField(max_length=100, null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyAccountManager() def __str__(self): return self.email When I create a new group with the custom user model, the group gets automatically assigned to all created users. I reproduced this behavior both programmatically and through the Django Admin. When I use the default user model the group creation doesn't assign groups to all users automatically. I also discovered that when using a custom user model the Django Admin … -
How to use logical operators in DRF's DEFAULT_PERMISSION_CLASSES?
Since DRF==3.9--(release notes) we have got an option to combine/compose the permission classes in our views. class MyViewSet(...): permission_classes = [FooPermission & BarPermission] I did try something like this, REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'utils.permissions.FooPermission' & 'utils.permissions.BarPermission', ), # other settings } and python raised exception TypeError: unsupported operand type(s) for &: 'str' and 'str' So, How can I use combined permission as global permission using DEFAULT_PERMISSION_CLASSES ?