Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Oauth2: How does this exactly works and How to implement it on the oauth2 client part?
There is an oauth2 client which is an application developed in django and oauth2 provider also an application in PHP CI. The Django application should authenticate users from the PHP application and let the users run the Django application with their accounts. I am confused about how the oauth2 works. Still, I am not able to figure the situation here. I tried looking from the docs: https://django-oauth-toolkit.readthedocs.io/en/latest/ I just have to work as being the oauth2 client. Can someone explain how this works? -
Android Paypal Native Checkout Sdk Endless loading
I am using server-side integration of paypal python sdk. I create the order on the server-side. Now I want a user to pay on my mobile kotlin app. For this I am using the paypal android native checkout sdk. For testing I copy the orderId from the server-side and paste it into the paypalButton.setup, now paypal let me log in with me personal sandbox account, but if I click on continue i am stuck in an endless loading loop and nothing happens. Thank you for helping. In the screenshot is how I use the paypalbutton The order Id is pasted from the server That is how the order is created on the server-side -
You have multiple authentication backends configured Django?
I am having this error You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. in my Login class base view in Django Login View class SystemLoginView(LoginView): template_name = "registration/login.html" authentication_form = LoginForm def post(self, request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] db_name = request.POST['year'] branch = request.POST["branch"] user = authenticate(username=username, password=password) if user and user.active: period_id = AccountingPeriod.objects.all() if period_id: request.session["period_id"] = period_id[0].id else: request.session["period_id"] = None messages.error( request, _( "Please You must Be initial the Period Before Any Operation" ), ) set_defualt( request.session.session_key, int(branch), ) request.session["branch_id"] = branch cache.set("branch", branch) list_branch = [] for x in user.user_branch.all(): dict_data = {"id": x.pk, "name": x.name} list_branch.append(dict_data) request.session["user_branch"] = list_branch request.session["db_name"] = db_name request.session["permission"] = get_all(request) request.session["permission_partion"] = get_all_partion(request) request.session["db_name"] = db_name return super(SystemLoginView, self).post(request, *args, **kwargs) Login Form class class LoginForm(AuthenticationForm, IttechForm): CHOICE = [(x, x) for x in DATABASES] year = forms.ChoiceField( choices=CHOICE, label=_("Year"), widget=forms.Select(attrs={"class": "form-control"}) ) branch = forms.ModelChoiceField( queryset=Branch.objects.all(), label=_("Branch"), widget=forms.Select(attrs={"class": "form-control"}) ) username = forms.CharField( label=_("Username"), max_length=20, widget=forms.TextInput(attrs={"placeholder": _("Username"), "class": "form-control"}), ) password = forms.CharField( label=_("password"), max_length=30, widget=forms.PasswordInput(attrs={"placeholder": _("Password"), "class": "form-control"}), ) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) def clean(self): username = … -
DRF how to add loggedin user to serializer field
I want to auto add my loggedin user. From DRF tutorial and other stackoverflow questions I write this code but facing error TypeError at /articles/write/ getattr(): attribute name must be string Request Method: POST Request URL: http://127.0.0.1:8000/articles/write/ Django Version: 3.2.4 Exception Type: TypeError Exception Value: getattr(): attribute name must be string Here are code model.py class ArticlesModel(models.Model): title = models.CharField('Enter Your title', max_length=150) body = models.TextField('What is on your mind') image = models.ImageField(upload_to='articles', blank=True, null=True) slug = AutoSlugField(populate_from=title) date_added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) class Meta: ordering = ('-date_added', 'image',) def __str__(self): return f'{self.title} by {self.author.username} at {self.date_added}' def get_absolute_url(self): return f'http://localhost:8000/media/{self.image}' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url else: return '' serializers.py class ArticlesSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source='author.username') class Meta: model = ArticlesModel fields = ['id', 'title', 'body', 'image', 'get_absolute_url', 'author'] def create(self, validated_data): return ArticlesModel.objects.create(**validated_data) views.py class WriteArticleView(APIView): permission_classes = [IsAuthenticated,] def post(self, request): serializer = ArticlesSerializer(data=request.data) if serializer.is_valid(): serializer.save(author=request.user) return Response(status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
fields.E305 reverse query name clashes with reverse query name
I would like to have audit columns in each model. However, once two models have the same code, I get an error "(fields.E305) Reverse query name for 'app.Model.created_on' clashes with the reverse query name for 'app.Model.created_on'. created_on created_by updated_on updated_by Example class ModelB(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by', on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by', on_delete=models.CASCADE) class ModelB(models.Model): created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by', on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by', on_delete=models.CASCADE) I don't really need a reverse key in users for each of these, but I want a way to be able to lookup the user_id if necessary. -
How to create a model field that is an average of all of another foreign key model' field. Ex: avg rating field
I have two models. Fiction model that can be any movie, book, tv series or something similar. I have another model that is a review that contain review like fields for example: reviewer, rating, description. What I want to do is the following: Have Two extra fields in the fiction model that are: number of reviews average of review ratings I was able to add them as integer and float fields and then changed them whenever a new review was added, edited, or deleted but there are two issues. Adding reviews from the admin won't be accounted for I just feel like that is not the best approach and I feel like there is a more sensible approach for the fields to be automatically filled from the review model. Here are the two models as well as how I implemented the api views. fiction models.py from django.db import models from stream.models import StreamPlatform class Fiction(models.Model): """ Model that encopasses a Movie, TV Series, book or similar """ MOVIE = 1 TV_SERIES = 2 BOOK = 3 PODCAST = 4 TYPE = ( (MOVIE, 'Movie'), (TV_SERIES, 'TV-Series'), (BOOK, 'Book'), (PODCAST, 'Podcast') ) title = models.CharField(max_length=50) description = models.CharField(max_length=200) active = models.BooleanField(default=True) … -
how to enable submit button after successful validation in jquery
So I have two button: <div class="field-row"> <button type="submit" class="form-button" id="validate" style="cursor: pointer;">Validate</button> <button type="submit" class="form-button" id="submit" style="cursor: pointer;">Submit</button> </div> I want to disable the submit button in the start and then after the form is validated by the validate button by INSERT Query a string is passed from the server side, I need to enable the submit button and disable the validate button when the string is shown. If someone can please help me, Im fairly new to jquery. -
How can i request cart objects from post list view?
This is my post listview where i want the cart object to be. but i keep getting this error 'PostListView' object has no attribute 'cart'. Am not sure if it is a good practice to write a dispatcher to handle that functionality of rending the cart object ? from cart.cart import Cart class PostListView(ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def dispatch(self, request, *args, **kwargs): cart = Cart(request) if self.cart: return cart def get_context_data(self,**kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked for user in Post.objects.all(): if self.request.user.is_authenticated: friend_list = FriendList.objects.get(user=self.request.user ) friends = friend_list.friends.all() context['friends'] = friends return context Here is my cart detail view, i have tried writing a context for it but i had another error saying post has no attribute request and now wondering how i can get users on the app to accesses the cart object when they are on the post listview ? def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update':True}) return render(request, 'cart/detail.html',{'cart':cart}) -
Django Models create a task for all users
So i'm trying to build a webapp where the same task is given to all users, and when the users complete the task they can mark it as completed, to do so i added a 'status' bool that is set to true when the 'task' is not complete, and with a button the user can set it to false, the problem is that when i use a many-to-many field, if one user changes the 'status', it changes for everyone. I also tried using a Foreignkey but if i use a Foreignkey i have to create a task for every user. What i want is to create a task, assign it to all users, and then all the users can interact with the task without affecting what other users see. These are the models that i created (it's in spanish): class Usuario(AbstractUser): pass class Tps(models.Model): users = models.ForeignKey(Usuario, on_delete=CASCADE) titulo = models.CharField(max_length=100) TECNOLOGIA_DE_LA_FABRICACION = 'TDF' MANTENIMIENTO_Y_REPARACION_DE_EQUIPOS = 'MYRDE' MAQUINAS_ELECTRICAS_Y_ENSAYOS = 'MEYE' SEGURIDAD_E_HIGIENE_INDUSTRIAL = 'SEHI' LABORATORIO_DE_ENSAYOS_INDUSTRIALES = 'LDEI' INSTALACIONES_INDUSTRIALES = 'II' RELACIONES_HUMANAS = 'RH' TALLER_DE_ELECTROMECANICA = 'TE' ORGANIZACION_INDUSTRIAL = 'OI' INSTALACIONES_ELECTRICAS = 'IE' EDUCACION_FISICA = 'EF' EQUIPOS_Y_APARATOS_DE_MANIOBRA_Y_TRANSPORTE = 'EYADMYT' MATERIAS_CHOICES = [ (TECNOLOGIA_DE_LA_FABRICACION, 'Tecnologia de la fabricación'), (MANTENIMIENTO_Y_REPARACION_DE_EQUIPOS, 'Mantenimiento y R de … -
Django Model with foreign key relationships exceeding 1664 'SELECT' SQL entries
In my django model 'AllocatedTemplates', I have the following fields: template_job_id = models.ForeignKey(JobTemplate, related_name='jobtemplate_id', on_delete=models.CASCADE) interview_job_id = models.ForeignKey(Job, on_delete=models.CASCADE, null=True, blank=True) interview_company_id = models.ForeignKey(Company, related_name='company_id', on_delete=models.CASCADE) created_at = models.DateTimeField(default=now, blank=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, on_delete=models.CASCADE, null=True) I am using Postgres DB. When I am trying to access this model from the admin, it get the following error: 'target lists can have at most 1664 entries' What's happening is that the foreignkey relationships are calling more than 1664 'SELECT' sql queries which is exceeding the limit. What I can do to ensure that the 'SELECT' sql queries are below 1664 queries at the time with the existing model fields? -
Occurrence of a failure to migrate a Django
An error occurs when I use commands related to migration. File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/jch/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/jch/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/jch/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/jch/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/jch/venv/lib/python3.8/site-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. As an exception, if I use "python3 managy.py makemigrations", "No changes detected" is output. The first app is notice. If only notice connects to db, it will work normally. #/notice/models.py from django.db import models from django.db.models.base … -
How can I use distinct() with an F() expression?
My count contains duplicates in this query: items = items.annotate( user_id=F("product__productitemweightthroughmodel__product_item__user_id"), start_month=TruncMonth("start") ) \ .values("user_id", "start_month") \ .annotate(count=Count("start_month")) I would need to apply distinct() to the F expression somehow to avoid getting duplicates, is this possible? -
How to deploy webpack generated html file?
I run webpack to generate the js/css for my Django app, and it generates two things: (1) transpiled, packed, and versioned js/css files under myapp/static/myapp/ (the versioning uses the hased content of the file, e.g. myapp.7dd0fe49a6586234d7e7.min.js). (2) Since the version specifier is not very human friendly, and to make sure all files are included, the following file is created as myapp/templates/myapp/include-scripts.html: {% load staticfiles %} {% if debug %} <script src="{% static "myapp/js/myapp.min.js" %}"></script> <link rel="stylesheet" href="{% static "myapp/css/myapp.css" %}" type="text/css"> {% else %} <script src="{% static "myapp/js/myapp.7dd0fe49a6586234d7e7.min.js" %}"></script> <link rel="stylesheet" href="{% static "myapp/css/myapp.dd0a677adcba9309426a.css" %}" type="text/css"> {% endif %} This way production usage will get the versioned files, and consumers of myapp can include the the latest version of the generated files by simply: {% include "myapp/include-scripts.html" %} Now I want our gitlab pipeline to automate the process. Building the libraries is not problematic, since they're versioned we can push them to our static server immediately: workflow: rules: - if: $CI_COMMIT_MESSAGE =~ /^no-pipeline/ when: never - when: always webpack: stage: deploy image: thebjorn/dknode2:latest # has rsync ssh-client yarn etc. installed variables: DKBUILD_TYPE: "PRODUCTION" # our webpack looks at this to create versioned resources before_script: - eval $(ssh-agent -s) - ssh-add … -
Onclick not working in Vuejs axios response (Django)
Fisrt of all sorry for the long question. Since Vue JS performance is very good as compared to some of other platform (Based on test criteria). I render some html to a span through axiom response. But button (in the response html) click not working and also vue js data also not displaying. Here is my code <div id="vue-app" class="container"> {%csrf_token%} <button v-on:click="greet" class="btn btn-primary">BUTTON</button> <span v-html="message"></span> </div> <script type="text/javascript"> let app = new Vue({ el: "#vue-app", delimiters: ['[[', ']]'], data: { message: "", }, methods: { greet: function (event) { let formData = new FormData(); formData.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value); axios({ method: 'post', url: '{% url "core:test_url" %}', data: formData }).then( response => (new Vue.set(this, 'message', response.data)) ); } } }); </script> Django view class test_func4(View): def post(self, request): return render(request, 'home/vue_js_axiom.html', { "post_to_view": 123 }) vue_js_axiom.html <table class="table table-striped"> <tr> <td>DATA FROM DJANGO VIEW</td><td>DATA FROM VUE JS</td> <td>ON CLICK BUTTON</td> </tr> <tr> <td>{{post_to_view}}</td><td>[[vue_js_variable]]</td> <td> <button v-on:click="click_from_response_view" class="btn btn-warning btn-sm">ON CLICK</button> </td> </tr> </table> <script> let container = new Vue({ el: '#container', delimiters: ['[[', ']]'], data: { vue_js_variable: "true", }, methods: { click_from_response_view: function (event) { alert("clicked from response view"); } }, }); </script> Can someone help to solve this problem? How … -
What would be the equivalent of this function based API
I need my class based API to insert data inside 2 different tables I have a function based API that can do it but it doesn't take files/images so I would like to add the part where the insertion is made in the 2nd table into the class based api function based API @api_view(['POST']) def registerCustomer(request): data = request.data customer = Enroles.objects.create( # in data.get is to be put the name of the states nom = data.get('name',''), prenom = data.get('prenom',''), date_naissance = data.get('dob','2021-06-21 10:30'), lieu_naissance = data.get('pob', ''), ville = data.get('ville',''), quartier = data.get('quartier',''), telephone = data.get('phone',''), point_chute_prefere = data.get('favoriteHospital',''), structure = data.get('employeur',''), role = data.get('profession',''), tel_structure = data.get('contactNumber',''), alerter_pers = data.get('emergency1','False'), # domicile = data.get('domicile',''), # persContact = data.get('contact',''), # relation = data.get('relation',''), modele_brac = data.get('bracelet',''), adresse_ramassage = data.get('pickup',''), total_a_payer = data.get('price',0), code_promo = data.get('parrainCode',''), civilite = data.get('civil',''), uniq = uniqueFunction(), dossier = data.get('dossier'), avatar = data.get('avatar'), ) serializer = EnrolSerializer(customer, many=False) # finding the latest id of the Enroles table last = Enroles.objects.latest('id') if (Enroles.objects.latest('alerter_pers') != False): prevenir = PersonnePrevenirs.objects.create( nom = data.get('firstlastName',''), domicile = data.get('domicile',''), numeros = data.get('contact',''), lien = data.get('relation',''), id_enrole = last ) prevenir2 = PersonnePrevenirs.objects.create( nom = data.get('firstlastName2',''), domicile = data.get('domicile2',''), numeros = data.get('contact2',''), … -
Custom user model: Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive
I always get the message "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." I write in settings.py AUTH_USER_MODEL = 'eCommerce.User'. And after I run makemigrations and migrate command I use these commands: python manage.py createsuperuser and then python manage.py runserver. There is no errors in cmd but in the Django administration the above message shows. from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self,email,name,password=None): if not email: raise ValueError("Users must enter an email address.") if not name: raise ValueError("Users must enter a name.") user = self.model( email= self.normalize_email(email), name= name, #phone_number = phone_number, ) user.set_password=password user.save(using=self._db) return user def create_superuser(self,email,name,password=None): user = self.create_user( name= name, email= self.normalize_email(email), password= password ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using= self._db) return user class Address(models.Model): street = models.CharField(max_length=50) city = models.CharField(max_length=20) postal_code = models.CharField(max_length=10) class User(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=50, unique=True) name = models.CharField(max_length=30) phone_number = models.CharField(max_length=20) billing_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True ,related_name='billing_address') shipping_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, related_name='shipping_address') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) #is_superuser = models.BooleanField(default=False) #is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] … -
how to solve this problem ?-TypeError: '<' not supported between instances of 'NoneType' and 'int'
I am very beginner on python django framework and here I am trying to write some very basic pagination logic for my little django blog though I got following error. please somebody fix my problem. File "D:\learn django\mountaincoders\blog\views.py", line 30, in blog if page<math.ceil(length/no_of_posts): TypeError: '<' not supported between instances of 'NoneType' and 'int' views.py file def blog(request): no_of_posts=3 page=request.GET.get('page') print(page) if page is None: page=1 else: page=int(page) blogs=Blog.objects.all() length=len(blogs) print(length) blogs=blogs[(page-1)*no_of_posts:page*no_of_posts] if page>1: prev=page-1 else: page=None if page<math.ceil(length/no_of_posts): nxt=page+1 else: nxt=None context={'blogs':blogs,'prev':prev,'nxt':nxt} return render(request,'bloghome.html',context) -
Django display loop in template
Hello I am doing a calculation in my view for the customers, I need to display the result for every customer in the template. I know I need to loop through in the template but unsure what values to use.Image of view for loop For example in the picture the value I need to show is 'first_day_rate_calc'. If I just put {{ first_day_rate_calc}} in my template I only get one result but I need to display them all. Thank you. -
Django : how to add a link in django admin form and redirect to another page and select an input, and comes back to the form
I have a django admin form as shown. When a User inputs a data in the content_type field, a link should appear and it will redirect to another page which shows object values corresponding to the content_type User selected earlier. From there user can select an object and the id of the object will be saved to Object_Id field in the form. how it can be implemented ? This is the django admin form -
Django: How to show the updated information on the page without reloading
I am working in Djnago and I want to update the information without reloading the page. At first, I have used Ajax for not reloading the page after submitting the form, and it is working properly. Then I used Ajax for get operation and it is working too but to see the new information on the page, I have to refresh the page. The view.py file: def bfs_view(request): form = BFSForm(request.POST or None) if form.is_valid(): form.save() form = BFSForm() try: image_url_info = None num_states_explored = None final_solution = None text_file = open("BFS\outputs\maze.txt", "w") field_name = 'description' input_value = BFS.objects.latest('id') field_object = BFS._meta.get_field(field_name) field_value = field_object.value_from_object(input_value) field_string_value = str(field_value).split("\n") text_file.writelines(field_string_value) text_file.close() m = Maze("BFS\outputs\maze.txt") print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() image_url_info = "/../../../static/search/bfs/maze.png" num_states_explored = m.num_explored # final_solution = ''.join(m.end_result) final_solution = str(''.join(m.end_result)) print(''.join(m.end_result)) # BFS.objects.latest('id').delete() except: print("BFS ERROR: Error in the try session of BFS in view.py") context = { 'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored, 'solution': final_solution} return render(request, "BFS/bfs.html", context) def post_bfs_view(request): if request.method == "POST" and request.is_ajax(): bfs_view(request) return JsonResponse({"success":True}, status=200) return JsonResponse({"success":False}, status=400) def get_bfs_view(request): if request.method == "GET" and request.is_ajax(): try: image_url_info = None num_states_explored = None final_solution = None text_file = … -
Django ORM order by filters
Help me please with my problem. I want to get objects sorted first by one filter and then by another filter. How can I get objects with this ordering in 1 query to the DB (need for pagination)? This example shows queryset without ordering: rooms = Room.objects.filter(Q(name__icontains=search) | Q(owner__username__icontains=search)) I have the room model: models.py from django.db import models from django.contrib.auth.models import User class Room(models.Model): name = models.CharField(max_length=150) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py (my bad code) class RoomListView(ListAPIView): def get_queryset(self): search = 'test' # for example rooms1 = Room.objects.filter(owner__username__icontains=search) rooms2 = Room.objects.filter(name__icontains=search) return list(rooms1) + list(rooms2) The wrong result: search = "test" [ { "id":1, "name":"test", "owner":{ "username":"user1" } }, { "id":2, "name":"room1", "owner":{ "username":"test" } }, { "id":3, "name":"test2", "owner":{ "username":"user2" } } ] The correct result: search = "test" [ { "id":2, "name":"room1", "owner":{ "username":"test" } }, { "id":1, "name":"test", "owner":{ "username":"user1" } }, { "id":3, "name":"test2", "owner":{ "username":"user2" } } ] How can I get objects with this ordering in 1 query to the DB (need for pagination)? -
How to disable HTML view with django?
Imagine you are using django guardian for some object level restrictions. Now I have the following code; admin.py class ControlAdmin(GuardedModelAdmin): prepopulated_fields = {"description": ("title",)} list_display = ('title', 'description', 'priority') search_fields = ('title', 'description') ordering = ('-title',) Now I have selected in the database that user maxdh has no permissions for viewing a control, which checks out: >>> control = Control.objects.first() >>> checker = ObjectPermissionChecker(maxdh) >>> checker.has_perm('change_control', control) False >>> checker.has_perm('view_control', control) False However when I go to the html which renders the table for the controls I can still see the table: html: <div class="card-body"> <div class="card-body"> {% load django_tables2 %} {% render_table controls %} What am I is missing? I read the docs but could not identify Please help! -
Sending part of the data to frontend and after clicking next pages sending another request to backend for the rest of it for efficiency
I have a large dataset sometimes containing millions of products data. When I am sending this to frontend I limit it to 1000 product at first to be fast. This is how I am doing with Django rest: def get_products(self, request, pk=None): page = int(request.query_params['page']) if 'page' in request.query_params else 0 page_size = 1000 data = list(collection.find(filter_query, {'_id': 0}).skip(page * page_size).limit(page_size)) total_count: collection.count() return Response({'message': 'success', 'data': data, 'count':total_count}, 200) So in React, I accept the first 1000 products at first request. I show them on AG-GRID table. But I also need to show real page numbers ( I have the total count of the products). If user clicks on page=650 for example, I will send another request to the backend with the equivalent page number and fetch the remaining data. `http://localhost:8000/${ID}/products?page=${page}` This is how I fetch data and show in AG grid on frontend: React.useEffect(() => { jwtAxios( `http://localhost:8000/${ID}/products/` ).then((result) => { if (!result || !result.data.data || !result.data.data.length) { setRowData([]); setColumnData([]); return; } setRowData(result.data.data); // Get column fields const columnDefs = []; Object.keys(result.data.data[0]).map((fieldName) => { columnDefs.push({ headerName: fieldName, field: fieldName, }); return null; }); setColumnData(columnDefs); }); }, [catalogID]); // enables pagination in the grid const pagination = true; const … -
django RuntimeError at /admin/users/user/1/change/, Single thread executor already being used, would deadlock
i tried to make chat app with django-channels. RuntimeError is occurred when New django-chaneels project and edit data in adminsite.. I'm not sure that i think the error occurred because i made several django-channels projects.. When I built my first project, websocket is not working.. so i made other 2nd, 3rd, 4th projects with django-channels.. now websocket is connected, but i have trouble with RuntimeError (Error message: Single thread executor already being user, would deadlock) So.. what can i do for this...? myproject/settings.py enter code heremport os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-is!$&voe3y058!2sus9egmxh@d!$)=l&o8_vl=m8zz!ap+d#a#" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "users.apps.UsersConfig", "channels", "core.apps.CoreConfig", "broadcasts.apps.BroadcastsConfig", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "busker.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] … -
Django read from filefield returns hex, when I try to decode it I get weird characters
Im builing a django website that matches documents, and I upload documents to Minio bucket, so the defaut storage is storages.backends.s3boto3.S3Boto3Storage from django-storages and not the default Django storage class. This question is similar to Why is Django FieldFIle readline() returning the hex version of a text file? class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'doc_file'] def form_valid(self, form): form.instance.author = self.request.user f = form.instance.doc_file.open('r') text = ''.join(i.decode("utf-8", 'ignore') for i in f.readlines()) form.instance.content = ''.join( [i if ord(i) < 128 else ' ' for i in text]) return super().form_valid(form) If I upload a .txt file it reads it properly but if I upload a doc file it gives me alot of weird characters even after I do ##''.join([i if ord(i) < 128 else ' ' for i in text])## For example if the file contains just SSSSSSSSssss, I get !# ddddSxSx l SSSSSSSSssss OJQJCJ &p@P ! i4@4NormalCJOJPJQJmH <A@<Default Paragraph Font GTimes New Roman5Symbol3Arial;Helvetica 0hKl&Kl& 0" Oh+'0 .+,0 "Root Entry F$1TableWordDocumentSummaryInformation(DocumentSummaryInformation8