Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Split pdf files from request and send the splitted pdf's as response without saving it locally Django/Python
As mentioned in the title I have an API endpoint which receives a PDF file object from request. I need to split these PDF into multiple pdf's and send these split pdf's as response without saving any of these files locally using PYTHON inside a zip folder. Thanks in Advance!! I'm able to split and create zip if I save the files locally using pypdf2 but I just wanna know is there a way to split and put in a zip without saving locally. -
If user is not authenticated and adding something to cart, the item goes to the wishlist. But if user is logged in everything ok. DJANGO JS
I want my system to remember not only the products of logged in people, but also those who are not logged in. I made about the same cookie system for cart and wishlist that works until you loogged out. I'll put everything because idk where exactly to look main.html script part <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getToken('csrftoken') function getCookie(name) { var cookieArr = document.cookie.split(";"); for(var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); if(name == cookiePair[0].trim()) { return decodeURIComponent(cookiePair[1]); } } return null; } var cart = JSON.parse(getCookie('cart')) if (cart == undefined){ cart = {} console.log('Cart Created!', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" } console.log('Cart:', cart) var wishlist = JSON.parse(getCookie('wishlist')) if (wishlist == undefined){ wishlist = {} console.log('wishlist Created!', wishlist) document.cookie ='wishlist=' + JSON.stringify(wishlist) + ";domain=;path=/" } console.log('Wishlist:', wishlist) cart.html (wishlist almost the same) {% extends 'store/main.html' … -
stripe.txt not visible in my django project
I am following the tutorial via the link below. https://www.youtube.com/watch?v=ncsCnC3Ynlw&t=13787s I follow what the mentor did, but I don't have stripe.txt file in my django project, after I install stripe. pip install stripe the stripe.txt should be something like this. No auth:4242424242424242 Auth: 4000000000000025000003155 Error: 400000000000000000999555 Can anyone advise me how to solve this? Thank you so much -
How to load data from database to frontend step by step like big company websites do in Django fullstack?
We all know that Django web framework is powerful for loading tons of data and scalable to deliver it to user interface. So I got really common question, how do I fetch data step by step like Instagram or Youtube does? Instagram fetches videos, reels every 16 loops, First fetches 16 videos, then after watching last 16 th video then loads (prepares) another 16 videos, so how do I do my data to be fetched in exactly that way? Do I need js to do like that? Is it possible to do it in Python itself? I am not really sure amount of instagram fetches but, Can you please example some ways to do that? -
Compare performance with and without cache using django redis
I am using redis to implement caching for django project, I have created two function to compare the performance but function with caching seems slow any reason to that. Here is the loadtest output for the function without caching [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Max requests: 50 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Concurrency level: 1 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Agent: none [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Completed requests: 50 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Total errors: 0 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Total time: 0.40408834 s [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Requests per second: 124 [Thu Mar 23 2023 17:48:01 GMT+0530 (India Standard Time)] INFO Mean latency: 8 ms and is the loadtest output for the function with caching [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] INFO Max requests: 50 [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] INFO Concurrency level: 1 [Thu Mar 23 2023 17:47:56 GMT+0530 (India Standard Time)] … -
What is the purpose of def get_instances_from_related() method in django_elasticsearch_dsl
I am working on creating elastic search indexing for the python Django project for a model with related tables. When I am working on it I came across the website https://pypi.org/project/django-elasticsearch-dsl/6.4.2/. I have followed the steps and implemented an elastic search for my model and it's working fine. But I can't find the purpose of the method def get_instances_from_related(self, related_instance). Why we are using this method, where and when we are it is called. Could anyone please explain this? Thank you. -
How to write a sql query and django queryset
Here i am having two tables Book,Publications Book tables is having the following fields id, book_name, pub_id And Publications table is having the following tables id, pub_name Using the pub_name how can i get the book_name in SQL query and Django query -
django-imagekit set dynamic width
I am using django-imagekit on my project, I cannot set dynamic size for processors. Is it possible to set it dynamic and make height auto ? models.py class Ad(TimeStampedModel): AD_MAIN = "main" AD_RIGHT = "right" AD_TYPE = ( (AD_MAIN, "Main"), (AD_RIGHT, "Right"), ) name = models.CharField(max_length=255, verbose_name="Номи") image= ProcessedImageField( upload_to="ads", format="webp", processors=[ResizeToFill(width=get_image_size, height=None)], options={'quality': 90}, ) ad_type = models.CharField( max_length=7, choices=AD_TYPE, default=AD_MAIN, ) is_active = models.BooleanField(default=False,) @property def get_image_size(self): if self.ad_type == self.AD_MAIN: return 1300 elif self.ad_type == self.AD_RIGHT: return 420 ] -
messages in the admin when subclassing BaseInlineFormset
I want to display a warning depending on entries made in the ItemInlineFormSet: from django.contrib import admin, messages from django.forms.models import BaseInlineFormSet from django import forms class SomeAdminForm(forms.ModelForm): class Meta: model = ModelA class ItemInlineFormSet(BaseInlineFormSet): def clean(self): msg = "test" class TheTabularInline(admin.TabularInline): model = ModelB formset = ItemInlineFormSet class ModelAAdmin(admin.ModelAdmin): inlines = [TheTabularInline,] form = SomeAdminForm I thought I could simply overrwrite save_model() or save_formset() in TheTabularInline to display the message: class TheTabularInline(admin.TabularInline): model = ModelB formset = ItemInlineFormSet def save_model(self, request, obj, form, change): messages.info(request, form.msg) But the variable is not accessible from there. Neither is request from within the clean() method of ItemInlineFormset. Do I have to overwrite the __init__()? -
Django not displaying action messages when used with apigateway http api
I have deployed a Django app on aws lambda and configured API gateway HTTP API. The action messages are not displayed when I perform actions like creating or deleting objects on Django admin. The action messages are properly displayed when I integrate Rest API instead of HTTP API. I already found keeping the Session storage in Django settings solves the problem, but I think it's a workaround instead of the solution. MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' -
scheduling post request after 2 minutes in djangorestframework?
Hello developers I am stuck to post request automatically by using APScheduler in djangoRestFramework each 2 minutes please help to do it main problems is pass request in scheduling job. class LogisticsTruckListView(APIView): def post(self, request): truck_id = request.data.get('truckListId') queryset = LogisticsTruckList.objects.filter(truckListId=truck_id) serializer = LogisticsTruckListSerializer(queryset, many=True) data = serializer.data # get vehicle no vehicle_no = data[0]['vehicle_no'] if vehicle_no: url = "https://track.cxipl.com/api/v2/phone-tracking/doc-latest-location?vehicleNumber="+vehicle_no headers = { "Content-type": "application/json", "authkey": "UB1CNQLKU32LPCFQJ2NGL7YY1E51HYF6" } response = requests.get(url, headers=headers, verify=False) if response.status_code == 200: data = response.json() return Response(data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_400_BAD_REQUEST) here is my scheduling job code .. def start(): scheduler = BackgroundScheduler() viewSets = LogisticsTruckListViewSet() scheduler.add_job(viewSets.getTrackingDetails(), 'interval', minutes=1, id='tracking_details__001', replace_existing=True) scheduler.start() Help me out soon as possible I want to schedule a task in django rest framework -
Django problem with" python manage.py makemigrations"
Hi i'm doing the Mosh Tutorial about Django and when i run the command python manage.py makemigrations i have this in terminal File "C:\Users\Giovanni\PycharmProjects\PyShop\venv\Lib\site-packages\django\db\models \fields\__init__.py", line 1121, in __init__ super().__init__(*args, **kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' (venv) PS C:\Users\Giovanni\PycharmProjects\PyShop> This is my models.py from django.db import models class Product(models.Model): name = models.CharField(max_lenght=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_lenght=2083) -
Django: You're accessing the development server over HTTPS, but it only supports HTTP. code 400, message Bad request version
I am trying to access my Django website using python manage.py runserver , which returns me http://127.0.0.1:8000/. However, when I try to access this link using Google chrome, I get this error on chrome This site can’t provide a secure connection 127.0.0.1 sent an invalid On Anaconda prompt, I get this error: Code 400, message Bad request version ('ª') You're accessing the development server over HTTPS, but it only supports HTTP. I notice that Google Chrome always changes my website to http://127.0.0.1:8000/ I am uncertain if this is the issue because. I have been working on the Django project and have been accessing the website on chrome using the same method and there was no issues with it at all. Could it be because of the settings.py configurations that caused the error? import os from pathlib import Path import django_heroku # to host heroku import dj_database_url # to host heroku from decouple import config # to host heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d44=xloa_ngo&moz%cujtvuqpr7ub)hfbqss6$xnubj031q3!9' # SECURITY WARNING: … -
Group list active item appears 2 times in a list
Im writing program that shows static schedule for school organisations and now there is a page of schedule with relevant days-lessons, but the title of the day appears 2 times. Here is a screenshot of my issue: Issue Here is the html code of the page schedule.html {% extends 'app/layout.html' %} {% block body %} <ul class="list-group"> {% for i in subjects %} <li class="list-group-item active" aria-current="true">{{i.day}}</li> <li class="list-group-item " aria-current="true">{{i.title}}</li> {% endfor %} </ul> {% endblock body %} views.py def showSchedule(request, ID): relevant_group = Students.objects.get(id = ID) subjects = relevant_group.students.all().order_by("day") context = {"group": relevant_group, "subjects":subjects} return render(request, "app/schedule.html", context) How to make this blue(active item) Friday appear just 1 time? -
django conditional filtering
I have this model of Vehicle: class Vehicle(models.Model): ... driver = models.OneToOneField(Driver, related_name="vehicle", on_delete=models.CASCADE, blank=True, null=True) In my form i want to initialize the queryset of driver so only the driver that have no relations with vehicle appear in list (because its one-to-one relations). So in my forms.__init__: self.fields['driver'].queryset = vendor.drivers.select_related('user').filter(vehicle__isnull=True) but I realize in my edit form (using ModelForm), the driver not initialized in form because i guess, the queryset override it. The initial driver is not vehicle__isnull So what i want is, vehicle__isnull except for this initial driver if there is a driver already. How can I achieve that? Any help would be appreciated. -
Why doesn't models.py get created on running python3 manage.py polls from within a script?
I wrote many scripts to help me manage my django projects. One of them, cr_app.py creates a new app: #!/usr/bin/env python3 from subprocess import run def main(): create_app() def create_app(): name = input("The name of the app?\n") run(f"""python3 manage.py startapp {name}""", shell=True) if __name__ == "__main__": main() When I am inside of my virtual envirnment's project directory and, following the tutorial, I run manually python3 manage.py startapp polls then I find models.py already created inside of polls/. But this does not happen when I run cr_app.py and create a new app polls even though I run this script while being in the projects activated virtual environment (although cr_app.py is not, it is located in a different, remote directory). Why so? -
Running django project failing after upgrade to django 3.2.18
I upgraded my django project from django 3.0.6 to django 3.2.18. After that I cannot run my project with following command: python -m my_project.manage run server 127.0.0.1:8000 it produces below error message: python.exe: No module named my_project.__main__; 'my_project' is a package and cannot be directly executed However when I run: python manage.py runserver 127.0.0.1:8000 It works perfectly fine. Does anyone has similar issue? I suspected it was related to django app configuration but changes in this field does not help. -
Reverse for 'usecase-details' with no arguments not found. 1 pattern(s) tried: ['usecase\\-details/(?P<ucid>[^/]+)\\Z'] Django
I have three models user, usecase, and usecase assign: I have two views redirecting to the same page to show the details of the usecase and to assign new users and unassign users: I'm trying to execute the logic of this method: DELETE FROM usecase_assign WHERE usecase_assign.user_email = 'nmbarak'; How can I get the user_email from the template and pass it in the view to delete it? what I tried is to create two views, the first one for showing the usecase details and assign new users, the second one to un-assign and to redirect to the same page. My usecase_assign model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my views: @user_login_required def view_usecase_details(request, ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc if request.method=='POST' and 'assignuser' in request.POST: user_email = request.POST['user_email'] userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid) if userAssignCheck: messages.error(request, "user already added!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: userAssignObj = UsecaseAssign.objects.create(user_email_id=user_email, usecase_id=ucid) if userAssignObj: messages.success(request, "User was Successfully Assigned with Usecase!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned, … -
How to use metronic select2 style in django-select2
I have a form and i render that in template with django-select2 and also i downloaded one of metronic html templates with css and js files and they have select2 styles in there But select2 its not django-select2 package but i need django-select2 so how can i use their customize on my package? https://preview.keenthemes.com/html/metronic/docs/forms/select2 template.html {% render_field form.contractor_counter|add_class:"form-select" %} thats` how they say i need to use their template of select 2 {# <select class="form-select" data-control="select2" data-placeholder="Select an option">#} {# <option></option>#} {# <option value="1">Option 1</option>#} {# <option value="2">Option 2</option>#} {# </select>#} -
TemplateDoesNotExist at / in pythonanywhere
when i deploy the website to pythonanywhere, it show this Exception. i had checked there was the file but it show (Source does not exist). How can i solve it? i tied 1) add ('learning_logs/templates') to 'DIRS' 2) add (path.join(BASE_DIR, 'templates') to 'DIRS' The problem didnt solve even i tried above solution. Can anyone help? the templates i save in below path: learning_log\learning_logs\templates\learning_logs settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['learning_logs/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] view.py def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs\index.xhtml') -
DRF - How to generate nested json with serializer?
I'm a beginer in DRF and here is a simple illustration of the nested json I want to generate: { "shop_name": "some_text", "shop_intro": "some_text", "swiper_images": [ { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" }, { "id": "id_num", "swiper_image": "some_url", "swiper_image_alt": "some_text" } ] } Here is my models.py: from django.db import models class ShopIndexPage(models.Model): shop_name = models.CharField(max_length=128, default="Shop Name") intro_text = models.CharField(max_length=1000, default="Intro Text") def __str__(self): return "Shop text of " + self.shop_name class SwiperImage(models.Model): swiper_image = models.ImageField(upload_to='images/index/swiper-images', default="None") swiper_image_alt = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.swiper_image_alt Here is my serializer.py: from rest_framework import serializers from .models import ShopIndexPage, SwiperImage class SwiperImageSerializer(serializers.ModelSerializer): class Meta: model = SwiperImage fields = ['swiper_image', 'swiper_image_alt'] class ShopIndexPageSerializer(serializers.ModelSerializer): swiper_items = SwiperImageSerializer(many=True) class Meta: model = ShopIndexPage fields = ['id', 'shop_name', 'intro_text', 'swiper_items'] Here is my views.py: from .models import ShopIndexPage from .serializers import ShopIndexPageSerializer from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_view(['GET', 'POST']) def index_list(request, format=None): if request.method == "GET": index_queryset = ShopIndexPage.objects.all() serializer = ShopIndexPageSerializer(index_queryset, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ShopIndexPageSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) I got the following error: Got AttributeError when attempting … -
Django Multiselect Filed showing List Index Out Of range Error in Window
I was working with Django and it's throwing an error IndexError: list assignment index out of range and the same code is working fine on Linux production, I used pip install django-multiselectfield for multiselect in Django, I am using this DATA= (('0', 'Small'),('1', 'Medium'),('2', 'Large,) and my field name is clients = MultiSelectField(choices=DATA, null = True, blank= True)this, but this is not working and throwing me list index out of range error on window power shell, please let me know how I can solve this issue. -
Cookies are being sent by Django but not received by frontend
I'm attempting to send a cookie to the front end using django middleware. In the middleware I'm seeing that the cookie is getting created and then attached to the response. But once I'm on the frontend (React) I'm not finding the cookies with .get('Set-Cookies') and can't figure out why. Middleware (python) class DeviceCookieMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) new_customer = None if 'device' not in request.COOKIES: new_customer = Customer.objects.create() response['Set-Cookie'] = f'device={new_customer.device}; Max-Age=3600; Secure; HttpOnly; SameSite=None' request.new_customer = new_customer print(response.headers) return response Frontend (Javascript) export async function fetchProductsBySlugs(slugs, setterFunc, startDate, endDate, dateChange) { const [start, end] = parseDates(startDate, endDate) try { const response = await fetch(`${SERVER_ADDRESS}/api/products/products/list/?slugs=${slugs.join(',')}&${datesUrlString(start,end,dateChange)}`); const cookies = response.headers.get('Set-Cookie') console.log(cookies) const products = await response.json(); setterFunc(products); return products; } catch (error) { throw error; } } Things I've Tried: I've looked around and attempted reordering my middleware in Django settings as I've heard that can cause issues based on the order in which it's processed. I've also tried different browsers. Firefox clued me into the fact there was no SameSite setting and that could be the issue. But once I updated that, it still will not appear. I tried using the response.set_cookie() … -
Not Null Constraint Failed in Django DateTime field with auto_now_add=True
I have a model in which there is datetime field. The structure is similar to the below one class ModelName(models.Model): uid = models.CharField(max_length = 50, default="") ordercreated = models.DateTimeField(auto_now_add = True) So when I am trying to create a entry in this field. Most of the times it is working fine. But sometimes it is throwing a Not Null Constraint Failed error. One more thing to note, more than one entry can be made in this model at the same time as I am using celery. Since, I have set the auto_now_add = True. So I was not expecting this kind of issue on creation. -
Django outputs verbose_name in quotes and parentheses in admin panel
My problem is the following. Code: ... class Meta: verbose_name = 'сайт', verbose_name_plural = '1. Сайт', ... Result: Why Django outputs verbose_name in quotes and parentheses in admin panel?