Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DataTables: Retain rows/data even after page refresh
I am using DataTables version 1.10.20 in my Django project. I have two DataTables in a page, one for Products and another for Cart. The data in Products table is sourced by AJAX call. The user will add the products from products table to cart table by clicking on a add button. User should be able to modify the quantity in the cart table and when satisfied, finally click on a checkout button. The checkout button will call some view for next steps to save the transaction. The problem is, before clicking on checkout, if the user refreshes the page after adding a couple of products or navigates to a different page, the Cart DataTable is loosing all the data and the user will have to add them all over again. The data in Cart DataTable should be only cleared when "Checkout" is clicked. Is this possible ? I have tried using StateSave: true as documented here but it did not help. Here is my code.. DataTable for "Products" <script defer type="text/javascript" language="javascript" class="init"> // This function will initialilize the 'Products' datatable. $(document).ready(function () { $('#productstable').dataTable({ "ajax": { "url": "{% url 'getproductsdata' %}", "dataSrc": '' }, // Datatable customization options … -
Retrieving pdf file when converted from docx
I have a web app that has a feature of converting docx documents to pdf.I am using Python/Django on Ubuntu server and for conversion i am using lowriter. My code is: args = ['lowriter', '--convert-to',' pdf ','/path/input.docx'] p = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE) Everything works fine when downloading the pdf, but i want to process the pdf created in python before downloading it, so i need to retrieve the pdf in code but it doesn't seem to save it in the folder '/path/'. Do you have any idea why it doesn't save it or what i can do? -
How to select related with existing object in Django?
I have existing user object that have many-many fields through select_related and prefetch_related: user = models.User.objects.first().select_related(...).prefetch_related(...) I need to select articles of this user through Article model (no user.article_set): articles = models.Article.objects.filter(user=user) And i want articles to have the existing user object, for example: articles = models.Article.objects.filter(user=user).select_related(user) or articles = models.Article.objects.filter(user=user).annotate(user=user) How is this possible to do? -
AttributeError: Got AttributeError when attempting to get a value for field `user` on serializer `RegisterSerializer`
I am trying to Register a User using a Serializer.I hava UserSeriaizer in RegisterSerializer, thought the user is created and able to access serializer.validated_data but i am not able to access serializer.data Here is my serializer classes: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'email', 'password'] extra_kwargs = { 'id' : {'read_only' : True}, 'password' : {'write_only' : True} } class RegisterSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Token fields = ['user', 'key'] extra_kwargs = { 'key' : {'read_only' : True} } depth=1 def create(self, validated_data): user = User.objects.create_user(**validated_data['user']) user.is_active = False token = Token.objects.create(user = user) user.save() return(user) And the View is : serializer_class = RegisterSerializer(data={'user' : request.data}) try: serializer_class.is_valid(raise_exception = True) except Exception as e: return(Response(serializer_class.errors, status=404)) else: user = serializer_class.save() print(serializer_class.data) Models are as follows: class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=15, unique=True) first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=254, unique=True) password = models.CharField(max_length=254) #is_active = models.BooleanField(default=True) #is_admin = models.BooleanField(default=True) USERNAME_FIELD = 'username' objects = UserManager() def __str__(self): return self.username and the Token is created using 'from rest_framework.authtoken.models import Token' -
UWSGI log to multiple locations
I'm a bit new to uwsgi so this may be a dumb question, I'm trying to get uwsgi to write logs to multiple locations and have not been able to find a way to do this. I'm want to setup uwsgi so it writes to both my logfile (/tmp/uwsgi.log) and stdout (so I can see it in the logs in my k8s pod). But I can't get both to work. I can only get one or the other to work. Here is my uwsgi.ini file: [uwsgi] root = %d/../test chdir = %(root) module=test.wsgi:application socket=/tmp/uwsgi_test.sock master=True pidfile=/tmp/uwsgi_test.pid vacuum=True max-requests=2000 logto=/tmp/uwsgi.log chmod-socket = 666 vacuum = true processes = %(%k * 4) enable-threads = True single-interpreter = True limit-as = 4056 buffer-size=65535 stats=/tmp/uwsgi_test_stats.sock Running this uwsgi file with /opt/conda/bin/uwsgi --ini /home/docker/uwsgi/k8s-sandbox-webserver.ini sends log files to only /tmp/uwsgi as specified by the logto parameter in the uwsgi.ini. If I remove the logto parameter completely then the logs only go to stdout. How can I make these uwsgi logs appear in both stdout and /tmp/uwsgi.log? So far I've tried logto2 and and daemonize so far but haven't had any luck with getting those to work for this purpose. -
How do I Upload a file using Django Rest Framework?
While posting file in the form, the 415 error is thrown detail: "Unsupported media type "application/json;charset=UTF-8" in request. serializer: class PrescriptionSerializer(serializers.ModelSerializer): class Meta: model = Prescription fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['medicine'] = MedicineSerializer( Medicine.objects.get(pk=data['medicine'])).data data['doctor'] = DoctorSerializer( Doctor.objects.get(pk=data['doctor'])).data if(data['address_of_opd'] != None): data['address_of_opd'] = AddressSerializer( Address.objects.get(pk=data['address_of_opd'])).data else: data['address_of_opd'] = {} return data ViewSet: class PriscriptionViewSet(viewsets.ModelViewSet): queryset = Prescription.objects.all() permission_classes = [ permissions.AllowAny, ] serializer_class = PrescriptionSerializer What am I missing in here? -
How do I let my django server print a receipt using my client's printer?
I'm working on a web application that allows users to add items to their cart. What I want to do is to print the items in the cart to a kitchen impact receipt printer on my clients side (I'm using the TM-U220 Receipt Printer). Currently, I am using my own computer to run the server but in the future, I hope I can get it working online so anyone can visit the website. I can't seem to find any solution on how to do that and if it is possible? I've only recently started Django and I can't seem to find a good solution. Any tips, help or idea on how to writing data to the printer on the client side from Django server? -
Like button back end logic using Django Rest Framework
I have a Blog app where users can add new Post and any users can like the post. models.py class Post(models.Model): title = models.CharField(max_length=60) class PostLikes(models.Model): likeusers = models.ManyToManyField(User) likepost = models.ForeignKey(Post,on_delete=models.CASCADE,null=True,related_name='likepost') serializers.py class PostSerializers(serializers.ModelSerializer): #likepost = serializers.SerializerMethodField() **I have to mention like count here** class Meta: model = Post fields = '__all__' class PostlikeSerializer(serializers.ModelSerializer): class Meta: model = PostLikes fields = '__all__' views.py class LikeListCreate(APIView): def get(self,request,pk):#function to get total number of likes to particular post post = Post.objects.filter(pk=pk) # find which post's likes are to be extracted like_count = post.likepost.count()# counts total user likes ,besides my code is wrong serializer = PostlikeSerializer(like_count,many=True) return Response(serializer.data) def post(self,request,pk):#function to add likes to post # how do I check if user is already liked the post ? likeusers = request.user likepost = Post.objects.filter(pk=pk) serializer = PostlikeSerializer(data=request.data) if serializer.is_valid(): serializer.save(likeusers,likepost) return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) urls.py path('posts/<int:pk>/like/',LikeListCreate.as_view(),name = 'post_likes'), I am unable to implement logic in views.py module and serializers.py section too. Please help, thanks in advance Git link to my project https://github.com/Anoop-George/BlogApp.git -
Unable to display image in template (Django 3.0)
Unable to display profile_pic image in template I know i m doing something very terrible. model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True) def __str__(self): return self.user.username index.html {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Django Level Five</h1> {% if user.is_authenticated %} <h2>Welcome {{ user.username }}!</h2> <div> <img src="{{ user.profile_pic.url }}" alt="user-image"> </div> {% else %} <h2>Welcome to the site!</h2> {% for b in users %} {% endfor %} {% endif %} </div> </div>{% endblock %} views.py def index(request): #commented: userpro = UserProfileInfo() #commented: var={'userz': userpro} #commented: return render(request, 'basic_app/index.html',context=var) return render(request, 'basic_app/index.html') User authentication is fine and name is getting displayed in template but not the image. I have tried lot of things but image didn't show. Div and Alt-name getting displayed but not the profile_pic. -
if comment.name == user not working correctly
I want users to be able to delete comments they have written. Unfortunately though I can not get the if statement to work. {% if comment.name == user %} <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I could see the value of user and comment.name I included the below code. This was for testing purposes and would not be included in the sites final design. <h3 class="article-content">{{ user }}</h3> <p class="article-content">{{ comment.name }}</p> I also wanted to test to make sure the inside of the if statement was work. <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I included the below code. Again this would not be included in my final sites design. {% if post.author == user %} <a href="{% url 'delete_own_comment' comment.id %}">-------delete this comment---------</a> {% endif %} But by looking at the screenshot you can tell the code is not working properly. The 30th comment is a 'Test comment for StackOverflow purposes.' The comment was written by RossSymonds. The user currently logged in is RossSymonds. If everything was working properly you would see 'delete this comment' (which is different to '------delete this comment---------'). Does anyone have a suggestion? … -
How to access related model object in vuejs component with django rest framework
I am building a full-stack web application, using Django, Django Rest framework and Vue.js as the frontend. I am working with a Post model that has an author column, which is related to the Django User model by foreign key, like so; class Post(models.Model): title = models.CharField(max_length=50, unique=True) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) I have set up my serializers, viewsets and the urls like so; serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username', 'email'] class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ['url', 'title', 'body', 'author'] In my vews.py; class UserViewSets(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class PostViewSets(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer In my urls.py; router = routers.DefaultRouter() router.register('users', UserViewSets) router.register('posts', PostViewSets) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] I can access my Post model on the rest framework console on my browser. Now in my Vuejs component, i can also get the list of my posts if i make a request to the post api endpoint i.e. http://localhost:8000/posts. However, i also want to get the related model, i.e User (the author of individual post), as an object so i can do something like post.author.username or post.author.email … -
Pytest django - Multiple application, multiple database - not able to access any DB other than default db
Problem I have a Django(1.8) project running 2 applications: App1, App2. Both of the applications run with their own databases: app1db and app2db, sharing the defaultdb for users and groups. I am trying to integrate pytest-django as part of the unit testing. This is where I am hitting with problem as Pytest do not support multiple databases. My use case is I would be needing the unit tests only on app1 and I am pretty much sure I won't be needing it on app2. And I can mock my users and groups objects from defaultdb for this unit tests and I won't be needing access to defaultdb. But the problem is I always see the unit tests access the defaultdb and I don't see a way of making the app1db accessible from unit test cases. When I try to access any object form app1db, I get the following error: E ProgrammingError: relation "app1_table" does not exist E LINE 1: INSERT INTO "app1_table" ("field1", "field2", "... E ^ Database Settings 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'defaultdb', 'PASSWORD': 'pass', 'HOST': localhost, }, 'app1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app1db', 'USER': 'postgres', 'PASSWORD': 'pass', 'HOST': localhost, }, "app2": { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': … -
Django Management Command - Write All or Nothing
I have a django custom management command. This is how the handle and other methods in BaseCommand looks: def first_function(data_point): another_model = AnotherModel(data=data, related_data= data_point) another_model.save() def second_function(data_point): yet_another_model = YetAnotherModel(data=data, related_data= data_point) yet_another_model.save() def handle(self, *args, **options): data_cursor = DataPoint.objects.filter(ready_for_migration=True) for data_point in data_cursor.iterator(): with transaction.atomic(): self.first_function(data_point) self.second_function(data_point) data_point.complete=True data_point.save() sleep(20) raise Exception("Testing Exeception") I expect the AnotherModel, YetAnother Model table to be loaded and after Exception is raised I want the data that was loaded in the respective tables to be erased. Instead what I am observing is that the tables get loaded fine, the exception is thrown but after the execption, the data remains in the table. Essentially I want all the related data for a given data point to be loaded but if any of the related tables fail, the transaction for the data point should rollback. What am I missing? -
Receiving 'TypeError: expected string or bytes-like object' when saving object
I have an issue with uploading data from excel to a db using Django. When this function runs, it is suppose to get the data in specified range and upload it to db when 'q.save' is ran. def scrapeExcel(excel): uploadQuery = [] wb = load_workbook(excel) for sheet in wb.worksheets: last_row = sheet.max_row if sheet == wb.worksheets[0]: fullName = sheet.cell(row = 16, column = 4).value for row in sheet.iter_rows(min_row = 20, max_row = last_row - 1): curRow = [] for cell in row: curRow.append(cell.value) uploadQuery.append( time( file = excel, fullname = fullName, cdate = get_date(curRow[3]), dayname = curRow[4], units = curRow[9], submitteddate = get_date(curRow[11]), approveddate = get_date(curRow[15]), project = curRow[21], name = curRow[22], comment = curRow[25], locationname = curRow[26], status = 1 ) ) for q in uploadQuery: q.save() When I run this, it gives me the following error. TypeError: expected string or bytes-like object When I checked each value via print or sys.stderr.write, I know they are getting the right value. But inside the for loop, if I check what q is, with for q in uploadQuery: sys.stderr.write(' query--{} '.format(q)) q.save() it just says query--time Object (none) So I am assuming, it is not getting appended to uploadQuery? or is … -
How do I access Django running on a Google Compute Engine VM from my browser?
I have a Django dashboard application I wish to view from my browser. Django is running in a Docker container on one of Google's Compute Engine instances. The GCE instance is on a Google VPC, on which I've added firewall rules to open Django's port 8000. I've added my IP to Django's ALLOWED_HOSTS in settings.py. The container's logs indicate that it is running fine, yet when I access the GCE instance's IP from my browser, I am immediately unable to connect. I can ping the instance from my command line just fine. Is there something I'm missing here? Been stuck on this for a few hours now. Note: I have the Django container running on a "Docker network" in order for Celery to communicate with a RabbitMQ container. This was recommended to me somewhere, but I am unfamiliar with Docker networks or if they are causing the issue. -
how to create a monthly array between two dates in django?
I have a model that have the following input: monthly income: 100 start date: 31/03/2020 (created with DateField) end date: 24/7/2020 (created with DateField) I want to obtain the following QuerySet: [0, 0, 100, 100, 100, 100, 100, 0, 0, 0, 0, 0] that is the 12 months and the respective income amount. -
Use text input for ModelChoiceField in Django
I'd like to be able to have a user change which product is on a specific line item of an order. Here is my model: class OrderLineItem(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='details') product = models.ForeignKey(Product, on_delete=models.CASCADE) price_before_discounts = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) discount = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) has_applied_discount = models.BooleanField(default=False) total = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) line_number = models.IntegerField(default=1) added_by_promotion = models.ForeignKey('Promotions.CouponRedemption', on_delete=models.CASCADE, blank=True, null=True, default=None) substitute = models.ForeignKey(Product, related_name='substitute', on_delete=models.CASCADE, blank=True, null=True, default=None) The only field I am trying to change is the substitute field. Here is my form: class OrderDetailSubstitutionForm(ModelForm): substitute = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput, required=False) def __init__(self, *args, **kwargs): super(OrderDetailSubstitutionForm, self).__init__(*args, **kwargs) self.fields['substitute'].widget.attrs.update({'class':'form-control text-center','style':'width:100%'}) self.fields['substitute'].label = "" class Meta: model = OrderLineItem fields = ('substitute',) Because there are around 400 products in the database, the page takes a long time to load when there are more than a small amount of line items. So instead of using a select widget, I'd like to be able to allow a user to enter a product's SKU, and then do a lookup and get the appropriate product id, or raise a validation error if it can't find anything. I've tried overriding the clean method to do this lookup, … -
I am having issues with nested serializers in django
from rest_framework import serializers from .models import UsersMan from log.serializers import LogSerializer from log.models import Log class UserSerializer(serializers.ModelSerializer): class Meta: model = UsersMan fields = ("s_no","user_id","name","time_zone") class UserLogSerializer(serializers.ModelSerializer): #members = serializers.SerializerMethodField(source="UsersMan", read_only=True) activity_periods = serializers.SerializerMethodField(source="Log", read_only=True) class Meta: model = UsersMan depth = 1 fields = ("s_no", "user_id", "name", "time_zone","activity_periods",) -
AttributeError: _auto_id_field Django with MongoDB and MongoEngine
I am using mongoengine with Django Below is my Model class class MyLocation(EmbeddedDocument): my_id = IntField(required=True) lat = GeoPointField(required=False) updated_date_time = DateTimeField(default=datetime.datetime.utcnow) My Views.py def store_my_location(): loc = MyLocation(1, [30.8993487, -74.0145665]) loc.save() When I am calling the above method I getting error AttributeError: _auto_id_field Please suggest a solution -
How do I use column data for function calls in a Django filter?
I'm trying to filter a Django QuerySet with the following: result_queryset = result_queryset.filter( start_datetime__gte=datetime.now(F("<foreign__key>__timezone")) ) I'm comparing the start_datetime of a record and checking if it's greater than or equal to the current time localized to a timezone, which is a column in the model. But this results in the error: graphql.error.located_error.GraphQLLocatedError: tzinfo argument must be None or of a tzinfo subclass, not type 'F' I understand that this is because F is not being evaluated as it's a SQL expression. The question is: How do I get the actual value of the timezone column so that I can use it in datetime.now() inside of the filter? -
How do I get linebreaks to show the blank line between paragraphs in Django?
I'm trying to get text from a blog to show on my html page similar to how it shows in the Django admin. I've used both linebreaks and linebreaksbr and the following happens. What the Django admin shows (and how i'd like it to show as paragraphs): This is a test - sentence 1. This is the second sentence after a line break. This is the code I have that renders it out on the page: {% for post in posts %} {% if post.published %} {{ post.title }} Created by: {{ post.author }} on {{ post.published_on }} {% if post.has_been_updated %} Updated by: {{ post.author }} on {{ post.updated_on }} {% endif %} {{ post.body|linebreaksbr }} {% endif %} {% endfor %} This is how it shows on the page:Second sentence on new line without line in between On a side note, if I use linebreaks instead of linebreaksbr it will cancel out all of my CSS code. The CSS code only works with linebreaksbr. -
IntegrityError at /profiles/author/post - NOT NULL constraint failed: profiles_tweet.author_id
NOT NULL constraint failed: profiles_tweet.author_id I want to save the tweet with state pending , but it gives Integrity error . And also I want to view all tweets of author but Iam not able to filter . I want that if any author tweet something is stored as pending in database . and I want it to view in his profile . From models.py class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USER_TYPE_CHOICES = ( ('AUTHOR', 'author'), ('EDITOR', 'editor'), ('PUBLISHER', 'publisher'), ('SUPERVISOR', 'supervisor'), ('ADMIN', 'admin'), ) user_type = models.CharField(choices=USER_TYPE_CHOICES,max_length=64, default='student') favorite_color = models.CharField(max_length=50) bio = models.TextField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['favorite_color'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class Tweet(models.Model): author = models.ForeignKey(MyUser,on_delete=models.CASCADE) text = models.CharField(max_length=140) # author_email = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) published_at = models.DateTimeField(null=True) STATE_CHOICES = ( ('pending','pending'), … -
Django url cannot be found after editting urlpatterns
I'm playing with Django python tutorial and notice a very odd url behavior. My project name is 'mysite', and in its urls.py, it by default has from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] This shows that little rocket base page when I visit localhost:8000. Then I editted like following, from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('student/', include('student.urls')) ] to indicate a new url for my own app, this time the base page localhost:8000 returns a 404. I'm very curious why my new line will affect the base page? BTW my django version is 3.0.6. -
django submit not woking (only returning me csrf tokenvalues)
I had made a form in which I have 3 buttons Out of those 3 buttons, last button is for submit which only return me CSRF value here's my code teacher-profile.html <form name="get_teacher_data" method="post"> {% csrf_token %} <div class="card"> <div class="card-body"> <h2 class="card-title border-bottom pb-3">Go through the following paragraph to fill up some valuable information</h2> <p class="card-text"> I <input id="teacher_name" type="text" placeholder="name of teacher" class="form-control" style="width:auto;display:inline;" disabled> currently gives lecture for students of <select class="selectpicker" data-live-search="true" name="branch" id="branch" title="branch" multiple> <option>B.Tech</option> <option>M.Tech</option> <option>Ph.D</option> </select> at <input id="institute_name" type="text" placeholder="name of institute" class="form-control" style="width:auto;display:inline;" disabled> <div class="card"> <div class="card-body"> <table class="table table-hover"> <thead> <tr> <th scope="col">Semester</th> <th scope="col">Section & Room No</th> </tr> </thead> <tbody> <tr id="row1"> <td> <select class="selectpicker" id="semester1" title="semester" name="semester"> <option>I</option> <option>II</option> <option>III</option> <option>IV</option> <option>V</option> <option>VI</option> <option>VII</option> <option>VIII</option> <option>ALL</option> </select> </td> <td> <div class="form-row"> <input id="section1" type="text" name="section" placeholder="section" class="form-control" style="width:auto;"> <input id="room_no1" type="text" name="room_nos" placeholder="room no" class="form-control" style="width:auto;"> </div> <button id="add_sec" class="btn btn-light" type="button">Add more sections</button> </td> </tr> </tbody> </table> </div> <div class="card-footer"> <button id="add_sem" class="btn btn-danger" type="button">Add more semester</button> </div> </div> </p> </div> <div class="card-footer"> <button id="save" class="btn btn-primary" type="submit" for="get_teacher_data">Save</button> </div> </div> </form> my view def get_teacher_data(request): if request.method == 'POST': val = (request.POST) print(val) return … -
Add select_related() to Django Authentication backend
In my project I have both Group and Custom User Based Permissions. I have a custom authentication backend which essentially checks to see if the user has group permissions and then sees if they have any revoked permissions which need to be removed from the checked perms. I am running into an optimization issue now that I am testing the implementation of said revoked permission, because my CustomUser model has an M2M field that holds these revoked permissions which is a relation to auth_permissions, and my BackendAuthentication checks for it, I am getting crazy amounts of DB hits on page load. How can I pass a perfetched object to my AuthBackend? Here is my AuthBackend: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import Permission class UsersAuthenticationBackend(ModelBackend): def _get_revoked_perms(self, user_obj): if user_obj.is_superuser or user_obj.is_admin: revoked_perms = Permission.objects.none() elif hasattr(user_obj, 'revoked_permissions'): # this causes the issue, I need to pass in the prefetch related to my model backend...HOW? # this should be something like CustomUser.objects.prefetch_related('revoked_permissions') revoked_perms = getattr(user_obj, 'revoked_permissions').values_list('content_type__app_label', 'codename') else: revoked_perms = Permission.objects.none() revoked_perms = ["{}.{}".format(perm[0], perm[1]) for perm in revoked_perms] print(revoked_perms) return revoked_perms def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_active: return False revoked_perms = self._get_revoked_perms(user_obj) all_perms = self.get_all_permissions(user_obj) allowed_perms = …