Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to send and fetch data periodically from Django backend to React frontend?
I'm making a web visualization app that needs to display data in real-time. I have a Python SDK that only requests data (using request library from python) directly from our database using the API provided and returns a response in JSON format. I'm using Django version 3.2 and have created a Django app and a React app version 17.0.2 in the same directory. What I did was get the data in my views.py using the Python SDK and then using the Django Rest Framework, created an API from it without using serialization. Then in the front-end (React), I fetched the data in the DRF API using Axios. So far, it's working just fine. However, I noticed that I need to restart my local Django server and refresh the page first before the latest/updated data gets reflected in my visualization. What I need is for the back-end to send the latest data to the front-end in real-time or for the front-end to request/fetch the latest data periodically from the back-end - whichever is better in terms of performance. I'm new to using DRF in the backend and Django+React as the front-end. Someone suggested looking into promises in Python but I'm not … -
How to give access to different object of a model to different users in django
I am doing an online classroom project in Django where I created a model named course which is accessible by teachers. Now I am trying to add students in a particular class by inviting students or students can enroll using "clasroom_id"(a unique field I used in the model). I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict) -
How to prevent django migrations from running?
My team frequently uses the production DB for testing new changes and on more than one occasion migrations have been created and applied before being code reviewed, creating issues in production. There are so many things wrong with this situation, but I'm hoping to at least protect our prod DB by blocking migrations based on the state of an environment variable. Is this possible? -
How to know which django middlewares are asynchronous enabled and which are not?
To see what middleware Django has to adapt, you can turn on debug logging for the django. request logger and look for log messages about “Synchronous middleware … adapted” . I have been trying to do just the same but without any luck. This is my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'DEBUG', }, 'loggers': { 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, } Even though I have set up the LOGGING variable, I am not getting the output like mentioned in the documentation. Starting server at tcp:port=8000:interface=127.0.0.1 HTTP/2 support not enabled (install the http2 and tls Twisted extras) Configuring endpoint tcp:port=8000:interface=127.0.0.1 Listening on TCP address 127.0.0.1:8000 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:47] "GET /admin/" 200 3550 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started for ['127.0.0.1', 42684] HTTP close for ['127.0.0.1', 42684] HTTP response complete for ['127.0.0.1', 42684] 127.0.0.1:42684 - - [22/Mar/2022:12:11:48] "GET /admin/core/user/" 200 9028 HTTP b'GET' request for ['127.0.0.1', 42684] HTTP 200 response started … -
Django error no such table: auth_group when running makemigrations
When i run python manage.py makemigrations it throws an error: File "/home/smoke/miniconda3/envs/testing/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/urls.py", line 7, in <module> from .views import login_view, register_user File "/home/smoke/Documents/wsl_dev/testing/genelookup/apps/authentication/views.py", line 14, in <module> compute, created = Group.objects.get_or_create(name='compute') File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 588, in get_or_create return self.get(**kwargs), False File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get num = len(clone) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1202, in execute_sql cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/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/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/smoke/miniconda3/envs/testing/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in … -
how to create a Dropdown in Django
how to create two Dropdown fields in Django. first is state, & second is city View.py file: def dropdown(request,state_slug): context={} stateO=State.objects.order_by('name') context['state']=stateO sO=State.objects.get(state_slug=state_slug) cityO=City.objects.filter(State=sO).order_by('name') context['city']=cityO context['my_state']=sO return render(request,'drop.html',context) Url.py: class State(models.Model): name = models.CharField(max_length=96) state_slug = models.SlugField(max_length=96, blank=True) def save(self, *args, **kwargs): # Saving The Modefied Changes if not self.state_slug: self.state_slug = slugify(self.name) super(State, self).save(*args, **kwargs) def __str__(self): # Dundar Method return self.name class City(models.Model): State = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name html file: <body> <select> {% for i in state %} <option value="{% url 'dropdown' i.state_slug %}}">{{i}}</option> {% endfor %} </select> <select> {% for j in city %} <option value="{{ j }}">{{ j }}</option> {% endfor %} </select> </body> filter the citys name on the base of state name. without using Ajex. -
Creating Oauth callback function in python. I there is a webserver should sends me Token and I want to react to the token if it's correct by call back
I want to make the same function but in Python Django how can I do that because I want to make authentication for login using Oauth 2.0 public function callback(Request $request){ $response = Http::post('https://oauth.zid.sa' . '/oauth/token', [ 'grant_type' =>'authorization_code', 'client_id' => 48, 'client_secret' => 'LsswUNyWTjyKT9AsXnpsv3FnG4glSNZQ5SM3YRnD', 'redirect_uri' => 'http://client.test/oauth/callback', 'code' => $request->code // grant code]);} -
upload image in forms Django
I am trying to upload image from form but whenever I submit everything got saved in database other than image field.But when I try to do samething from admin panel it works. models.py class Post(models.Model): title = models.CharField(("Title"), max_length=100) title_image = models.ImageField( ("Title Image"), upload_to='static/Images/TitleImages/', max_length=None, blank = True,null = True) Forms.py class AddPostForm(ModelForm): class Meta: model = Post fields = ['title','title_image'] Views.py class AddPostView(LoginRequiredMixin,CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous: messages.error(request,"You need to login to access this page") return redirect('/') elif request.user.is_superuser: if request.method == "POST": form = AddPostForm(request.POST) if form.is_valid(): form.save() messages.success(request,"POST added successfully") return redirect('/') else: print("error") else: print("method is not post") form = AddPostForm() return render(request,'MainSite/add_post.html',{'form':form}) else : messages.error(request,"You need to have superuser permission to access this page") return redirect('/') addpost.html <form action= "" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <button class="btn btn-primary profile-button" style = "width:150px;"type="submit" >Add Post</button></div> </form> my model have 2 things title and title_image but whenever I submit only title is saved and when I do through admin panel it works. I dont know what I am doing wrong here any advice will be helpful. Thanks in advance -
DJango unable to upload image on update
So basically django is unable to upload file after calling update function. It does work with create function. The path is getting updated in the database but the file isn't copying in the /media/ I'm not using the form for image (only for blog content), rather using froala editor. views.py def blog_update(request, pk): context = {} if not (request.user.is_authenticated): return redirect('/') else: try: blog_obj = Blog.objects.get(id = pk) if blog_obj.user != request.user: return redirect('/') initial_dict = {'content': blog_obj.content} form = BlogForms(initial = initial_dict) if request.method == 'POST': form = BlogForms(request.POST) image = request.FILES['image'] title = request.POST.get('title') gist = request.POST.get('gist') user = request.user if form.is_valid(): content = form.cleaned_data['content'] blog_obj = Blog.objects.filter(id = pk).update( user = user , title = title, gist = gist, content = content, image = image ) messages.success(request, f"Blog updated successfully!") return redirect('/my-blogs/') context['blog_obj'] = blog_obj context['form'] = form except Exception as e: print(e) return render(request, 'update-blog.html', context) forms.py class BlogForms(forms.ModelForm): class Meta: model = Blog fields = ['content'] I tried to print the path for existing file as well as the new selected file and it shows correct. Somehow the update function isn't copying the file to the media dir. I'm new to this, any help is … -
Django ChoiceField with custom forms
I am relatively new to Django and have been following up some tutorials on how to create registration forms with Django. **This is the html form code** <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>First name</label> {{ form.first_name }} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Last name</label> {{ form.last_name }} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="col form-group"> <label>Email</label> {{ form.email }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Directorate</label> <select name="directorate" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in form.directorate %} <option value=""></option> {% endfor %} </select> </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>Create password</label> {{ form.password }} </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Repeat password</label> {{ form.confirm_password }} </div> <!-- form-group end.// --> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block"> Register </button> </div> <!-- form-group// --> </form> **This is models.py code** class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) directorate = models.CharField(max_length=100) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) … -
Date value in Django API response is one day lesser that actual value in database
I have a Django model which contain a date field. While I am calling a get API to get values from this model. The date value in response is one day lesser that what is there in the db. Please find a sample table id type created_date 1 test_type 2019-05-23 05:30:00 While I calling a get API I got response like this: {id":"1","type":"test_type","created_date":"2019-05-22T20:00:00-04:00"} Can you please help to fix this issue. And please give me an idea why this is happening. Thanks in advance -
Taking django application to https
I have a django application running perfectly fine in development server with http://localhost:8081 I need to take it to https. For which I tried 2 methods, but none of them is working. Method1: Using stunnel I installed stunnel and generated cert and key with openssl. openssl genrsa 2048 > ca.key openssl req -new -x509 -nodes -sha1 -days 365 -key ca.key > ca.cert cat ca.key ca.cert > ca.pem Defined dev_https as: pid= cert = certs/ca.pem sslVersion = all foreground = yes output = stunnel.log [https] accept=10443 connect=8081 and executed below commands: stunnel certs/dev_https & HTTPS=on /home/user/python3.9/bin/python3 /path/to/django/app/manage.py runserver localhost:8081 This is giving me error on console from stunnel as: connect_blocking: connect 127.0.0.1:8081: Connection refused (111) Connection reset: 0 byte(s) sent to SSL, 0 byte(s) sent to socket from django app gui: If I try to access the app over https://localhost:10443 This site can’t be reached If I try to access app over http://localhost:8081 ---> It works fine. But that's not required. Method2: Apache with mod_wsgi I installed mod_wsgi with rpm. Then modified httpd.conf as: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias / /path/to/django/app/wsgi.py WSGIPythonHome /home/user/python3.9 WSGIPythonPath "/home/user/python3.9/lib;/home/user/python3.9/lib/python3.9/site-packages" <Directory /path/to/django/app> <Files wsgi.py> Require all granted </Files> </Directory> and restarted the httpd. On starting the django … -
django inspectdb non public schema
We only have 1 database with atleast 10 different schemas how can I generate an inspectdb. Let's say python manage.py inspectdb "schema9.table1" > models.py to generate models I found couple of answers saying that django dont support this kind of feature specifically postgresql but maybe since it's 2022 maybe there's a simple and short way to do this -
Writeable Serializer
I have the following viewsets and serializers setup to create a single action to post a schedule with it's steps but I receive the following error. class StepCreateSerializer(serializers.Serializer): start_time = serializers.TimeField() time = serializers.IntegerField() def update(self, instance, validated_data): pass def create(self, validated_data): print(validated_data) return validated_data class ScheduleCreateSerializer(serializers.Serializer): name = serializers.CharField(max_length=100) identifier = serializers.CharField(max_length=10) steps = StepCreateSerializer(many=True) def update(self, instance, validated_data): pass def create(self, validated_data): steps_data = validated_data.get('steps', []) schedule = Schedule.objects.create(**validated_data) for step_data in steps_data: Step.objects.create(schedule=schedule, **steps_data) return schedule class ScheduleViewSet(BaseViewSet): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer def create(self, request, *args, **kwargs): ser = ScheduleCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) ser.save() return Response() I call it with the following json payload with POST method: { "name": "Schedule123", "identifier": "S123", "steps": [ { "start_time": "07:21:00", "time": 5, "valve_actions": [ { "start_state": true, "end_state": false, "valve": 2 }, { "start_state": true, "end_state": false, "valve": 1 } ] } ] } It results in the following error when called with the payload TypeError: Direct assignment to the reverse side of a related set is prohibited. Use steps.set() instead. The models are as follows class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey("manager.Schedule", on_delete=models.CASCADE, related_name="steps", null=True) How do … -
Route53 DNS issue with Django Elastic Beanstalk app
Not sure what I am doing wrong here. My zone is public and I have simple routing for the A records pointing to the EB alias. I even tried a CNAME to no avail. I even did a test response within the console. Everything checks out but there is something funny happening between the Route53 -> EB handshake. The EB alias works just fine by itself. I would love some pointers. Perhaps I need to configure something within Django settings? -
Getting "_pickle.PicklingError: Can't pickle <function>: it's not the same object" for django-q async_task decorator
I'm trying to create a decorator that I can apply to any function, so I can make it a django-q async task. The decorator is written as bellow def django_async_task(func): """Django Q async task decorator.""" def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper Then I can use the above decorator in any task as below @django_async_task def my_task(a): print(f'Hello {a}') task_id = my_task('Vidu', task_name='task1') However, I cannot get the above to work as I'm getting _pickle.PicklingError: Can't pickle <function my_task at 0x7f3dc084be50>: it's not the same object as tests.my_task I tried functools wraps as below but it didn't have any effect. def django_async_task(func): """Django Q async task decorator.""" @functools.wraps(func) def wrapper(*args, task_name): return django_q.tasks.async_task(func, *args, task_name=task_name) return wrapper I also tried a decorator class but it didn't solve the issue either. -
Password reset function in django admin is not working
urls.py from django.contrib import admin from django.urls import path,include from django.urls import re_path from App.views import * from.router import router from django.views.generic import TemplateView from rest_framework_simplejwt.views import ( TokenObtainPairView,TokenRefreshView) from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views urlpatterns = [ path('', TemplateView.as_view(template_name="social_app/index.html")), #social_app/index.html path('admin/', admin.site.urls), #admin api path('api/',include(router.urls)), #api path('accounts/', include('allauth.urls')), #allauth re_path('rest-auth/', include('rest_auth.urls')), #rest_auth path('api-auth/', include('rest_framework.urls')), re_path('/registration/', include('rest_auth.registration.urls')), path('api/token/', MyObtainTokenPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('jobview/',job), path('timelog/',timelogview), path('chaining/', include('smart_selects.urls')), path('admin/password_reset/',auth_views.PasswordResetView.as_view(),name='admin_password_reset',), path('admin/password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done',), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm',), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete',), ] + static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) I have given the password reset function in the admin page login, it is showing as "Forgotten your password or username?" in the page but when I click it the url changes http://127.0.0.1:8000/admin/login/?next=/admin/password_reset/ to this but the same login page is loading i didnt redirected to any other reset page. I have tried but couldn't able to fix it, kindly help me to fix this issue. -
Django+Docker - print() works in settings.py but not in other files
I'm using Django with Docker on my local system. print("Hello World") works in settings.py, but doesn't work in any other file!? Guess the Logger is taking away the control, but I just can't figure out how. At my wits end with this issue. Even print("Hello World", flush=1) doesn't work. (Here's the bigger issue) -
Multiple orders are being saved in one time django ecommerce?
In my django ecommerce website. I am trying to impplement order. It's working, but in one click being saved two orders. orderItem def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] quantity = data['quantity'] print('Action:', action) print('Product:', productId) print('Quantity:',quantity) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + quantity) if action == 'remove': orderItem.quantity = (orderItem.quantity - quantity) orderItem.save() if action=='delete': orderItem.quantity=0 if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) order def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) name = data['form']['name'] email = data['form']['email'] phone = data['form']['number'] phoneAdd = data['form']['numberAdd'] address = data['form']['address'] time = data['form']['time'] date = data['form']['date'] payment = data['form']['payment'] comment = data['form']['comment'] id_order = int(data['form']['id']) if request.user.is_authenticated: customer = request.user.customer order = Order.objects.get(id=id_order) order.transaction_id = transaction_id order.complete=True order.save() OrderInfo.objects.create(customer=customer,order=order,name=name,email=email,phone=phone,phoneAdd=phoneAdd,address=address,time=time,date=date,payment=payment,comment=comment) else: print("Not logged in ") return JsonResponse('Payment submitted..', safe=False) It's working and complete is being changed to TRUE. However, another empty order being created. So, what's the problem? Can you please help to solve this problem? -
Scanning External files inside python backend
I have some files that I need to download and then upload to a specific location during execution of code. These files are other than source code files but required by the source code(.yaml, .xml, some .zip folders etc.) I need to scan these files for any security vulnerabilities - on the backend. Most available approaches look at source code and not at external files. Any advice to this end would be useful.(No recommendations) Note:- I am not asking for any Software recommendations. Please feel free to ask for clarifications if you find the question misleading. -
Django Admin S3 Private Media Files
When using the private media django-storages class below. When I view the uploaded file in the admin it does not generate the URL Query String Authorization parameters. from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class PrivateMediaRootTenantedS3Boto3Storage(S3Boto3Storage): auto_create_bucket = True default_acl = "private" file_overwrite = False custom_domain = False -
datatable column filtering with serverside(ajax) doesn't work
I'm developing with django and javascript with datatable. I want to apply column filtering in my datatable (https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html) but it works fine without serverside option & ajax (in client side), but it doesn't work with serverside option & ajax. How can i FIX IT? Please help me..T_T this is my code. <table id="sample_table" class="table table-bordered table-hover"> <thead> <tr> <th class="sample_id">ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </thead> <tbody id="sample_table_body"> </tbody> <tfoot> <tr> <th>ID</th> <th>date</th> <th>serial</th> <th>name</th> <th>birth</th> </tr> </tfoot> </table> </div> <!-- /.card-body --> </div> var column_list = [ { "data" : "id" , "className": "sample_id"}, { "data" : "receiving_at" }, { "data" : "serialnumber" }, { "data" : "name" }, { "data" : "birthday" }, ]; $('#sample_table tfoot th').each(function(){ var title = $("#sample_table thead th").eq( $(this).index() ).text(); $(this).html('<input type="text" placeholder="Search '+title+'" />' ); }); var sample_table = $('#sample_table').DataTable({ "paging": true, "autoWidth": false, "lengthChange": false, "ordering": true, "processing" : true, "columns": column_list, "order": [ [0, 'desc'] ], "fixedHeader": true, "orderCellsTop": true, "ajax": { url: '/view_datatable/', type: 'POST' }, "serverSide" : true, //get data from server "initComplete": function() { // column filtering RUN after table loaded . $( '#sample_table tfoot input' ).on( 'keyup change clear', function () { if ( sample_table.search() !== … -
API request failing if pagination is required in Django due to OrderBy' object has no attribute 'lstrip'?
I have a view that inherits from the ListModelMixin from Django REST Framework and have overridden the list(...) function so I can add query parameter validation to the list method: <!-- language: python--> class UserViewSet(ListModelMixin): def get_queryset(self): return User.objects.all() def list(self, request): queryset = self.get_queryset() # Get the query parameters from the request sort_by = request.query_params.get('sort_by') sort_order = request.query_params.get('sort_order') sorting_query: OrderBy = F(sort_by).asc(nulls_last=True) if sort_order == "desc": sorting_query = F(sort_by).desc(nulls_last=True) querySet = querySet.order_by(sorting_query, "id") # Code fails here on the pagination method page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The error I see when running the API is: AttributeError(\"'OrderBy' object has no attribute 'lstrip'\")", which I suspect has something to do with the sorting_query variable, but I have no idea WHY. The thing is, I only see this error when the total number of results exceed the MAX page size and pagination is needed. Otherwise, the API works fine. Any help would be appreciated! Note: I'm using cursor pagination from the Django REST Framework. -
Creating a Django post feed that gradually renders posts in batches as you scroll down
I am trying to make a Django post feed without pagination, but hypothetically, once there are more than a thousand posts, it would be too heavy to always render all of the posts available. So I am trying to find a way to mimic what many other websites with infinite feeds (like Twitter for example) do so that it renders only a batch of posts, and then renders additional ones once you scroll down to the end of the already rendered ones. I am using a function view instead of the class view. Thank you in advance for any help. -
Ignore HTML line in Django Template
I am new to Django. That's why I am a bit confused. and I am not sure is it possible or not? {% for appoint in appoints %} {% if appoint.a_status == 'Pending' %} <h4>Pending</h4> <p>{{appoint}}###<a href="#">Accept</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Accept' %} <h4>Accepted</h4> <p>{{appoint}}###<a href="#">Done</a>###<a href="#">Reject</a></p?> {% elif appoint.a_status == 'Done' %} <h4>Done</h4> <p>{{appoint}}</p?> {% else %} <h4>Reject</h4> <p>{{appoint}}</p?> {% endif %} {% endfor %} This is part of a template. I want to ignore Django attribute/code to ignore the h4 tag. I know I can do this something by running loop for every h4 tag. but that will less efficient.