Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins
I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."This means that Django recognizes the question but rejects it for some unknown reason. ReactJs is using a proxy to work with server data. I've read already solved articles on forum such as article 1, article 2, article 3, article 4, their solutions didn't help me. My request from ReactJs: const item = {tittle : data.target.tittle.value, description : data.target.description.value}; axios({ headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method : "post", url : "api/articles/", data : item }).catch((e) => {console.log(e)}) Setting.py: CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000' ] ALLOWED_HOSTS = [ 'localhost', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', ] CORS_ORIGIN_ALLOW_ALL = True class for processing requests in views.py: class ArticleList(generics.ListCreateAPIView): def post(self, request, format=None): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, format=None): snippets = Articles.objects.all() serializer = ArticleSerializer(snippets, many=True) return Response(serializer.data) -
In Django create a model method which determines an id for all objects that share the same foreign key
Kind of new to Django and while trying to create my first own project, i stumbled upon a problem. I have two different model classes: Star and Planet. Each planet has a foreignkey which belongs to a Star. Now I would like to have a field for Planet, which is basically the id/pk for its star system that is given on creation/discovery. All known planets of the star system already have their star system id and thus the newly created/discovered planet would require an id that is incremented on the last id that was given. Id Star Id in Star System Name 1 Sun 1 Neptune 2 Alpha Centauri 1 Hoth 3 Alpha Centauri 2 Coruscant 4 Sun 2 Earth 5 Sun 3 Jupiter 6 Alpha Centauri 3 Yavin4 7 Sun 4 Venus My models are looking like this models.py: class Star(models.Model): name = models.CharField(max_length=200) class Planet(models.Model): name = models.CharField(max_length=200) star = models.ForeignKey(Star, on_delete=models.CASCADE) def starSystemPlanetId(self): What could work in here? This new Id should be available to be called in a template like this: {% for planets in object_list %} <li> <p>Planet {{planets.name}} is the Nr. {{planets.customer_id}} planet of the star system</p> </li> {% endfor %} I have learned … -
How to calculate aggregate sum with django ORM?
I'm trying to group_by() data based on dates and with every day I want to calculate Count on that day also the total count so far. Sample output I'm getting: [ { "dates": "2022-11-07", "count": 1 }, { "dates": "2022-11-08", "count": 3 }, { "dates": "2022-11-09", "count": 33 } ] Sample output I'm trying to achieve: [ { "dates": "2022-11-07", "count": 1, "aggregate_count": 1 }, { "dates": "2022-11-08", "count": 3, "aggregate_count": 4 }, { "dates": "2022-11-09", "count": 33, "aggregate_count": 37 } ] -
django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] problem
In 'models.py' i have this fields. first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) date_of_brith = models.DateField(default='YYYY-MM-DD', null=True) email = models.EmailField(max_length=50, null=True) When i try to migrate. I get this error. I tryed to delete also the field and I still have the same error django.core.exceptions.ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
Django can't close persistent Mysql connection
Problem: Our Django application includes zipping large folders, which takes too long (up to 48 hours) so the Django connection with the database gets timed out and throws: "MySQL server has gone away error". Description: We have a Django version==3.2.1 application whose CONN_MAX_AGE value is set to 1500(seconds). The default wait_timeout in Mysql(MariaDB) is 8 hours. ExportStatus table has the following attributes: package_size zip_time Our application works this way: Zip the folders set the attribute 'package_size' of ExportStatus table after zipping and save in the database. set the attribute 'zip_time' of ExportStatus table after zipping and save in the database. Notice the setting of the columns' values in database. These require django connection with database, which gets timedout after long zipping process. Thus throws the MySQL server gone away error. What we have tried so far: from django.db import close_old_connections` close_old_connections() This solution doesn't work. Just after zipping, if the time taken is more than 25 minutes, we close all the connections and ensure new connection as: from django.db import connections for connection in connections.all(): try: # hack to check if the connection still persists with the database. with connection.cursor() as c: c.execute("DESCRIBE auth_group;") c.fetchall() except: connection.close() connection.ensure_connection() Upon printing … -
Django: Send mail to admin on every error raised
I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me. Currently I do something like this where on every raise I send a email. But I want a system where on every error there would be a email sent. # send an email alert email_content = "Email content" subject = "Subject" if settings.ENVIRONMENT == 'PROD': BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) else: BaseScraper.email_alert_for_error( subject, email_content, ["admin@mail.com"], ) -
duplicate record when combine `distinct` and `order_by`
I'm using filter_backend for ordering my fields, but I have a problem, when I order by product__company__name, the API responds 1 result as me as expected, but with 2 records duplicated. I read the Note in this docs https://docs.djangoproject.com/en/3.2/ref/models/querysets/#distinct that If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don’t appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned. So how can I resolve this problems ? Thank so much. filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ["product__company__name"] ordering_fields = [ "created", "product__company__name", ] def get_queryset(self): if self.kwargs.get("shelf_type") == "want_to_read": result = ( MyModel.objects.filter( <logic_code> ) return result.distinct() -
insertion command via an API (Django project)
I am developing an e-commerce site using API calls. I would like to insert orders, the idea is after having selected several products on the cart (assume 4 products), I would like to insert them using the API only once, not with a loop. That is to say, I call the API only once and this inserts the 04 products into the database. And not put the API call in the shopping cart session loop, which will call the url 4 times. API Noted that if I remove its rows from the loop, it only inserts the last product url='http://myAPI/Product/postProduct' x=requests.post(url,json=data) Views.py @login_required def postCommande(request): for key,value in request.session.get("cart", {}).items(): data={ 'my_commande':[ { 'date':str(datetime.now()), 'name': request.user.client.name, 'content':[ { 'article':value.get('product_id'), 'designation':value.get('name'), 'quantite':value.get('quantity') } ] } ] } url='http://myAPI/Product/postProduct' x=requests.post(url,json=data) -
How to reverse query a table with foreign keys such that I can get the values of those foreign keys as well?
My models: https://pastebin.com/qCMypxwz How can I query the Variants table from Products table? I want to get the values of image and colors (which is a table itself) from the Variants table. This is what I am doing so far but this is giving me similar queries according to debug tool: productList = Products.objects.prefetch_related('category', 'variants_set__color_id', 'variants_set__image') for productName in productList: products = dict() prod_id = productName.variants_set.all()[0].id products['id'] = prod_id products['category'] = productName.category.category_name products['prod_name'] = productName.prod_name products['brand'] = productName.brand prod_colors = productName.variants_set.all().values_list('color_id__name', flat=True).distinct() prod_images = list(productName.variants_set.all()[0].image.all()) image_list = list() for image in prod_images: image_list.append(image.image_url) products['image'] = image_list products['colors'] = list(prod_colors) price = productName.variants_set.all()[0].price products['price'] = price createdAt = productName.variants_set.all()[0].createdAt products['createdAt'] = createdAt productListDict.append(products) -
How to upload file using many to many field in django rest framework
I have two models. One is article and other is documents model. Document model contains the filefield for uploading document along with some other metadata of uploaded document. Article has a m2m field that relates to Document Model. Article model has a field user according to which article is being which article is being posted. I want to upload file using m2m field, but it gives two errors: "files": [ "Incorrect type. Expected pk value, received InMemoryUploadedFile."] I also tried using slug field, the document does not exists. but i am uploading new file then why saying document does not exist. Please guide me how i can achieve this? Article Model class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateTimeField(auto_now_add=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=mode Document Model class DocumentModel(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID") document=models.FileField(max_length=350, validators=[FileExtensionValidator(extensions)], upload_to=uploaded_files) filename=models.CharField(max_length=100, blank=True) filesize=models.IntegerField(default=0, blank=True) mimetype=models.CharField(max_length=100, blank=True) created_at=models.DateField(auto_now_add=True) Article Serializer class ArticleSerializer(serializers.ModelSerializer): #serializer for getting username of User created_by=serializers.CharField(source='created_by.username', read_only=True) isFavourite=serializers.PrimaryKeyRelatedField(many=True, read_only=True) tags=serializers.SlugRelatedField(many=True, queryset=Tags.objects.all(), slug_field="tag") readtime=serializers.IntegerField(read_only=True) class Meta: model= Article fields = ["id" , "headline", "abstract", "content", "readtime", "get_published_timestamp", "isDraft", "isFavourite", "tags", 'files', 'created_by' ] Document Serializer class DocumentSerializer(serializers.ModelSerializer): filesize=serializers.ReadOnlyField(source='sizeoffile') class Meta: model=DocumentModel fields = ['id', … -
How to add a column data from one table to another table column field in postgresql using python
I am new to django and postgresql. I have two tables in postgresql. in one table i have two fields ID and Value. i want to add the datas in the ID column to another table column field named value_id. In postgres the tables are from the same schema. I want to do this via python. Is there any way. please help. cur = con.cursor() db_insert = """INSERT INTO "Database"."TABLE_ONE" ("LT_ID_ONE", "LT_ID_TWO") VALUES( (SELECT "LT_ID_ONE" FROM "Database"."TABLE_TWO" WHERE "LT_NUM_ONE" =%s), (SELECT "LT_ID_TWO" FROM "Database"."TABLE_THREE" WHERE "LT_NUM_TWO" =%s) );""" insert_values = (df1.iloc[0, 0], df1.iloc[0, 1]) cur.execute(db_insert, insert_values) I am doing this in django so the above method will not work. can anyone please suggest any way please -
How to implement onfocus() with span tag onclick() event
I have one input type field which is google inspired input type with label animation which have onfocus event and In that one of the Input field has the Password field in which I have to apply eye-toggle functionality with onclick event. I am sharing screenshot of the input type. Input Field When I am trying to implement toggle functionality for password. onclick event is not able to trigger because of onfocus event. Here is the code for toggle. <div class="col-3 inputfield"> <input type="password" id="Password" name="Password" class="inputfield-control" placeholder=" "> <label class="form-label">New Password</label> <div class="input-group-append custom"> <span toggle="#password-field" class="icon ion-md-eye-off field-icon toggle-password show-password-icn" ></span> <br> </div> </div> $(document).on('click', '.toggle-password', function() { $(this).toggleClass("icon ion-md-eye"); var input = $("#Password"); input.attr('type') === 'password' ? input.attr('type','text') : input.attr('type','password') }); Because of the Animation in input field toggle click event is not even triggers. I have try to perform other click event rather then click event, still any of the click event is not working with Animation. -
Python 2.7.16 randomize a list of in with probability
I am using python version 2.7.16 and i want to get the alternative of the random.choices() method of python 3. sample code for latest python version - import random rewards = ['80 credit', '40 credit', '10 credit'] weights = (1000, 2000, 7000) pick = 3 selected_rewards = random.choices(rewards, weights=weights, k=pick) print(selected_rewards) i want this alternative for python version 2.7.16 i have tried everything but unable to find solution for this could anyone help me to get details related this ? -
How to improve the query to exclude referenced objects inside query (mptt model)?
I have the following code where each Song can have Parts and each part can have multiple Genres assigned. from model_utils.models import TimeFramedModel from django.db import models from mptt.models import MPTTModel, TreeForeignKey from mptt.fields import TreeManyToManyField from django.db.models import Prefetch class Song(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] class Part(TimeFramedModel): # start and end fields via inheritance song = models.ForeignKey(Song, related_name="parts", on_delete=models.CASCADE) genres = TreeManyToManyField(Genre) desc = models.TextField() def __str__(self): return self.start I'm trying to write a query: Input: A set of Genre.ids named in_genres Output: A query set containing the Songs that have a Part of the input Genre.ids and all other Parts excluded. My current query is: for genre_id in in_genres: genre = Genre.objects.get(pk=genre_id) qs = Song.objects.filter(parts__genres__in=genre.get_descendants(include_self=True)).prefetch_related( Prefetch( 'parts', Part.objects.filter(genres__in=genre.get_descendants(include_self=True) ) ) I there a way to improve this query? Is this the best way to achieve this? Any help is highly appreciated! -
How to use image as checkbox html
So basically what I need to do is a login page, with an eye on the password field, so the user can click on the eye icon, and see the password. What I have so far is a simple checkbox: <input type="checkbox" id="box" onclick="reveal()"> and the function to show and hide the password: function reveal() { if (document.getElementById('box').checked) { document.getElementById("id_password").type = 'text'; } else document.getElementById("id_password").type = 'password'; } It works with this solution, but I need to have an Eye-Icon, instead of a simple checkbox. How can I make an Image as the checkbox? -
Django: saving unique value without duplicate it
I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that. Model: class Service(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=127, unique=True, null=False, blank=False) # that field is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( "accounts.User", on_delete=SET_NULL, blank=False, null=True, related_name="service_created_by", ) def __str__(self): return f"{self.name}" -
How do I write HTML code in Django's syndication feed framework?
I'm using Django's syndication feed framework to generate RSS for my website, referring to this document I have done the work according to the example it provides, the code is similar to the following, I have not made too many changes. from django.contrib.syndication.views import Feed from django.urls import reverse from policebeat.models import NewsItem class LatestEntriesFeed(Feed): title = "Police beat site news" link = "/sitenews/" description = "Updates on changes and additions to police beat central." def items(self): return NewsItem.objects.order_by('-pub_date')[:5] def item_title(self, item): return item.title def item_description(self, item): return item.description # item_link is only needed if NewsItem has no get_absolute_url method. def item_link(self, item): return reverse('news-item', args=[item.pk]) Then I want to add <a href="test.com">Click to my site</a> in item_description, I made some minor changes. def item_description(self, item): description = item.article_description description = description + "<a href='test.com'>Click to my site</a>" return description But the final generated code is escaped. <description>&lt;a href='test.com'&gt;Click to my site&lt;/a&gt;</description> I don't want to be escaped, what should I do? As far as I know, <![CDATA[MyInfo]]> tags need to be added to the HTML code in the xml, similar to the following. <![CDATA[<a href='http://test.com'>Click to my site</a>]]>" But I don't know how to do this in Django framework. -
Notification Django cannot be display
I am making a notification in Django but it seems to be not working. How can I make a notification whenever a user add a incident report (model: Incident General), it will notify the roles: admin and super admin that a new report for this user is added and when the admin or super admin change the status it will notify the user of the change in status. Can someone help me with this? Thank you Views def ShowNotifications(request): profile = get_object_or_404(UserProfile, user=request.user) notifications = Notification.objects.filter(user=request.user).order_by('-date') context = { 'profile': profile, 'notifications': notifications, } return render(request, 'notifications.html', context) Models class Notification(models.Model): TYPES = ((1, 'Reports'), (2, 'User Accounts'), (3, 'Inbox'), (4, 'Attributes Builder')) incident_report = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, related_name="noti_report", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=TYPES) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) IF_DUPLICATE = ( ('Duplicate', 'Duplicate'), ('Possible Duplicate', 'Possible Duplicate'), ('Not Duplicate', 'Not Duplicate') ) WEATHER = ( ('Clear Night', 'Clear Night'), ('Cloudy', 'Cloudy'), ('Day', 'Day'), ('Fog', 'Fog'), ('Hail', 'Hail'), ('Partially cloudy day', 'Partially cloudy day'), ('Partially … -
Got AttributeError when attempting to get a value for field `user` on serializer `cart_serializer`
Got AttributeError when attempting to get a value for field user on serializer cart_serializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'user. Views.py class view_cart(APIView): permission_classes = [IsAuthenticated] def get(self, request, total=0, quantity = 0, cart_items=None): grand_total = 0 delivery=0 cart = Cart.objects.get(user=request.user) cart_items = CartItems.objects.filter(cart=cart) print(cart_items) for item in cart_items: total += item.product.price * item.quantity quantity += item.quantity delivery = 150 grand_total = total + delivery serializer = cart_serializer( cart_items, context={"total": total, "grand_total": grand_total, "delivery": delivery}, ) return Response(serializer.data) Seralizer.py class cart_serializer(ModelSerializer): total = SerializerMethodField() delivery = SerializerMethodField() grand_total = SerializerMethodField() class Meta: model = Cart fields = ["id", "user", "total", "delivery", "grand_total"] def get_total(self, *args, **kwargs): return self.context["total"] def get_delivery(self, *args, **kwargs): return self.context["delivery"] def get_grand_total(self, *args, **kwargs): return self.context["grand_total"] Models.py class Cart(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Cart' def __str__(self): return self.user.email class CartItems(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: verbose_name_plural = 'Cart Items' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product.product_name Don't know why this error shows -
Trying to retrieve colors all variants of a product are available in, alot of queries are made. Optimization possible?
Here's my models: https://pastebin.com/qCMypxwz the query executed creates many duplicated queries according to the debug tool. Is there a way to optimize this? Fairly new to django so I am not sure if I am doing the querying right. What I want to do is get the details of the first variant of a product but the colors key of the dictionary must have all the colors the variants are available in. My view: productList = Products.objects.prefetch_related('category', 'variants_set__color_id', 'variants_set__image') for productName in productList: products = dict() prod_id = productName.variants_set.all()[0].id products['id'] = prod_id products['category'] = productName.category.category_name products['prod_name'] = productName.prod_name products['brand'] = productName.brand prod_colors = productName.variants_set.all().values_list('color_id__name', flat=True) #THIS QUERY LOOKS LIKE THE PROBLEM prod_images = list(productName.variants_set.all()[0].image.all()) image_list = list() for image in prod_images: image_list.append(image.image_url) products['image'] = image_list products['colors'] = list(prod_colors) price = productName.variants_set.all()[0].price products['price'] = price createdAt = productName.variants_set.all()[0].createdAt products['createdAt'] = createdAt productListDict.append(products) -
How to add the form to many to many field in Django?
caffeinated_form = CaffeinatedForm() if request.method == 'POST': caffeinated_form = CaffeinatedForm(request.POST) if caffeinated_form.is_valid(): instance = caffeinated_form.save(commit=False) instance.user = request.user instance.item = item instance.hot_or_cold = caffeinated_form.cleaned_data['hot_or_cold'] instance.hot_cold = caffeinated_form.cleaned_data['hot_or_cold'] order = Order.objects.create(user=request.user, ordered=False) order.items.add(instance) instance.save() I want to add my caffeinated_form to ManyToMany field called items. -
Automatically add HStore extension Django
I'm developing on a django app that has a directory like so: App: manage.py --App1: -models.py -etc. --App2: -models.py -etc. --App3: -models.py -etc. Many of them use HStore field(s) in the model definition file and when I go to migrate them each time I have to do this sequence: run python manage.py makemigrations {app 1,2,3 and so on here} Add HStoreExtension() to operations=[] in the first migration file like: 0001_initial.py It becomes tedious to do that when there's a ton of migrations for one app. I realize there may be better ways to structure the application but that's how it was built. Is there any way to avoid having to "makemigrations" then add the hstore extension to the operations each time? I don't want to create a lot of manual work for others to spin up the app. I know there are similar questions where the solution is to run a query to the database to add the extension. In this multiple subdirectory apps situation would I just include that in the top level application init file? -
Is there any Solution for this Login syntax>?
Ive this Django Login and Registration form but the registration form is fetching in database auth_user but not in helloworld_register This is my Registration code def Register(request): if request.method =='POST': username=request.POST['username'] email=request.POST['email'] first_name=request.POST['first_name'] last_name=request.POST['last_name'] password1=request.POST['password1'] password2=request.POST['password2'] if User.objects.filter(email=email).exists(): messages.info(request, 'uh oh..:( This Email is Already Taken ') print('emailtaken') return redirect('/Register') elif User.objects.filter(first_name=first_name).exists(): messages.info(request, 'uh oh..:( This Name is Already Taken ') print('Name taken') return redirect('/Register') user=User.objects.create_user(username=username, email=email,first_name=first_name,last_name=last_name,password=password1) user.save(); messages.info(request, 'Registration complete Login to continue ..:)') print('user created') return redirect('/LOGIN') return render(request, 'Register.html') And this is my Login Code def LOGIN(request): if request.method=='POST': email=request.POST['email'] password1=request.POST['password1'] user=auth.authenticate(email=email,password1=password1) #user.save(); if user is not None: auth.LOGIN(request,user) return redirect('LOGIN') else: messages.info(request, 'mmm :( Invalid Credentials ') return redirect('LOGIN') Even though if i try Logging in with registered credentilals im unable to login -
How can I paginate list of dictionaries in django
I am working on Django pagination and trying to paginate my data which is in the form of dictionaries inside a list, I tried function based approach as per documentation class MyUserData(TemplateView): template_name = "myuserdata.html" form = "userform" def listing(request): contact_list = Contact.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'list.html', {'page_obj': page_obj}) I am writing above function inside my class which is inheriting (TemplateView) now the problem is that it is reducing the number of results to 25 but when i click on next it doesn't show next page <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> Flow is like this the user will come and enter the start date and end date and click on submit and get's his history of data and the issue is user gets all his history if he selects longer date range which I want to paginate this is how data is coming … -
Django AWS S3 some media images not showing up
The user uploaded images show up (ex: profile pics) but not my 'static' images (logos). They are both in the same bucket. (Folder -> profile-pics, Folder -> static-images). Heroku production urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py DEBUG = False MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-west-1' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = "virtual" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' some template. below isn't loading.. <img src="/media/signin_buttons/btn_google_signin_dark_normal_web.png"> but for example, user uploaded images load up from S3 {{ user.profile_pic.url }} pip list asgiref==3.5.2 boto3==1.25.2 botocore==1.28.2 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.7 cryptography==36.0.0 defusedxml==0.7.1 dj-database-url==1.0.0 Django==3.2.15 django-allauth==0.46.0 django-cleanup==5.2.0 django-crispy-forms==1.12.0 django-heroku==0.3.1 django-storages==1.13.1 gunicorn==20.1.0 idna==3.3 jmespath==1.0.1 oauthlib==3.1.1 Pillow==8.3.2 psycopg2==2.9.5 pycparser==2.21 PyJWT==2.3.0 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 s3transfer==0.6.0 six==1.16.0 sqlparse==0.4.3 urllib3==1.26.12 whitenoise==6.2.0