Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
There is a way to publish and consume message from Django to react?
I’m new in Django and I’m trying to “send messages״ from Django to react. My motivation is to make my react app more dynamic. I have a dashboard in my react app and I want to render dashboard component once data changed in Django. Another case: I have a posts and comments in my app and I want when some one add a comment to post to render comments component to show to all of the users the new comment without refresh the page. I think maybe I can use some message broker and publish a message from Django and react will consume the message and render components. There is something like that? Thanks you. -
How to add dynamic title to extend page in django?
I need to change the title of base.html based on rendered page in the {% block content %} -
TTFError at / Can't open file "C:\Users\-\AppData\Local\Temp\tmp52b4p0wi.ttf"
I'm trying to render the Arabic content to the pdf, through the xhtml2pdf library in Django but as mentioned in the documentation, xhtml2pdf comes up with limited supported languages, that's why I'm using the manual .ttf file, but it is showing me this error Here's my views.py def generate_pdf(request): pdf = render_to_pdf('index.html') if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_.pdf" content = "inline; filename='%s'" % filename download = request.POST.get("download") if download: content = "attachment; filename='%s'" % filename response['Content-Disposition'] = content receipt_file = BytesIO(pdf.content) return response utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Then main thing my .html file, with .ttf font format <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gift PDF</title> <style type="text/css"> @font-face { font-family: ArialUnicode; src: url("D:\Software House\Extras\Tests\pdfTest\main_project\static\fonts\arial-unicode-ms.ttf"); } body { margin: 0; font-family: "ArialUnicode", sans-serif; } </style> </head> <body> <div class="headings">إلي</div> </body> </html> -
Getting `Python(3427,0x117fae600) malloc: *** error for object 0x109823458: pointer being freed was not allocated`
Trying to set up a django repo on macOS Monterey with MySQL as the database. While running python manage.py migrate, getting the above error. -
Django Rest Framework: How to paginate results one month at a time?
I'm looking to get one month's worth of objects at a time on a given page in a model view set. I've pulled through the date I'd like to filter on in the select related clause of the queryset (please see code below) The transactions we're dealing with are low in volume so the size of the monthly dataset won't be overwhelming. My view is as such: @action(detail=False, methods=['get']) def list_advisor_commissions(self, advisor=None): advisor_commissions = self.queryset.select_related("transaction__transacted_at")\ .filter(advisor=advisor).order_by('-transaction__transacted_at') monthly_commissions = self.paginate_queryset(advisor_commissions) if monthly_commissions is not None: serializer = self.get_serializer(monthly_commissions, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(advisor_commissions, many=True) return Response(serializer.data) How would I go about doing this? I've had a look in the pagination section of the DRF API reference but I'm at a loss. Any pointers (to either relevant documentation or to a particular approach) would be greatly appreciated Cheers! -
While import from excel, + sign is not inserted in number field, django
I have one excel file which has SMS-no and WhatsApp-no fields. We are storing numbers with country codes in our database. While importing .xls file number is inserted successfully but the '+' sign is not inserted in the database. I am sharing a screenshot of the excel file and how it is stored in a database. Screenshot of excel file Screenshot of data inserted in the database Here is my code of views.py fs = FileSystemStorage() filedata = fs.save("ImportDB.xls", myfile) BASE_DIR = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) filepath = BASE_DIR + "\media\ImportDB.xls" book = xlrd.open_workbook(filepath) sheet = book.sheet_by_name("Sheet1") database = MySQLdb.connect( host="localhost", user="root", passwd="", db="mbs") cursor = database.cursor() query = """INSERT INTO addcontact (f_name, l_name, add_ln1, add_ln2, country, city, zip, sms_no, whtsp_no) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""" for r in range(1, sheet.nrows): f_name = sheet.cell(r, 0).value l_name = sheet.cell(r, 1).value add_ln1 = sheet.cell(r, 2).value add_ln2 = sheet.cell(r, 3).value country = sheet.cell(r, 4).value city = sheet.cell(r, 5).value zip = sheet.cell(r, 6).value sms_no = sheet.cell(r, 7).value whtsp_no = sheet.cell(r, 8).value values = (f_name, l_name, add_ln1, add_ln2, country, city, zip, sms_no, whtsp_no) cursor.execute(query, values) cursor.close() database.commit() database.close() fs.delete(filedata) Every data is inserted successfully. But number added without + sign in database. -
Python3 Objects All Could Not Print Anything
I start a shell with the below command: python manage.py shell Then I import my models called Port and User with the below command: from blog.models import Post from django.contrib.auth.models import User After then I have implemented below few commands: user = User.objects.get(username='ola') Post.objects.create(author = user, title = 'Sample title', text = 'Test') At the last, I have implemented below command: Post.objects.all() However, I could only get the string as below picture Could anyone help me with this? Why couldn't I get the string? -
How to Fix Error "App crashed" django project on Heroku
I got the following error: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=lovepik.herokuapp.com request_id=7fa3879b-1977-4080-84ce-1f313e91dede fwd="118.68.37.121" dyno= connect= service= status=503 bytes= protocol=https I use Python 3.8.10 I use Buildpack on Heroku: https://github.com/heroku/heroku-buildpack-google-chrome https://github.com/heroku/heroku-buildpack-chromedriver settings.py: import os from pathlib import Path # 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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-bxx!a1tokt9f1eu0wgu-a#w$bjwx^!65w3n&f9-wq5a&)2df^+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'lovepik' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'getlink.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / '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', ], }, }, ] WSGI_APPLICATION = 'getlink.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
How can I get value from loop select in template?
I wan to get value of item price in js for every select what would be my jquery function? {% for package in packages %} <div class="form-group col-md-6"> <label for="bedrooms">{{ package.title }}<span style="color: red;">*</span></label> <select class="form-control input-dsn" required id="bedrooms" name="package_{{ package.id }}" onChange="document.getElementByName('package_{{ package.id }}').value = this.value;"> {% for item in package.item_set.all %} <option value="{{ item.id }}" data-item-value="{{ item.price }}">{{ item.title }}</option> {% endfor %} </select> </div> {% endfor %} -
Sturggling to display data that I am inserting
I am doing shopping CRUD with model Products with Categories,sub categories,color,size as foreign keys using serializers because I am told to use foreign keys and serailizers.the problem is that the data that I am trying to insert isnt coming in the show page below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) show and insert functions def show(request): showall = Products.objects.filter(isactive=True) print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print(insert_clothes) form = POLLSerializer(data = insert_clothes,many=True) # print('form:',form.data) if form.is_valid(): form.save() # print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: return redirect('polls:show') else: print('GET',id) return render(request,'polls/product_insert.html') product_list.html <table> <thead> <tr> <th>Categories</th> <th>Sub-Categories</th> <th>Colors</th> <th>Size</th> <th>Title</th> <th>Price</th> <th>SKU Number</th> <th>Product Details</th> <th>Quantity</th> <!-- <th>Product Image</th> --> </tr> </thead> {% for result in data %} <tbody> <tr> <td><b>{{result.categories}}</b></td> <td><b>{{result.sub_categories}}</b></td> <td><b>{{result.color}}</b></td> <td><b>{{result.size}}</b></td> <td><b>{{result.title}}</b></td> <td><b>{{result.price}}</b></td> <td><b>{{result.sku_number}}</b></td> <td><b>{{result.product_details}}</b></td> <td><b>{{result.quantity}}</b></td> <!-- <td><b>{{result.image}}</b></td> --> <td style="position: relative;left:50px;"> <a href="/update/{{result.id}}/"> <button class="btn btn-primary"> Edit </button> … -
Django - Recursion Error with static main.css
Running into a max recursion error when hitting my static main.css file in django. Need help identifying the issue and how to correct it. Had no issues when my login/sign up pages were within my single dbManagementApp. After adding those to a new app (accounts) then adding the templates into a specific folder for each app, I received the below error message. Debugger In template ###, error at line 7 maximum recursion depth exceeded while calling a Python object 1 <!DOCTYPE html> 2 <html lang="en" dir="ltr"> 3 <head> 4 <meta charset="utf-8"> 5 <title>HOME</title> 6 {% load static %} <!-- load the static folder for css--> 7 <link rel="stylesheet" href="{% static 'main.css' %}"> Traceback File "C:\Users\lukep\anaconda3\envs\djangoenv\lib\site-packages\django\template\base.py", line 766, in __init__ self.literal = float(var) ValueError: could not convert string to float: "'main.css'" My main urls.py: from django.contrib import admin from django.urls import path, include from dbManagementApp import dbmviews from accounts import accviews urlpatterns = [ path('admin/', admin.site.urls), path('', include('dbManagementApp.dbmurls')), path('accounts/', include('accounts.accurls')) ] dbManagementApp/dbmurls.py from django.urls import path from . import dbmviews from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', dbmviews.home, name='home'), path('aboutus/', dbmviews.aboutUs, name='aboutUs'), path('pricing/', dbmviews.pricing, name='pricing'), path('contact/', dbmviews.contact, name='contact'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) dbManagementApp/dbmviews.py … -
How to kill a Celery task if it's not finished after a set period of time?
I have a Celery task that runs the main function of external Python scripts. However, some of the scripts may take a very very long time to execute and I'd like to set a time limit after which the tasks are aborted if they're not finished. I've tried all the ways I've found on other similar questions but I couldn't find a way to implement it. My task is the following : @app.task(name="execute_script", bind=True, base=CallbackTask) def execute_script(self, script_id, variables, name, start_time): self.update_state(state='EXECUTING') script = Script.objects.get(pk=script_id) mod = Script.get_script(script) # Getting the script's module try: mod.main(variables, name) except Exception as e: raise e return name Is there a way to set a time limit on a Celery task after which it's aborted if not finished ? -
Django css loads into admin site, but will not change the appearance
I am using nginx to load my static files. All of my static files appear where the should be in the STATIC_URL. When I inspect the admin page, I see the files loading properly. The styling still does not work. See, everything loads as expected, yet the css is not doing anythings. Does anybody know how to fix this? -
Multiple send request at one time
In a Django Project, Multiple send request at one time how can be handle. for example, If multiple person hit send button at same time in the website. How can be queue the request in Django-Website? -
I want to host django website which is more than 50mb as on github it only takes 25 mb .How can I do that?
Any hosting site like Heroku uses GitHub but the file is more than 50 Mb so I can't upload it -
Run bash file from Django views in Windows
I would like to run a bash file from a class written in views file of Django. I have tried many ways but didn't seem to work. So can you suggest some effective method for this ? -
Error during WebSocket handshake: Unexpected response code: 502 - Django
I am running my server on a ec2 instance with gunicorn and nginx. My site and project works but it gives error connecting with websockets. I am using Websocket in js to connect with Django channels. On my local server everything was working correctly but after deploying my site. Websockets are not working and giving me this error Error during WebSocket handshake: Unexpected response code: 502. What I have tried uptil now... I have installed redis and daphne. Configured daphne setting in nginx configuration. My Server is running on 80 port and I have set daphne on 8001 port. When I start daphne service it runs for some time and then disconnect/fail automatically but when it is running my websockets still cant connect. Any kind of help will be great for me. -
ModuleNotFoundError: No module named 'indiacowin'
enter image description hereplz, help me I don't think about the error.where indiacowin is my app name. -
How to use path parameter in GenericViewSet, Mixin CBS?
I'm new in DRF, Django. I want to make get API with path parameter which name is period. (ex. localhost:8000/api/ranks/{period}) # views.py class RankingView(mixins.ListModelMixin, GenericViewSet): queryset = Record.objects.all() serializer_class = RecordSerializer @action(methods=['GET'], detail=False, url_path='<str:period>', url_name='<str: period>') def get_rank(self, request, period): #logic return # urls.py router.register(r'api/ranks', RankingView) urlpatterns = [ path('', include(router.urls)), ] but it is not working. it might be easy to solve but I couldn't find answer, thank you for your help. -
Queryset random order specific to each user in Django
I want to order queryset randomly which is fixed for each user. When I use order_by("?") order change each time but I want different order for each user than don't change next time. For example for user one order is [obj1, obj5, obj3, obj4, obj2] and for user two is [obj5, obj2, obj1, obj3, obj4] and order for user one don't change but is different from other users. How can I do this? -
How to update redis - Django
I need help updating my cache. I use redis in my django project. Is there a way to trigger an auto refresh on redis itself so it performs a look up on the db to make an update on the cache. I am trying to implement this while avoiding signals and tasks. Is there anyway to trigger an auto refresh for a particular key in redis cache? -
Not able to view the data that I am inserting in Products model
I am doing shopping CRUD with Products model with categories,sub_categories,color,size as foreign key. the problem is that I am unable to view the data that I am trying to insert,below are the codes that I have tried. below is the model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) below is the show and insert function def show(request): showall = Products.objects.filter(isactive=True) print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() # print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) form = POLLSerializer(data=request.POST) if form.is_valid(): form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") return render(request,'polls/product_insert.html') show.html <td><b>{{result.categories}}</b></td> <td><b>{{result.sub_categories}}</b></td> <td><b>{{result.color}}</b></td> <td><b>{{result.size}}</b></td> <td><b>{{result.title}}</b></td> <td><b>{{result.price}}</b></td> <td><b>{{result.sku_number}}</b></td> <td><b>{{result.product_details}}</b></td> <td><b>{{result.quantity}}</b></td> insert.html <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="9-6 WEAR">9-6 WEAR</option> <option value="DESI SWAG">DESI SWAG</option> <option value="FUSION WEAR">FUSION WEAR</option> <option value="BRIDAL WEAR">BRIDAL … -
ImportError: attempted relative import beyond top-level package whilst referring within same app
I am here because google search didn't solve the issue yet. Project structure created in Visual Studio Community 2022 is like as follows, Project0 | --Project0 | ---settings.py --- <> | --App1 | ---models.py ---views.py ---forms.py | --App2 | ---models.py ---views.py ---forms.py ---tables.py Project0, App1, App2 are all in same hierarchy. When trying to run the solution, I am getting the following errors with App2 files, File "D:\Projects\Django\Project0\App2\urls.py", line 2, in <module> from . import views File "D:\Projects\Django\Project0\App2\views.py", line 5, in <module> from .tables import ProductTable, ProductHTMXtable File "D:\Projects\Django\Project0\App2\tables.py", line 2, in <module> from ..App1.models import List ImportError: attempted relative import beyond top-level package 1st issue: Here in App2 there are no models created. Instead, importing models from App1's model. So I guess the line --> from ..App1.models import List <-- might be wrong. If I remove those 2 dots '..' then I get Import could not be resolved error and the models are not being referred though its not stopping the solution from running. 2nd issue: Why do --> from . import views <-- & --> from .tables import <-- too are throwing errors. Unable to fix theses issues. Please help. -
how do i include get_absolute_url in my success_url of a class view
how do i include the get_absolute_url defined in the model in the class based view? model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(default="This is the Body of a Comment.") date_added = models.DateField(auto_now_add=True) time_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateField(auto_now=True) time_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Post Comments" ordering = ["-time_updated"] def __str__(self): return self.post.title + " | " + self.name.username def get_absolute_url(self): return f"/blogs/post/{self.post.slug}" view class DeleteCommentView(DeleteView): model = Comment template_name = "delete_comment.html" success_url = (refer the get_absolute_url) -
Hostname taking in python
In python i want to take current device hostname or mac address. Because i need to know which device user is using. List item I used socket.gethostname() but it shows me server host not current using device.