Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Trying to save Image to django model
I used beautiful soup to scrap and extract images from a website describe below successfully but when I viewed the extracted images they appear as Url as shown below. I then experience difficulty in attempting to save the scraped image to my django database as a particular error shown below keeps on appearing. After I got the error I also tried using a forloop to create the post because I thought am trying to save a list element in a single data but it still shown the same or I got the same error not commited but when I remove the image scrap data from the file in title, summary, content and try to save to django database.it was a success. Saving image is the problem and I need help Below is my sample code My scraped images appear as a list of url as shown below https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] but am unable to save the images scraped above like this because it will bring an error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this will bring an error when i try saving to models … -
Is there any reporting tool similar StimulSoft for using in Python and Django?
I'm looking for a reporting tool which capable generate printable docs same as StimulSoft in .net. I'm new in Django and I would be glad to help me. thanks -
PayPal payment method with commission
I am currently working on a project on which one user can personally send files or documents to other users. If the sender wants he could set a price for the file and the receiver have to pay in order to download that file. I have decided to use PayPal for the payment processes. Now from each transaction(of money), I want a little commission from the money that the sender gets. At first I had a idea of receiving all the payments(form the receiver) on my personal account, keep some commissions and transfer the remaining to the sender. But it would make the entire process so difficult and hard to maintain. I have currently read this and I am wandering if that gives you some commission for the transactions or it doesn't? At the end, My question is 'Can you get some commission(or money) using paypal payee.(or directly sending the money form sender to receiver)?' If I have made some mistakes, Please forgive me.. Thank you -
Filter related values from Django Admin M2M relation
Is it possible to filter related values in Django admin? I have many to many relationship set to be displayed inline. However there are many values so I want to somehow be able to search/filter those that I need. So here are the two models (I used Join table): # Create your models here. class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') class Meta: verbose_name_plural = "Countries" def __str__(self): return self.name class OpenDestination(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') origin_country = models.ManyToManyField(Country, through='BorderStatus') def __str__(self): return self.name class BorderStatus(models.Model): STATUS_CHOICES = [ ('OP', 'OPEN'), ('SEMI', 'CAUTION'), ('CLOSED', 'CLOSED') ] Country = models.ForeignKey(Country, on_delete=models.CASCADE) OpenDestination = models.ForeignKey(OpenDestination, on_delete=models.CASCADE) status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='CLOSED') class Meta: unique_together = (('Country', 'OpenDestination')) def __str__(self): return str(self.Country) + ' and ' + str(self.OpenDestination) And in admin.py class OpenDestinationInline(admin.TabularInline): model = OpenDestination.origin_country.through class ConutryAdmin(admin.ModelAdmin): inlines = [ OpenDestinationInline ] filter_horizontal = ('origin_country',) admin.site.register(Country, ConutryAdmin) admin.site.register(OpenDestination) admin.site.register(BorderStatus) So now when I access one coutry from Country model I see list of many countries from OpenDestination model (each having own status thanks to the Join Table). Now Im trying to figure out if its possible to filter countries from 'OpenDestination' when accessing single country from 'Country'. I tried adding filter_vertical/horizontal … -
Celery task not saving into Django sqlite db
I'm new to programming and I'm trying to schedule a task with celery to save data into sqlite db. I can't seem to get the data into the database. I am using redis as my broker, windows 10, and the latest version of both celery and django. models.py from django.db import models class Ticker(models.Model): BULLISH = 'Bullish' BEARISH = 'Bearish' NEUTRAL = 'Neutral' SENTIMENT = ( (BULLISH, 'Bullish'), (BEARISH, 'Bearish'), (NEUTRAL, 'Neutral'), ) ticker = models.CharField(max_length=200) date_posted = models.DateTimeField() sentiment = models.CharField(max_length=200, choices = SENTIMENT) sentence = models.TextField() def __str__(self): return ("Ticker: " + str(self.ticker) + " Date: " + str(self.date_posted) + " Sentiment: " + str(self.sentiment)) celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wsbscraper.settings') app = Celery('wsbscraper') app.config_from_object('django.conf:settings', namespace='CELERY') @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'main.tasks.scrape_test', 'schedule': 10.0, # 'args': (16, 16) }, } # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @shared_task def simple_print(): print("Hello World!") @shared_task def scrape_reddit(): run() @shared_task def scrape_test(): test_run -
django data shows all but images
My product card: product name and price shows but not image <Card> <Card.Img src={product.image_one} /> <Card.Body> <Card.Title as="div"> <strong>{product.name}</strong> </Card.Title> <Card.Text>${product.price}</Card.Text> </Card.Body> </Card> My settings.py: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_ROOT = 'static/images' My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('core.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The image shows when i enter in the image url in replace of the image_one props. What am i doing wrong? -
Using jquery clone function only one data is saved to database Django
if there are two forms then only the value of last form is registered on the data base if clicked on submit button. The thing that i want is to dynamically add forms according to the integer provided by the user (eg. If the user wants 3 rooms then 3 forms are to be added dynamically) and the data in the form is to be added on the database HTML CODE <form id = "mainForm" method ="post"> {% csrf_token %} <div id="first-group" class = "new"> <div id="bookform"> <n class="fa fa-user" aria-hidden="true"></n> <input name="name" type="text" id="input" placeholder="Name" name="name" required/> </div> <div id="bookform"> <n class="fa fa-flag" aria-hidden="true"></n> <select name="nationality" id="nation" style="width: 95%; border: none;" required> <option data-display="">Nationality</option> <option value="afghan">Afghan</option> <option value="albanian">Albanian</option> <option value="algerian">Algerian</option> <option value="american">American</option> <option value="andorran">Andorran</option> <option value="angolan">Angolan</option> <option value="antiguans">Antiguans</option> <option value="argentinean">Argentinean</option> <option value="armenian">Armenian</option> <option value="australian">Australian</option> <option value="austrian">Austrian</option> <option value="azerbaijani">Azerbaijani</option> <option value="bahamian">Bahamian</option> <option value="bahraini">Bahraini</option> <option value="bangladeshi">Bangladeshi</option> <option value="barbadian">Barbadian</option> <option value="barbudans">Barbudans</option> <option value="batswana">Batswana</option> <option value="belarusian">Belarusian</option> <option value="belgian">Belgian</option> <option value="belizean">Belizean</option> <option value="beninese">Beninese</option> <option value="bhutanese">Bhutanese</option> <option value="bolivian">Bolivian</option> <option value="bosnian">Bosnian</option> <option value="brazilian">Brazilian</option> <option value="british">British</option> <option value="bruneian">Bruneian</option> <option value="bulgarian">Bulgarian</option> <option value="burkinabe">Burkinabe</option> <option value="burmese">Burmese</option> <option value="burundian">Burundian</option> <option value="cambodian">Cambodian</option> <option value="cameroonian">Cameroonian</option> <option value="canadian">Canadian</option> <option value="cape verdean">Cape Verdean</option> <option value="central african">Central African</option> <option value="chadian">Chadian</option> <option value="chilean">Chilean</option> <option value="chinese">Chinese</option> <option … -
How to get the pk of several objects in the domain name url www.site.com in Django
I try to build a blog and this blog in the home view www.site.com consist of posts and these posts have comments, Now I Show the posts using List [] because the user has the ability to follow the content and in this list, I show the content based on the user, Now I successfully to show the posts but this post contains comments that's mean I need to get the pk of the post but as I said this post in the home view www.site.com without any extra URL that's mean as My knowledge I can't pass the pk in the def home_screen_view(request, pk) because this raise error home_screen_view() missing 1 required keyword-only argument: 'pk' So my qustion how can I get the pk in the base url www.site.com My view def home_screen_view(request, *args, **kwargs): users = [user for user in profile.following.all()] post = [] for u in users: p = Account.objects.get(username=u) posts = p.post_set.all() post.append(posts) my_posts = request.user.post_set.all() post.append(my_posts) if len(post): post= sorted(chain(*post), reverse=True, key=lambda post: post.created_date) posts = Post.objects.filter(pk=post.pk) # here I want to get the pk of the post in order to show the comments related this post comment = PostCommentIDE.objects.filter(post=posts) The url path('', home_screen_view, name='home'), … -
Django image compression and resize not working
I don't understand why this code can't resize image? Why image is uploading it's actual size? here is my code: #models.py from django.db import models from PIL import Image class Post(SafeDeleteModel): header_image = models.ImageField(upload_to="blog/images/", blank= True, null= True) def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.header_image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.header_image.path) I aslo want to know how to applay format and quality attribute of PIL in django model. see below: ("kenya_buzz_compressed.jpg", format="JPEG", quality=70) -
mutiple time data saving problem in django sqllite3
i using django with sqllite i create a survey form with the help of django model and django forms but when i hit submit i see sometime data save twice in my database is it happen normally or something wrong with my code from django.shortcuts import render, redirect from django.contrib import messages from django.template.response import TemplateResponse from .forms import SurveyForm # Create your views here. def index(request): if request.method == 'POST': form = SurveyForm(request.POST) if form.is_valid(): form.save() return TemplateResponse(request, 'thankyou.html') else: return messages.error(request, 'Please fill the form to continue') else: form = SurveyForm() return render(request, 'learnersform.html', {'form': form}) -
Use object variable in base.html of Django
I come from Ruby on Rails and I am trying to learn Django. There are multiple things that puzzle me when it comes to how to solve simple things. I have a sidebar in which I would like to have a link to a random item. My first thought was to use: <a href="{% url 'headline_detail' Headline.objects.order_by('?')[0].id %}">Random headline</a> Although it works perfectly fine to run Headline.objects.order_by('?')[0].id in the shell, this causes an error in Django: Could not parse the remainder: '('?')[0].id' from 'Headline.objects.order_by('?')[0].id' which I find very weird since 'Headline.objects.order_by('?')[0].id' creates a number (id) and if I put the same number in as <a href="{% url 'headline_detail' 123 %}">Random headline</a> it works perfectly fine. Another option would be to create this previously in the template, like {% rand_id = Headline.objects.order_by('?')[0].id %} <a href="{% url 'headline_detail' Headline.objects.order_by('?')[0].id %}">Random headline</a> which is I would hotfix it in Rails - but this doesn't work. The third option (which is better than the 2nd) is to put the variable in the view. However, this is not really viable since this code is in the sidebar and I cannot pass this in every view (DRY!). So, I figure out I should use context templates, … -
Tutorial for browser-sync setup for Wagtail
I am new to python world and finished Codeforeveryone Wagtail videos. I have wireframe website that I have added to Wagtail but could not figure out how to get browser-sync to work. Could anyone suggest what I need to do to get this browser-sync setup working so that html, css, scss update automatically after I hit the save button? -
DRF: Need Guidance to perform a task
I need to create an API to book a call with an advisor Endpoint: /user/<user_id>/advisor/<advisor_id>/ for this used path('user/<int:user_id>/advisor/<int:advisor_id>') in urls.py but the problem is I have to request a Booking time(a DateTime sting) when I make a request to that link which I can perform via PostMan In serilaizer.py I used: class BookingSerializer(serializers.ModelSerializer): class Meta: model = models.Booking fields = '__all__' def create(self, validated_data): user = models.Booking.objects.create( user=validated_data['user'], advisor=validated_data['advisor'], time=validated_data['time']) user.save() return user In this i have pass everything via the body in postman but I want to use the user_id and advisor_id from the url and just want to provide DateTime string via body in PostMan -
Django form field has initial value and is disabled, but not being submitted
tldr I'm having a problem that seems like it's fairly basic, but I can't figure it out. It seems that if a form field is disabled, and that field is instantiated with an initial value, the initial value correctly displays in a rendered template, but that field does not get submitted with the POST payload, which I would expect. Details In my Django application I have: a form with two required fields, field1 amd field2. a template that displays the form and allows submission a view that On a GET, renders the template with the form unbound On a POST, validates the data and either does something (if valid) or renders the template with the bound form if the submission had errors. Desired behavior On a GET, have the view provide an initial value for field1 That value needs to be set dynamically, so I can't just set a default on the field Have the value be visible, but not editable, by the user Have the value submitted with the form on a POST My attempt What I expected to work was: Render the unbound form by passing initial= Set the form field to disabled=True. Reproducible example This is on … -
Why does my Submit button renders a page that is blank when it is supposed to contain the data that was just updated?
I'm trying to update the values of my database using a HTML Form. When I Click Edit it brings me to the edit the values above. However as I am clicking the submit button, it returns me a database but with no other values. Is there anyone that can help me understand what I did wrong and point me to the right documentation (if any) editclaims.html: <div class="arrange2"> <h1>Edit Claim Form - #{{claims.id}} </h1> </div> <form method="POST" action="/update/{{claims.id}}"> {% csrf_token %} views.py: def editclaims(request,id): context = initialize_context(request) user = context['user'] claims = SaveClaimForm.objects.get(id=id) return render(request, "Login/editclaims.html",{'claims':claims, 'user':user}) def updateclaims(request, id): context = initialize_context(request) user = context['user'] claims = SaveClaimForm.objects.get(id=id) form=reclaims(request.POST, request.FILES, instance=claims) if form.is_valid(): form.save() messages.success(request,"The Claim has been updated successfully.") return render(request, "Login/existingclaims.html", {'SaveClaimForm':claims, 'user':user}) urls.py: urlpatterns = [ path('existingclaims/', views.viewclaims, name='existingclaims'), path('editclaims/<int:id>', views.editclaims, name='editclaims'), path('update/<int:id>', views.updateclaims, name='updateclaims'), ] -
Hide buttons if user doesn't belong to any of Django groups
My problem is that I want to hide the button from all users who are not in group1 and group2 or in both groups. I did the following thing but it seems doesn't work at all. My views.py: def is_group1(user): return user.groups.filter(name='Group1').exists() def is_group2(user): return user.groups.filter(name='Group2').exists() def employee_list(request): groups = [g.name for g in request.user.groups.filter(name__in=['Group1', 'Group2'])] context = {'employee_list': Employee.objects.filter(dept__in=groups)} return render(request, 'employee_register/employee_list.html', context) My little example of employee_list.html: <form> {% if user.is_group1 %} <button formaction="{% url 'employee_insert' %}">Add</button> {% if user.is_group2%} <button formaction="{% url 'employee_insert' %}">Add</button> {% else %} <p>You are not logged</p> {% endif %} </form> Any thoughts how I can implement this ? -
"ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine" when i tried to add image in db
# Create your models here. from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ import uuid from django.db.models.signals import post_save, post_delete from django.utils.timezone import now class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email,username, first_name, last_name, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email,username=username,first_name=first_name,last_name=last_name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): """User model.""" username = models.CharField(max_length=200, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.EmailField(('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Post(models.Model): """post model""" id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) name = models.CharField(max_length=100,null=False) picture … -
Select a valid choice while selecting Foreignkey in django admin mongodb
database in MongoDB (djongo) I have registered a model in admin.py admin.site.register(Media) models.py class Media(BaseModel): _id = models.ObjectIdField(primary_key=True) url = models.URLField() media_type = models.CharField(max_length=100) user = models.ForeignKey(User, db_column="user", on_delete=models.CASCADE) post = models.ForeignKey(Post, db_column="post", on_delete=models.CASCADE) group = models.ForeignKey(Group, db_column="group", on_delete=models.CASCADE) class Meta: db_table = "media" while changing values using the admin site I got these errors. can you help me to solve this error? django==3.0.5 djongo==1.3.4 -
Multiple Django admin site on same server ,login abnormal
I deploy serveral django web sites on windows with IIS on same server,such as A,B,C. Each site works,but when I login django admin on site A,the login of django admin on site B and C will logout and each operation need relogin. Browser is chrome. I want these sites don't interfere each other. Is there lack of django configuration? -
Rendering a dictionary in a template
While rendering values of a dictionary in a template, some values are showed outside the html table. I cant realize why. Any ideas? Thanks in advance, #This is how the dictionary is printed in console [{'socio': 'Randazzo Walter Ariel 25', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': 'P', 'agosto': 'P', 'septiembre': 'P', 'octubre': 'P', 'noviembre': 'P', 'diciembre': 'P'}, {'socio': 'Silvi Edgardo Marcelo 31', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': '-', 'agosto': '-', 'septiembre': '-', 'octubre': '-', 'noviembre': '-', 'diciembre': '-'}] #this is how the template is rendered #Template: <table class="table" style="width: 100%;"> <thead> <tr style="border: 1px solid black;"> <th style="width: 30%; text-align: center;">SOCIO</th> <th style="width: 25%; text-align: center;">ENE</th> <th style="width: 25%; text-align: center;">FEB</th> <th style="width: 25%; text-align: center;">MAR</th> <th style="width: 25%; text-align: center;">ABR</th> <th style="width: 25%; text-align: center;">MAY</th> <th style="width: 25%; text-align: center;">JUN</th> <th style="width: 25%; text-align: center;">JUL</th> <th style="width: 25%; text-align: center;">AGO</th> <th style="width: 25%; text-align: center;">SEP</th> <th style="width: 25%; text-align: center;">OCT</th> <th style="width: 25%; text-align: center;">NOV</th> <th style="width: 25%; text-align: center;">DIC</th> </tr> </thead> <tbody> {% for pago in pagos %} <tr {% if forloop.first %}style="padding-top: 3px;" {% endif %}> <td class="text-center">{{ pago.socio }}</td> <td class="text-center">{{ … -
How to check if session is expired in Django views?
I am using Django session framework for login and logout functionality in my application. I do have multiple Django views as per business requirements. I have login view where I call authenticate() function to start the session for a user. But,I want to know how do I check whether session is valid when user calls different views. I am planning to implement using following code snippet. Can I someone tell me if this is the correct way of checking whether session is active or expired? def login(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) user_name = body['user_name'] password = body['password'] user = authenticate(user_name,password) if user is None: ... else: ... return JsonResponse(...) def view_1(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) user_name = body['user_name'] session_key = body['session_key'] # is below code a correct way to validate for user session if request.session['user_name'] == user_name and request.session.session_key == session_key: print('session active') else: print('session expired') -
Modifying django-allauth library
GitHub library: https://github.com/pennersr/django-allauth Package installed using pipenv. I have installed this library and made the settings so that the authentication is working fine. How do I make changes to login and signup html files as I have to add lots more html content on those pages? These files are in the allauth module which is not visible under my project directory as I installed it using pipenv. -
ModuleNotFoundError: "No module named <mymodule>", when deploying to Heroku from Django
When deploying my Django app to Heroku, I get a ModuleNotFoundError that states "no module named 'RealisticEstate'". RealisticEstate is the name of my Django project. The program builds no problem, but when I try to deploy I get the following errors: [2021-05-13 21:35:45 -0400] [15610] [INFO] Starting gunicorn 20.1.0 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15610] [INFO] Listening at: http://0.0.0.0:5000 (15610) 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15610] [INFO] Using worker: sync 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15613] [INFO] Booting worker with pid: 15613 9:35:45 PM web.1 | [2021-05-13 21:35:45 -0400] [15613] [ERROR] Exception in worker process 9:35:45 PM web.1 | Traceback (most recent call last): 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site- packages/gunicorn/arbiter.py", line 589, in spawn_worker 9:35:45 PM web.1 | worker.init_process() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 9:35:45 PM web.1 | self.load_wsgi() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 9:35:45 PM web.1 | self.wsgi = self.app.wsgi() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 9:35:45 PM web.1 | self.callable = self.load() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 9:35:45 PM web.1 | return self.load_wsgiapp() 9:35:45 PM web.1 | File "/Users/<user>/RealisticEstate/venv/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in … -
How can I change a string on swagger url
This String in particular [string to change][1] [1]: https://i.stack.imgur.com/3xn3s.png Class View class ServiceProviderBaseUnityAvaliationsView( mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [permissions.IsAdminUser, ] pagination_class = PageNumberPagination serializer_class = ServiceProviderBaseUnityAvaliationSerializer queryset = ServiceProviderBaseUnityAvaliation.objects.all() def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) -
Django and JavaScript pagination for SPA - possible to make this without repeating myself?
My website is single page application, 3 different pages. 3 JavaScript functions. 3 Methods in the Django backend ( 1 for each JavaScript function ) My backend methods return paginated posts, each JavaScript function uses fetch from a different URL that works with a different method in the backend I'm trying to add paginate buttons on the frontend, say I've added divs for the buttons, now I'm stuck with solving the problem that how when I click for example on the "next" button to fetch from the right URL again without needing to make a pagination frontend function for each JavaScript with a different fetch URL? I'm trying to do this without repeating myself in more than 1 function. views.py def show_all_web_posts(request): """ Method to return all posts in the database. """ all_web_posts = NewPost.objects.all() all_web_posts = all_web_posts.order_by("-date_added").all() page_number = request.GET.get('page', 1) paginator = Paginator(all_web_posts, 10) current_page_posts = paginator.page(page_number) posts_paginated = current_page_posts.object_list return JsonResponse({ "posts": [website_post.serialize() for website_post in posts_paginated] }, safe=False) def display_profile_posts(request, profile_name): """ Method to return all posts that is related to specific profile. """ try: profile = User.objects.get(username=profile_name) profile_posts = NewPost.objects.filter(poster=profile.id) profile_posts = profile_posts.order_by("-date_added").all() page_number = request.GET.get('page', 1) paginator = Paginator(profile_posts, 10) current_page_posts = paginator.page(page_number) profile_posts_paginated …