Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Malloc Error: cannot allocate memory while running Django Application
I'm currently running 3 separate Django sites on a linux (debian 9) server. I am currently receiving the following error: Wed Sep 20 15:53:23 2023 - malloc(): Cannot allocate memory [core/utils.c line 1796] Wed Sep 20 15:53:23 2023 - !!! tried memory allocation of 512 bytes !!! When attempting to load a page on one the sites. This error message is found within my logfile for UWSGI. I receive no errors in my django logs. 2/3 sites are working fine, so I don't believe the system as a whole is struggling with memory. This error happened following our last push to the server which included a change in code that added matplotlib as an import. (Yes, I have already changed matplotlib to use the "Agg" backend to prevent a memory leak). I am aware this is not enough information for a full answer, but does anyone have any ideas as to direction? I am not finding any history of people with a similar error message online (not one that has to do with core/utils). Noting also that this did not happen on our development servers, which are about half the strength of this server. -
how to filter and sort fields in django-filter that are not in Django model?
I am trying to filter values in 2 fields that I am creating in my serializer and I am wondering how to add last_run and lat_status to filtering and orting fieldset but when I am adding them I get Cannot resolve keyword 'last_status' into field. error. Is there any option to annotate these 2 fields in my ListAPIView so I can sort and filter by them sample API data { "id": 2, "user": 1, "project": 3, "last_run": "17-08-2023 16:45", "last_status": "SUCCESS", "name": "test spider", "creation_date": "10-08-2023 12:36", }, models.py class Spider(models.Model): name = models.CharField(max_length=200, default="", unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, related_name='project_spider') creation_date = models.DateTimeField(default=timezone.now) serializers.py class SpiderListSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) last_run = serializers.SerializerMethodField() last_status = serializers.SerializerMethodField() class Meta: model = Spider fields = "__all__" def get_last_run(self, instance): return get_last_spider_status(instance.id)[0] def get_last_status(self, instance): return get_last_spider_status(instance.id)[1] filters.py from django_filters import rest_framework as filters from .models import Spider class SpiderFilter(filters.FilterSet): name = filters.CharFilter(field_name='name', lookup_expr='icontains') user = filters.NumberFilter(field_name='user__id', lookup_expr='icontains') project = filters.NumberFilter(field_name='project__id', lookup_expr='icontains') creation_date = filters.DateFilter( field_name='creation_date', input_formats=['%d-%m-%Y'], lookup_expr='icontains' ) class Meta: model = Spider fields = [] views.py class SpiderListView(ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = SpiderListSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = SpiderFilter ordering_fields = … -
__str__ returned non-string (type NoneType) I don't even know where the problem
I was making which user allowed to do what and which doesn't allowed by watching a video series. After I did something I couldn't delete one user. I added one more user to see could I delete that one and I deleted it. I even don't know where is the problem. decoraters.py from django.shortcuts import redirect from django.http import HttpResponse def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not autherized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == "customer": return redirect('user') if group == "admin": return view_func(request, *args, **kwargs) return wrapper_function models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) email = models.EmailField(null=True) profile_pic= models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name I don't know should I share anymore information. I hope someone can fix my problem and tell me why I … -
How can I Make Django Filter With Field-Choices?
Hello my friends, I am now facing a problem when I create a filter on the Category page, which is a Page not found (404) error, and I do not know what the exact problem is. Can anyone help please? models.py: class categorie (models.Model): title = models.CharField(max_length=100 , null=True ) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) def save(self , *args , **kwargs): if not self.slug: self.slug = slugify(self.title) super(categorie , self).save( *args , **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('category', args=(self.slug,)) class software (models.Model): LICENSE_CHOICES = [ ('free', 'free'), ('opensource', 'opensource'), ('demo', 'demo'), ] category = models.ForeignKey(categorie,on_delete=models.CASCADE,null=True) slug = models.SlugField(blank=True,allow_unicode=True,editable=True) title = models.CharField(max_length=50 , null=True) license = models.CharField(max_length=100 ,choices=LICENSE_CHOICES, null=True,blank=True) picture = models.ImageField(upload_to='img' , null=True) description = RichTextUploadingField(null=True,blank=True) created_at = models.DateField(auto_now_add=True) auther = models.CharField(max_length=100 , null=True) download = models.URLField(null=True) def save(self , *args , **kwargs): if not self.slug: self.slug = slugify(self.title) super(software , self).save( *args , **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', args=(self.slug,)) filter.py: import django_filters from .models import software class SoftwareFilter(django_filters.FilterSet): license= django_filters.ChoiceFilter( choices=[ ('free', 'free'), ('opensource', 'opensource'), ('demo', 'demo'), ], label='Choose from the list', field_name='license', ) class Meta: model = software fields = ['license'] views.py: from django.shortcuts import render , get_object_or_404 , Http404 from django.http import … -
Python - HTML/JQUERY Pagination
Hello friends and colleagues in the community, I am trying to make a pagination bar, the problem is that using a button I can only print/function the first page but not the remaining pages. Pagination This is my code: <div> <script type="text/javascript"> $(function () { $("#descargar").DataTable({ "lengthChange": true, "searching": true, "ordering": true, "info": true, "autoWidth": false, "responsive": true, language: { "lengthMenu": "Mostrar _MENU_ registros", "zeroRecords": "No se encontraron resultados", "info": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", "infoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", "infoFiltered": "(filtrado de un total de _MAX_ registros)", "sSearch": "Buscar:", "oPaginate": { "sFirst": "Primero", "sLast":"Último", "sNext":"Siguiente", "sPrevious": "Anterior" }, "sProcessing":"Procesando...", }, }) $("#descargar").ready(function() { $('.fa-binoculars').on('click', function() { var codigoPartner = $(this).data('codigo-partner'); var url_seguimiento = "/seguimiento/" + codigoPartner; window.location.href = url_seguimiento; }); }); }); </script> </div> I think the problem could lie in the DataTable but I'm not sure. I would greatly appreciate your help. What I hope is that the button works on the other pages (pagination) -
How to change background image in django web app using the admin interface?
I want to change the background of the home page in my web app but using the admin interface. I made a model specific for the backgrounds of each section used in the home page. this was my first approach, which is editing the save function and give the image name the id name as 1.jpg then reffering to 1.jpg in my html file Here is the my ImageHome model for the images in the background: def save_home_image(instance, filename): upload_to = 'Images/' ext = filename.split('.')[-1] # get filename if instance.name: filename = 'Home_Pictures/{}.{}'.format(instance.name, ext) return os.path.join(upload_to, filename) def custom_upload_to(instance, filename): ext = filename.split('.')[-1] return os.path.join('Images', 'Home_Pictures', f'{instance.name}.{ext}') class ImageHome(models.Model): name = models.CharField(max_length=500, null=True, blank=True) image_home = models.ImageField( upload_to=custom_upload_to, blank=True, verbose_name='Home Image', null=True, max_length=500 ) def __str__(self): return self.name def save(self, *args, **kwargs): # Check if an image with the same name exists try: existing_image = ImageHome.objects.get(name=self.name) # Delete the existing image if existing_image.image_home: existing_image.image_home.delete() except ImageHome.DoesNotExist: pass # Call the original save method to save the new image super(ImageHome, self).save(*args, **kwargs) here is the code in my html file: <section data-image-width="1980" data-image-height="1320" style="background-image: linear-gradient(0deg, rgba(41, 49, 51, 0.5), rgba(41, 49, 51, 0.5)), url('/media/Images/Home_Pictures/1.jpg') ; background-position: 50% 50%;"> my second approach … -
[Django][Django Migration Linter] Does not work with Oracle
I discover the world of Python and Django, having to take charge of an existing project written in Python with the Django framework. This Django project has to be connected to a new database, an Oracle database. I see on the net a tool that seems to be very useful. This tool calls djanomigrationlinter (https://pypi.org/project/django-migration-linter/) It seems to be very useful to ckeck the migrations, i see a very instructive demo on the net which shows the use of Django Migration Linter. I take as dependency of the project django-migration-linter. I want to use it but it does not work with Oracle. Executing the command : python manage.py lintmigrations --sql-analyser oracle gives me the following error: I have few questions: Do you know a similar tool compatible with Oracle ? I found a work around that seems to work by replacing in my command oracle by postgresql (even if it is an Oracle database that is connected to the project) python manage.py lintmigrations --sql-analyser postgresql and it seems to "work", i mean that it gives information about the migrations without errors => Do you think that it is a good work-around without any similar tool (if a similar tool compatible … -
After successful login django giving 404 error
I have a login page, and after user logs in it should take him to the main page under articles. I have the main project called pnb, then i have 2 other apps, which are users and articles Under the pnb -> urls.py i have the following from django.contrib import admin from django.urls import path, include from users import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('signin', views.signin, name='signin'), path('signout', views.signout, name='signout'), path('articles', include('articles.urls')), ] Under users -> urls.py i have the following from django.urls import path from .views import home urlpatterns = [ path('', home, name = "home"), ] Under users -> views.py i have the following from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect import articles.views def home(request): return render(request, "users/home.html") def signin(request): if request.method =='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('articles/index.html') else: messages.error(request, "Bad Credentials") return redirect('home') def signout(request): logout(request) return redirect('home') Under articles -> urls.py i have the following from django.urls import path from . import views urlpatterns = [ path('', views.articles_view, name='articles_view'), ] Under articles -> views.py i have the following from django.shortcuts … -
Does Django store the tables inside the 'models.py' files for each app in the same database?
Just to make it clearer: suppose I have a Django project that contains multiple apps. Each one of those apps contains a 'models.py' file. Each one of those 'models.py' files contains multiple Python classes; each class represents a Python table. (If I said anything wrong, please correct me). If what I said above is true, my question is: does Django save ALL of those tables (from multiple apps) in the same database? If yes, can you 'join' data from tables that belong to different apps? I hope this makes sense. I have just started learning Django and following their official tutorial but I feel it skips a lot of these types of questions and I find myself copying stuff without understand too much how exactly it works so here I am. -
Formatting text in Python
I currently have a breadcrumb package which have successfully deployed into my website. The package displays the name of the name of the html document which is gleamed from the web directory. I'm still very new to Python. This correctly display the breadcrumb trail, however I need to format this. My code is as follows but Django appears to ignore any formatting I tell it to action. class BreadcrumbsItem: def __init__(self, name_raw, path, position, base_url=None): ..... self.remove_dashes = self.name_raw.replace("-", " ") .... def remove_dashes(self): formatted_path_name = str(name_raw) return formatted_path_name.replate("-"," ") Why are the items (page names) in the breadcrumbs in my HTML document not being removed? -
How to insert a new page data manually in wagtail database table?
I am using wagtail 2.10.2. And I want to use SQL query to manually create a page entry for a page type in database. Would like to know the steps and possible complications in doing so. Thanks How to achieve this with out breaking the existing setup which is up and running. -
Django factory-boy custom provider
I would like to create my own customer Faker provider. I am using factory-boy which comes already with Faker included, so in my test factories I am using for a UserFactory name = factory.Faker('name') My question is, can I somehow implement my own custom provider? So I could use factory.Faker('my_provider')? Or for that I would have to swap all factory.Faker() instances and just use Faker() instance? -
Error while adding exiting table from sql server in django app using django inspectdb -- error
I am try to use py -m django inspectdb , but not able to get success... I am able to connect database through django code in setting.py I am getting following error while using inspectdb command in windowds cmd shell py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py (seatenv) C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\OSeatMap\OSeatMap>py -m django inspectdb SeatLocation --database="DB_UUIS_ITO_BB" > seatlocation.py Traceback (most recent call last): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 58, in getitem return getattr(self._connections, alias) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\asgiref\local.py", line 105, in getattr raise AttributeError(f"{self!r} object has no attribute {key!r}") AttributeError: <asgiref.local.Local object at 0x000001B984F51750> object has no attribute 'DB_UUIS_ITO_BB' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 198, in run_module_as_main File "", line 88, in run_code File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django_main.py", line 9, in management.execute_from_command_line() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 46, in handle for line in self.handle_inspection(options): File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\core\management\commands\inspectdb.py", line 55, in handle_inspection connection = connections[options["database"]] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gg\Documents\ggg\Work\Project\Seat Mapping\seatenv\Lib\site-packages\django\utils\connection.py", line 60, in getitem if alias not … -
annotate django query by substring
How do you annotate a query set using a substring from a field? I presume something like this: query_by_domain = ( queryset .annotate(domain=Substr("email", F("email").Index("@") + 1)) .values("domain") .annotate(count=Count("id")) .order_by("domain") ) -
Is there something i am doing wrong?
import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; import '../styles/sales.css'; // Import the CSS file function Sales() { const [propertyData, setPropertyData] = useState([]); useEffect(() => { // Fetch data from your Django API using Axios axios.get('http://127.0.0.1:8000/api/v1/core/for-sale/') .then((response) => { // Limit the photos to a maximum of four const limitedData = response.data.slice(0, 4); setPropertyData(limitedData); }) .catch((error) => { console.error('Error fetching data:', error); }); }, []); return ( <div className="sales-container"> {propertyData.map((property) => ( <div key={property.id} className="property-card"> <Link to={`/property/${property.id}`}> <img src={property.main_photo} alt={property.title} className="property-image" /> <h2 className="property-title">{property.title}</h2> </Link> <p className="property-description">{property.description}</p> <p className="property-details"> {property.bedrooms} Bedrooms | ${property.price} </p> </div> ))} </div> ); } export default Sales; I was trying to fetch data from a django-rest api. I have installed the axios library, defined the CORS_ALLOWED_ORIGINS also added the corsheaders but the images cannot be rendered. I get the following error "Error fetching data: TypeError: response.data.slice is not a function" -
how to display cart items detail in html
my views.py def cart(request): context={'cart': Cart.objects.filter(is_paid=False)} return render(request, 'cart.html',context) my models.py class Cart(models.Model): is_paid=models.BooleanField(default=False) class CartItems(models.Model): cart=models.ForeignKey(Cart, on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.SET_NULL, null=True,blank=True) color_variant=models.ForeignKey(ColorVariant, on_delete=models.SET_NULL, null=True, blank=True) size_variant=models.ForeignKey(SizeVariant, on_delete=models.SET_NULL, null=True, blank=True) my cart.html {% if cart %} <tr> {% for item in cart %} <td class="product__cart__item"> <div class="product__cart__item__pic"> <img src="{% static "img/shopping-cart/cart-1.jpg" %}" alt=""> </div> <div class="product__cart__item__text"> <h6>{{item.product.name}}</h6> <h5>98</h5> </div> </td> <td class="quantity__item"> <div class="quantity"> <div class="pro-qty-2"> <input type="text" value="1"> </div> </div> </td> <td class="cart__price">$ 30.00</td> <td class="cart__close"><i class="fa fa-close"></i></td> {% endfor %} </tr> -
Implicit UUID auto fields for primary keys in Django
By default, Django adds integer primary keys as Autofields. This is annoying for many purposes, but especially makes debugging more difficult (code may accidently refer to the wrong "id", but instead of creating a runtime error, this might work in "some" instances because the IDs are accidently the same). I want either unique integers across all tables or UUIDs for primary key. I do not want to specify either explicitly, since I want to only use this for debugging (and switch back to integers in production). This is not a new proposal, but all answers seem to say "this is not performant" (blinding flash of the obvious) or advise to use explicit UUID fields (I don't want to do this because it means changing my model EVERYWHERE, then having to change it back later). Is there a way how to achieve this? The proposals I've looked at (none of which answer by question) can be found here: Using a UUID as a primary key in Django models (generic relations impact) and Django: Unique ID's across tables with an open ticket for this feature here https://code.djangoproject.com/ticket/32577 -
Django psycopg2 error while migrating the project
The following error occurs while doing manage.py migrate. psycopg2.errors.UndefinedTable: relation "relation_name" does not exist ... ... ... django.db.utils.ProgrammingError: relation "relation_name" does not exist Happened when I tried to set up a copy of my project elsewhere. Yes, I have installed all the dependencies. -
Why is my page displaying duplicate objects during pagination?
I've added in a sort-by dropdown option to my webpage but for some reason it's displaying duplicate objects on the page. Here's how the flow goes: User lands on webpage and list of objects (these are posts from other users) are displayed. This displays as expected User then changes the drop down to sort the posts by "newest" and the webpage is reloaded but the webpage is displaying 2 of each object/post. home_page.html that the user lands on: <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <form action="{% url 'posts:dropdown_selected' %}" method="get" name="sort_form"> <select class="rounded border-gray-200" name="sort_by" onchange="sort_form.submit()"> <option id="" value="placeholder" disabled selected hidden>Sort By</option> <option value="most_supported">Most Supported</option> <option value="newest">Newest</option> <option value="oldest">Oldest</option> </select> </form> </div> </div> {% if home_search %} {% for post in object_list %} <div class="bg-grey-lighter flex flex-col mt-2 mb-2"> <a href="{% url 'posts:post_detail' post.pk %}"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <div class="bg-white px-6 py-8 rounded shadow-md text-black w-full"> <img class="lg mb-6" src="" > <h1 class="mb-8 text-3xl text-center">{{ post.title }}</h1> <p class="text-gray-700 text-base"> {{ post.description }} </p> </a> <div class="relative flex-nowrap text-gray-500 mt-8 mb-0"> {% for tag in post.tags.all %} <div class="ml-4 text-xs inline-flex items-center … -
How do I specify OpenApiParameter properties for OBJECT type?
In drf-yasg when we specify Schema we have properties argument, where we can specify fields of OBJECT type. How do I get the same behavior for drf-spectacular's OpenApiParameter? @swagger_auto_schema( summary="Wallet balance", description="Save the wallet's balance", request=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'balance': openapi.Schema(type=openapi.TYPE_NUMBER), 'some_object': openapi.Schema(type=openapi.TYPE_OBJECT, properties={ 'a': openapi.Schema(type=openapi.TYPE_STRING), 'b': openapi.Schema(type=openapi.TYPE_STRING), }), } ), ) -
How to develop an E-commerce website using Python and Django as a server side language
I want to build an E-commerce website using Bootstrap, HTML, CSS, Java script in Frontend and For backend I want to use Python, Django and MongoDB. Can I get step wise instruction to develop files of codes of each language and how to link each one of them to make fully functional website. I want to know what directories and files will get added in code editor. -
Error display in the django admin through save_model
I have the following code in one of the classes related to the admin page: def save_model(self, request, obj, form, change): if change: if form.initial['delivered'] != form.cleaned_data['delivered']: for line in obj.lines.all(): book = line.book if not book.is_available and not obj.delivered: raise ValidationError('Error') if obj.delivered: number = line.book.number + 1 line.book.is_available = True else: number = book.number - 1 if not number: book.is_available = False line.book.number = number line.book.save() obj.save() return super().save_model(request, obj, form, change) The problem is that when the code reaches the raise ValidationError('Error') line and is executed, it doesn't show the error on the page and shows it like django debug errors, and this error is displayed only when DEBUG=True. How can I show this error like the django admin form errors? I also tried this code with django signals but it had the same result. Only when I wrote a class form myself and gave it to the admin class, it displayed the error correctly, but I cannot implement the conditions here in the form class. Is there a way to fix it in the save_model? -
Django file structure: cannot import main module without export PYPATH
I am using Django 4.0.4 Here is my project structure: root/ | README.md |-- app/ | |-- init__.py | |-- manage.py | |-- project/ | | |-- __init__.py | | |-- settings.py | | |-- urls.py | | |-- etc... | |-- webapp/ | | |-- __init__.py | | |-- apps.py | | |-- views.py | | |-- utils/ | | |-- migrations/ | | |-- etc... | |-- mediafiles/ |-- docs/ The imports inside de files are structured like this: apps.py => from app.project.settings import APP_NAME settings.py => from app.webapp.utils.paths import BASE_DIR urls.py => from app.webapp.views import home views.py => from app.webapp.models import MyModel In settings.py INSTALLED_APPS = [ "webapp", ... ] In short, nothing very unusual, except that my root folder is one level higher than in a standard Django installation. However, as soon as I run python app/manage.py runserver localhost:8000 # OR python manage.py runserver localhost:8000 # (inside the `app/` directory) I get a ModuleNotFoundError: No module named 'app' The problem is fixed if I set the PYTHONPATH variable inside the root/ directory: export PYTHONPATH="$(pwd)" If I remove the app from my imports, then the command works but my IDE (PyCharm) no longer lets me take advantage … -
ExtJS paging/pagination loads all records at page load
I am trying to set up paging for a grid in my ExtJS app. Let's say I want to show 30 records per page and I have a total of 35 records. No matter what, when I visit the view, the grid always loads all 35 records in the first page although the paging bar shows the presence of two pages (see image). The navigation buttons in the paging bar don't work in that, for example, when I hit the "Next page" button, I get the following error: Uncaught TypeError: store.nextPage is not a function at constructor.moveNext (ext-all-debug.js:185314:23) at Object.callback (ext-all-debug.js:8705:32) at constructor.fireHandler (ext-all-debug.js:144259:17) at constructor.onClick (ext-all-debug.js:144241:16) at constructor.fire (ext-all-debug.js:20731:42) at constructor.fire (ext-all-debug.js:34336:27) at constructor.publish (ext-all-debug.js:34296:28) at constructor.publishDelegatedDomEvent (ext-all-debug.js:34318:14) at constructor.doDelegatedEvent (ext-all-debug.js:34361:16) at constructor.onDelegatedEvent (ext-all-debug.js:34349:18) Hitting the "Last page" button doesn't raise an error, yet it just loads the same 35 records. When I check my webserver logs, I can see that, when I visit the view, my app doesn't just request the first page of record but all of them, which makes no sense: [20/Sep/2023:10:09:55 +0200] "GET /api/requests/?page=1 HTTP/2.0" [20/Sep/2023:10:09:56 +0200] "GET /api/requests/?page=2 HTTP/2.0" I checked the API output of /api/requests/?page=1, generated by Django REST Framework, and it returns … -
Trying the 'share chat' feature for my Chatbot but its not working
I'm working on a chatbot app, and I need to add a feature in it, "share chat" which is basically the ChatGPT feature of sharing your chat. So, I'm able copy the link generated for the chat page that is opened, and when i open the link in the new tab, the page is opening as expected and we can chat in it, but only as long as we're logged in. I mean if I tried to open that link in an incognito window, or if a non-logged in user tries to open that link, it wont open. It's probably because of the @login_required decorator we are using in the Django Backend but we can't remove it since it's required for authentication. I need to a way to implement sharing the chat and even if the user is not logged in they can open and use it. The frontend is made using HTML,CSS and JS, while the backend is Python-Django. I tried opening the link without using the @login_required decorator but it was still not working. Please let me know what approach I can take here? Like what needs to be done from the backend side or frontend?