Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript code is not working but file is linked correctly
First function working correctly when i delete second one but when i rewrite it it doestn't work! Here is the javascript file. window.onload=function(){document.getElementById('loader').style.display='none';}; function toggle(){var blur = document.getElementsByClassName('blur'); blur.classList.toggle('active'); }; Please help me to solve it out. Here is HTML file. {% load static %} <html> <head> <meta name="website" content="Coding Tutorials" /> <meta name="keywords" content= /> <meta name="robots" content="nofollow" /> <meta http-equiv="author" content="Navneet Kaur" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Just Code </title> <link rel="stylesheet" href="{% static '/css/home.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static '/css/googlesearch.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"/> <link href="https://fonts.googleapis.com/css2?family=Limelight&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="{% static 'images/favicon48.png' %}" sizes="48×48" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon96.png' %}" sizes="96×96" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon144.png' %}" sizes="144×144" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon192.png' %}" sizes="192×192" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon288.png' %}" sizes="288×288" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon384.png' %}" sizes="384×384" type="image/png"> <link rel="shortcut icon" href="{% static 'images/favicon576.png' %}" sizes="576×576" type="image/png"> <style> @font-face { font-family: 'Blanka-Regular'; src: local('Blanka-Regular'), url('{% static 'fonts/Blanka-Regular.otf' %}'); } </style> </head> <body> <div id="loader"> <img src="{% static 'images/preloader.gif' %}" alt="Loading"/> </div> <div class="blur"> <div id="searchoverall"> <div class="dropdown"> <a href="#"class="divasigninbttn dropbttn"><img id="signinbttn"src="{% static 'images/signinbttn.jpg' %}" alt="signin"></img></a> … -
How to modify the id field in django-rest-framework-simplejwt?
I have a custom token serializer: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class TokenObtainPairWithoutPasswordSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password'].required = False def validate(self, attrs): attrs.update({'password': ''}) return super(TokenObtainPairWithoutPasswordSerializer, self).validate(attrs) This worked but now I'd like to change the id -field of my User to be userId and after that I can't get tokens anymore because it is searching for a field id. There must be some pretty simple way to modify this? -
multiple Modelform, multiple selection and multiple records
My aim is to put all the questions(IsSoru) of the relevant section and the options(IsSecenek) under the questions from the questions table on a page. To save by entering the person information(UserIs) at the bottom after the selected answers. To do it all with a single submit button. models class IsSoru( models.Model ): soru= models.CharField(max_length=145) metin_tr = models.CharField(max_length=250) sira = models.IntegerField() isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) class IsSecenek( models.Model ): secenek_tr = models.CharField(max_length=145) sira = models.IntegerField() issoru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) class UserIs( models.Model): eposta = models.EmailField(max_length=145) telefon = models.CharField(max_length=145) adres = models.CharField(max_length=245) sehir = models.CharField(max_length=45) mesaj = models.TextField() tarih = models.DateTimeField(auto_now_add=True) isdurumu = models.CharField(max_length=45, default='Yeni' ) isaltgrup = models.ForeignKey(IsAltGruplari, on_delete=models.CASCADE) kullanici = models.CharField(max_length=150) class Cevap( models.Model ): soru = models.ForeignKey(IsSoru, on_delete=models.CASCADE) cevap = models.ForeignKey(IsSecenek, on_delete=models.CASCADE) useris = models.ForeignKey(UserIs, on_delete=models.CASCADE) forms class UserIsForm(forms.ModelForm): class Meta: model = UserIs fields = ("kullanici", "eposta", "telefon", "adres", "sehir", "mesaj", "isaltgrup") widgets = { 'kullanici': forms.TextInput(attrs={'id': 'name','placeholder': _('Name/Surname'),"required":""}), 'eposta': forms.EmailInput(attrs={'id': 'email','placeholder': _('E-mail'),"required":""}), 'telefon': forms.TextInput(attrs={'id': 'phone','placeholder': _('Phone'),"required":""}), 'adres': forms.TextInput(attrs={'id': 'address','placeholder': _('Address'),"required":""}), 'sehir': forms.Select(attrs={'id': 'privence','placeholder': _('Privence'),"required":""}), 'mesaj': forms.Textarea(attrs={'id':'message', 'placeholder': _('Your Message'),"required":""}), } labels = {'kullanici':'', "eposta":'', "telefon":'', "adres":'', "sehir":'', "mesaj":'', "isaltgrup":''} class UserCevapForm(forms.ModelForm): class Meta: model = Cevap fields = ("cevap", "soru") view class SecDetay_View(CreateView): model = UserIs … -
from .api.serializers import EmployeeSerializer ModuleNotFoundError: No module named 'Auth.api.api
I am getting the following error when I trying to include my app URLs in base URLs Auth.api.views urlpatterns = [ path('', views.employee_list), ] Base.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Auth.urls')), path('api/', include('Auth.api.urls')), path('api-auth/', include('rest_framework.urls')), ] -
How to set custom primary keys of different models as foreign key and migrate to mysql properly in django?
I created this model for my django project and connected it with mysql. I created customerid as the primary key in the Customer model and used it as a foreign key in the cart to represent the owner. There should not be an id field since django does not create one when primary key is true. Whenever I try to migrate the model, it errors "Cannot drop 'id': needed in a foreign key constraint 'api_cart_owner_id_c65befd7_fk_api_customer_id' of table 'api_cart'"). I tried fake migration but that created an unwanted id field in the mysql schema. And if I leave it like that and make a post request with a customerid I get this error "Incorrect integer value: '' for column 'owner_id' at row 1". I suppose that owner_id is looking for id field from customer model instead of customerid. I believe I have not set the cart model correctly. How do I represent the customerid and itemid (custom primary keys of different model) as a foreign key for the cart model and migrate it properly? class Item(models.Model): itemid = models.TextField(primary_key=True) name = models.TextField() price = models.FloatField() quantity = models.IntegerField() ordered = models.IntegerField(default=0) def __str__(self): return self.name class Customer(models.Model): customerid = models.TextField(primary_key=True) name … -
how to make a field in Django only superuser editable and for other users it is read only?
my model class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE, null=True, blank=True) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) answer = models.TextField(default='') This is a question model where a user is allowed to post new questions but i want that this answer field is only superuser editable and a normal user have only readonly access for that field, needs help i searched for possible answers but didn't get any -
Why is my dockerized Django app so slow and shows ([CRITICAL] WORKER TIMEOUT)?
I'm trying to deploy a Django app in a Docker container. It works well but the first time I open a page I receive these messages: [CRITICAL] WORKER TIMEOUT [INFO] Worker exiting [INFO] Booting worker with pid: 19 The next time I open the same page it's pretty fast. Here's my Dockerfile (generated by wagtail app starter) FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application How can I fix that? -
How to copy a Django SQlite database to a Docker container?
I'm new to Docker. I am trying to dockerize a Django app. My project contains a Wagtail app and I'm using the auto generated Dockerfile by Wagtail. FROM python:3.8.6-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ nano \ vim \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . . USER wagtail RUN python manage.py collectstatic --noinput --clear CMD set -xe; python manage.py migrate --noinput; gunicorn mysite.wsgi:application It's working well but my sqlite Database is empty and I'd like to run my container with the wagtail pages that I will create locally. How can I change the Dockerfile for that endeavor? -
Can't figure out why I'm getting `Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found` in a django project
The project has 2 apps - accounts (very basic custom users) and portal. myproject/myproject/urls.py: from django.contrib import admin from django import urls from portal import admin as user_admin from portal import views urlpatterns = [ urls.path(r'admin/', admin.site.urls), urls.path(r'portal/mymodel/', views.testview), urls.path('', user_admin.user_site.urls), ] myproject/portal/templates/portal/mymodel/testview.html: {% extends "admin/change_list.html" %} {% block after_field_sets %}{{ block.super }} <h2> hello world </h2> {% endblock %} myproject/portal/templates/portal/views.py: from django.shortcuts import render def testview(request): return render( request, 'portal/mymodel/testview.html', {'app_label': 'portal'} ) and the stacktrace: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or self.get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me:D/myproject/venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or … -
Source specified in Javascript not showing up in Django template
Maybe this is a really dumb question, but I'm learning Javascript and Django and can't figure it out. I've spent a few hours on this and maybe it's a syntax error or something else. I want to specify the source of an image in javascript and then display the image in Django HTML template. It's not working, even with simple images Here is my javascript: $(document).ready(function() { var image = document.getElementById("image").src('https://res.cloudinary.com/.../{{ object.id}}'); } Here is my image info: <img src="#" id="image" class="mx-auto" width="250px" onerror='this.onerror = null; this.src="https://res.cloudinary.com/.../image.jpg"'/> What am I doing wrong? It's definitely not working - the image is not showing up even when it exists. I either get the default image or no image. -
When and what data should be cached?
I want to know when should I cache data? Should I cache ListViews? or DetailViews? What kind of data do I need to cache and does the amount of data matter? When to cache? When not to cache? I want to know when should I decide to cache data? P.s: I don't want to know how to cache, what I want to know is when to cache. -
How to check if redis connection is available when server starts running in django rest framework and return the error response if not connected
I'm doing multiple API calls but in each API call I'm checking if redis connection is available. showing only one of the API calls below. def check_redis_conn(): redis_exists = RedisCache.is_redis_available() if redis_exists is True: set_Data = RedisCache.set_data("message", "This is redis Test") return True else: return redis_exists def hello_vortex(request): is_redis_connected = check_redis_conn() if is_redis_connected is True: data = {'Description': 'This is the sample API call', 'version': 1.0} return JsonResponse{data,safe=False} else: return is_redis_connected RedisCache class: @classmethod def set_connect(cls): try: redis_instance = redis.StrictRedis( host='127.0.0.1', port=6379, ) @classmethod def get_conn(cls): try: cls.redis_instance = cls.set_connect() return cls.redis_instance except Exception as e: return JsonResponse{'message':'Error while connecting', safe=False} @classmethod def is_redis_available(cls): try: isConn = cls.get_conn() isConn.ping() return True except Exception as e: return JsonResponse{'message':'Error while connecting', safe=False} How can I check the redis connection only once when the server starts and return the Json Response on the server if the connection is not available. -
Tweet won't embed in django
Here's my html for my Django Twitter project. I am trying to embed tweets in Django <html lang="en"> <h1>Tweets</h1> <form action="" method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> <body> {% if tweets %} <p>{{tweets}}<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p> {% endif %} </body> </html> Here's my views.py: import tweepy from tweepy.auth import OAuthHandler from .models import Tweet from .models import Dates from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.shortcuts import render from django.db import models, transaction from django.db.models import Q import os import tweepy as tw from .forms import TweetIDForm from django import template import requests consumer_key = 'dddddd' consumer_secret = 'cccccc' access_token = 'dddddd' access_token_secret = 'ccccc' def clean_tweet_id(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TweetIDForm(request.POST) print(form) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required tweet_id = form.cleaned_data.get("tweet_id") #act = form.cleaned_data.get("action") auth = tw.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tw.API(auth, wait_on_rate_limit=True) twtjson = requests.get('https://publish.twitter.com/oembed?url=' + tweet_id + '&omit_script=true') tweets = twtjson.json() tweet = tweets.get('html') return render(request, 'tweet/tweet-list.html', {'form': form, 'tweet_id':tweet_id, 'tweets': tweet}) My code … -
django html set class as query set items
I have a query set that wants each string/item display in a class name for example : queryset = classes.all() what I tired: <div class="queryset"><h4>student1</h4></div> what I got: <div class="<QuerySet [<classTag: English>, <classTag: Math>, <classTag: CS>]>"><h4>student1</h4></div> what I want: <div class="English Math CS"><h4>student1</h4></div> -
Having solme logical error in my RegisterClass View?
My models.py Here I am have registered_students in as many to many field to Registered Names to store all the students that have registered for the class class RegisteredNames(models.Model): name = models.CharField(max_length=100, unique=True) class LiveClass_details(models.Model): chapter_details = models.TextField(default='') mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) no_of_students_registered = models.IntegerField(default=0) registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True) no_of_students_attended = models.IntegerField(default=0) This model is for registering a student class RegisteredClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) my views.py @api_view(['GET', 'DELETE']) @permission_classes((IsAuthenticated, )) def RegisterClassId(request, id): print(request.method) if request.method == 'GET': print("in get method") if not models.RegisteredClass.objects.filter(class_details=models.LiveClass_details.objects.get(id=id), user=request.user).exists(): print("in get method") registered_class = models.RegisteredClass.objects.create(class_details=models.LiveClass_details.objects.get(id=id), user=request.user) registered_class.save() registered_live_class = models.LiveClass_details.objects.get(id=id) registered_live_class.no_of_students_registered += 1 registered_live_class.no_of_students_attended += 1 # registered_live_class.save() print(request.user.username) registered_name = models.RegisteredNames(name=request.user.username) print('registered name : ', registered_name) registered_name.save() registered_live_class.registered_students.add(registered_name) registered_live_class.save() else: print("already registered") return Response(status=status.HTTP_201_CREATED) elif request.method == 'DELETE': print("in delete method") registered_class = models.RegisteredClass.objects.get(class_details=models.LiveClass_details.objects.get(id=id), user=request.user) print("registere_class : ", registered_class) registered_class.delete() registered_class.save() registered_live_class = models.LiveClass_details.objects.get(id=id) if(registered_live_class.no_of_students_registered != 0): registered_live_class.no_of_students_registered -= 1 registered_live_class.no_of_students_attended -= 1 registered_live_class.save() print('error here') registered_name = models.RegisteredNames.objects.get(name=request.user.username) print('error after registered name') print(registered_name) registered_name.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here in this view i am getting error in Adding as well as deleting registered_names from my liveclass_api model , In delete request it is returning error like RegisteredNames … -
Display data that no model exists in a serializer - Python - Django - Django Rest Framework
I have a "Model-Viewset-Serializer" and I need my Serializer to display additional fields that don't exist in the model. Model: class MyModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) type = models.CharField(max_length=100, null=False, blank=False) name = models.CharField(max_length=100, null=False, blank=False) Viewset: class MyViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = MyModel.objects.all() serializer_class = MySerializer def list(self, request, *args, **kwargs): queryset = MyModel.objects.filter(organization_id=request.user.my_connection_id) page = self.paginate_queryset(queryset) serializer = MySerializer(page, many=True) return self.get_paginated_response(serializer.data) Serializer: class MySerializer(ModelSerializer): class Meta: model = MyModel fields = ('id', 'type', 'name', 'description', 'array') I need to add the following object to the preview Value: [ {'status': 'ok', 'value': '1'}, {'status': 'pending', 'value': '5'}, {'status': 'approval', 'value': '3'}, {'status': 'rejected', 'value': '4'} ] description: 'text description' -
Python No such Device or Address in Heroku
How to avoid the error when I'm using "os.getlogin" in python django. If I use os.getlogin in my local machine works fine and the file that I downloaded save directly in Desktop but in Heroku app I got the error [Errno 6] No such device or address. Any work around to save the file directly to user Desktop? I'm using Heroku for my app. Thank You! import os def report_detail(request): username = os.getlogin() ....................... some codes ...................... wb.save(f"/Users/{username}/Desktop/Report.xlsx") -
Django question: regarding Foreign Keys on two separate tables
Clear here to view diagram Hello, based on a diagram on left: class Course(models.Model): ... ... ... class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) ... ... class Question(models.Model): question_text = models.CharField(max_length=500) grade = models.IntegerField(default=20) # Foreign KEY TO LESSON lesson_id = models.ForeingKey(Course, on_delete_models.CASCADE) ---> HOW???? How should I assign the 'lesson_id' in Question model to Lesson model when the common for both is Course model? Really need help on this I'm new to Programming. Thanks so much in advance -
Can you help me to fix this bug?
I am testing djangorestframework and there is an error. Can anybody help me? python version: 3.9.1 django version: 2.2.13 -
docker + nginx http requests not working in browsers
I have a AWS EC2 instance running Linux with docker containers running gunicorn/django and an nginx reverse proxy. I don't want it to redirect to https at the moment. When I try to reach the url by typing out http://url.com in the browser it seems to automatically change to https://url.com and gives me ERR_CONNECTION_REFUSED. The request doesn't show up at all in the nginx access_log. But when I try to reach it with curl I get a normal response and it does show up in the nginx access_log. I have ascertained that the django security middleware is not the cause as the HSTS options are disabled. I've tried clearing the browser cache and deleting the domain from the chrome security policies. nginx config: upstream django_server { server app:8001 fail_timeout=0; } server { listen 80; server_name url.com www.url.com; client_max_body_size 4G; charset utf-8; keepalive_timeout 5; location /static/ { root /usr/share/nginx/sdev/; expires 30d; } location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; if (!-f $request_filename) { proxy_pass http://django_server; break; } } } What am I overlooking? -
How do I filter model objects by most recently created in Django?
I am working on a website in Django and I have a model 'Question'. The Question model has a field 'date_created' which is a DateTimeField. from django.db import models from django.utils import timezone class Question(models.Model: ... date_created = models.DateTimeField(default=timezone.now) In my view, I want to be able to get all the questions that have been asked in the last 10 days. Something like this: Question.objects.filter(???) >> <All the questions that have been asked in the last 10 days> What do I replace '???' with? Thanks in advance. -
The proper way to store JWT tokens in redis for authentication purpose
What is the proper way to store JWT tokens in Redis? The token is signed and self-contained and relatively long string, but what we need is only for authentication. So, is it better to store as JWT using a hash or signature? Any ideas? thanks! Token UserID 1. JWT TOKEN User ID 2. JWT Signature User ID 3. MD5(JWT) User ID -
How to modify nav-pills to limit the number of pages to display
I am trying to implement a pagination system to one page using nav-pills. Since these nav-pills are created dynamically, there will be times when there are only 1, and others when there are 100 (or more). I am using bootstrap 4 & Django The visual impact is tremendous when there are a large number of nav-pills. Attached photo to give you an idea: The code: <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% for evidence_form in evidence_formset %} {% with index=forloop.counter|stringformat:'s' %} {% with id='evidence-form-'|add:index|add:'-tab' href='#evidence-form-'|add:index aria_controls='evidence-form-'|add:index %} <li class="nav-item"> {% if not current_tab and forloop.first or current_tab == index %} <a class="nav-link active" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ forloop.counter }}</a> {% else %} <a class="nav-link" id="{{ id }}" data-toggle="pill" href="{{ href }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ forloop.counter }}</a> {% endif %} </li> {% endwith %} {% endwith %} {% endfor %} </ul> </div> I would like to get a result similar to the following: Previous 1 2 3 4 5 Next That is, if the user clicks next, the following 5 pills will load: Previous 6 7 8 9 10 Next And if the user clicks on Previous we will go back to … -
Load Django Objects Quicker
so I'm working on a Django news aggregator project. A main aspect of the project involves me fetching reddit and twitter posts through their respective APIs, saving the post data to a post model, then loading those model objects onto the page. This is what I would prefer to do over fetching the data and displaying it directly through the response objects. Right now, I have two separate timelines of reddit posts, and twitters posts, adjacent to each other on the page. Last time I loaded the page, it took a really long time. This is what the page looks like btw: I was hoping someone could explain to me how I can get my page to load faster, and also how to integrate timeline/newsfeed functionality well. Lets say I have over 1500 post objects in my database, I don't want to load all 1500 on the page at one time. I'd like to load like the first 100, then if someone scrolls down the page enough, the next 100 become loaded, etc. Is there an easy/efficient way to go about this? Thanks -
How to manipulate data and display it through Django?
Background I have created an small app that can add projects, and show it in the index page, all those projects can be access individualy to its own "profile proJect page" clicking on the project name. Inside the project's profile page, it can be seeing data as ProjectName, ResponsableName, Description and all related data per page. Problem Now that have the app, I would like manipulate the data from the django models and display the analysis into another HTML page, is there any library you could recommend or it is posible to do it only with Django ? Where should I start ? I'm available to response any upcomming questions.