Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After Changing Python Version 3.6 to 3.10 I got cannot import name 'Callable' from 'collections'
File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid_init_.py", line 5, in from .celery import app as celery_app File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid\celery.py", line 3, in from celery import Celery File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\five.py", line 306, in getattr module = import(self.object_origins[name], None, None, [name]) File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\app_init.py", line 14, in from celery import state File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery_state.py", line 20, in from celery.utils.threads import LocalStack File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\utils_init.py", line 20, in from collections import Callable ImportError: cannot import name 'Callable' from 'collections' (C:\Users\Codertjay\AppData\Local\Programs\Python\Python310\lib\collections_init_.py) -
Django Rest Framework -Serializer inside serializer using same instance
So, I have a weird legacy issue where I have one model "Data", and for serialization purposes I need to restructure the fields. class Data(models.Model): id ... field_a field_b field_c date Then I have the serializers: class DataInfoSerializer(ModelSerializer): class Meta: model = Data fields = ['field_a', 'field_b', 'field_c'] class DataSerializer(ModelSerializer): data_info = DataInfoSerializer(required=False, read_only=True) class Meta: model = Data fields = ['id', 'date', 'data_info'] Now I somehow have to get DRF to use the same instance of Data that is passed into the "DataSerializer" to render the DataInfoSerializer. Any ideas how to achieve this? Or a better way. -
Data view in html table from django views
I am trying to display data the tables from the database in some tables in an HTML template from django views. The problem is that the words are in a list and I want each word to be in each field in the table, How can I do that? views.py: if request.method == 'POST': context = {} tp = request.POST.get('tp') ms = request.POST.get('mode_selection') elif tp == "Download" or tp == "Preview": usr = User.objects.get(username=request.user) if ms=='2': data = WordDifferentTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result'] elif ms=='3': data = LogicAnaloguiesTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12'] elif ms=='4': data = SimilarWInContextTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'] else: data = WordsTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5',) hds = ['word1', 'word2', 'word3', 'word4', 'word5',] return render (request, "base.html",context) else: return render (request, "base.html") HTML table: {% if data %} <div style="padding-top: 30px" class="row"> <h3 align="center">Preview</h3> <table style="border: 1px solid #dddddd;"> <thead> <tr style="border: 1px solid;"> {% for h in hds %} <th style="border: 1px solid;">{{h}}</th> {% endfor %} </tr> </thead> <tbody style="border: 1px solid;"> {% … -
How to set up a project using Saleor with a default django frontend
I want to start a project where I build a webshop and I got interested in Saleor. I would like to use this with the "default" django frontend. I was wondering how to start setting up the project. I want to fork the project but want to be able to update from origin when possible. For my project I might need to change models to my liking. What had in mind is for example the product model that I create a seperate app within saleor and make my own models that inherits from the Saleor products. But i don't know if this is the best way to do this. And does anybody else have an idea or suggestion on how to start this? Thanks -
Django framework project name is not valid [closed]
'rgshop.' is not a valid project name. Please make sure the name is a valid identifier. -
django and javascript question show and hide edit form from list of selected queries
I have the following in my index <div id="posts"> {% for post in posts %} <div class="card"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'profile' post.user.username %}">{{post.user.username}}</a> wrote:</h5> {%if post.user_id == user.id %} <div class="cardn"> <a href="#" onclick="editpost()">Edit</a> <div class="card-body" id="card-body" style="display: none"> <form action="editpost/{{post.id}} " method="post"> {% csrf_token %} <div class="form-group"> <label for="post_text" class="h4">Edit Post</label><br> <textarea name="post_text">{{post.text}}</textarea> </div> <button type="submit" class="btn btn-primary btn-sm">Edit</button> </form> </div> </div> {%endif%} <p class="card-text" id="post_text_{{post.id}}"> {{ post.text }}</p> <p class="card-text"><small class="text-muted">on: {{post.post_date}}</small></p> <p class="card-text"> <div data-id="{{post.id}}" class="card-link {% if post.current_like > 0 %} fas {%else%} far {% endif %} fa-heart">&nbsp<small class="text-muted">{{post.like_set.count}}</small> </div> </p> </div> </div> {% empty %} <h2>No posts</h2> {% endfor %} what i would like to reach is to show only the edit form for the clicked edit button using javascript here is my view def editpost(request, id): post = Post.objects.get( id=id) if request.method == "POST": text = request.POST.get("post_text") Post.objects.filter( id=id, user_id=request.session['_auth_user_id']).update(text=text) return HttpResponseRedirect(reverse("index")) else: return render(request, "network/editpost.html", { 'post': post }) my JS thats not working document.addEventListener("click", editPost); function editPost(event){ // Listener sees triggering event const clickedThing = event.target; // Event has useful properties const userCard = clickedThing.closest(".cardn"); if(userCard){ // Makes sure button has a `card` ancestor before proceeding // Now, with … -
Authorization in react with django rest api backend
I was trying to make an app where users could come and make rooms and their friend could join the room. I am using Django rest_framework as the backend and react as the frontend. For create room, the logic I was trying to implement was that if the user has already made a room and somehow clicking on create room the old room would be returned instead of creating a new room (I was trying to store the session id which then Django uses to retrieve the room if available. The request is made by axios in app.js. But each time the user press Create Room the session id is getting refreshed thus creating a new room. This is the posting part in App.js createRoom = () => { axios.post('http://localhost:8000/api/createroom', { withCredentials: true, }) .then(res => { const data = res.data; console.log(data); }) .catch(err => { console.log(err); }) } Django view to handle post request class CreateRoomView(APIView): def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset.first() else: room = Room(host=host) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) My logic seems to work in postman but not in react. Can someone explain what I … -
SSH Tunnel to private RDS instance from django
I have a django application and a RDS instance in a private VPC. I would to connect to it from my local machine, using a ssh tunnel. I already have this configured and I have tried the connection from pg-admin so there should be no problem in that configuration. My problem now is how to make that ssh tunnel in django. I have tried this solution, but it looks like sshtunnel python package does not support openssh keys.. I have tried to generate a valid key with ssh-keygen -t rsa but it still contains an OPENSSH private key. I think that's because I'm generating the key from MacOs. So I generated from a Linux environment and added it correctly. Now, my configuration looks like this: from sshtunnel import SSHTunnelForwarder ssh_tunnel = SSHTunnelForwarder( '<ec2 host amazon>', ssh_private_key='~/ec2-db', ssh_private_key_password='', ssh_username='ubuntu', remote_bind_address=('localhost', 5432), ) print("Here") ssh_tunnel.start() print("THere") DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'HOST': '<rds amazon dns>', 'PORT': ssh_tunnel.local_bind_port, 'NAME': '***', 'USER': '***', 'PASSWORD': '***', }, } The server with that configuration can start, but I cannot access it on localhost:8000 so I suppose the db connection has been made successfully but now I cannot check it. Any idea what may be … -
Hosting more than one django project on Apache Vhosts
Am trying to host more than one django projects [USING WINDOWS] on apache using virtual hosts same ip address but different port eg. 91 and 92 respectively. Whenever I call port 91 return project A but when I call port 92 still return project A. Virtual Hosts configurations are per image below. Static contents are served by nginx -
Django Channels consumers.py scope['user'] returns anonymousUser
I'm trying to create one to one chat but when I'm trying to get self.scope['user'] it returns AnonymousUser consumers.py class ChatConsumer(SyncConsumer): def websocket_connect(self,event): #error me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) self.thread_obj = Thread.objects.get_or_create_personal_thread(me,other_user) self.room_name = f'{self.thread_obj.id}_service' print(f"{self.channel_name} connected") async_to_sync(self.channel_layer.group_add)(self.room_name,self.channel_name) self.send({ 'type':'websocket.accept' }) def websocket_receive(self,event): print(f"{self.channel_name} message received {event['text']}") msg = json.dumps({ 'text':event.get('text'), 'username':self.scope['user'].username }) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type':'websocket.message', 'text':msg } ) def websocket_message(self,event): print(f"{self.channel_name} message sent {event['text']}") self.send({ 'type':'websocket.send', 'text':event.get('text') }) def websocket_disconnect(self,event): print(f"{self.channel_name} disconnected") async_to_sync(self.channel_layer.group_discard)(self.room_name,self.channel_name) print(event) routing.py from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from .consumers import ChatConsumer,EchoConsumer from channels.auth import AuthMiddlewareStack import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter([ path('ws/chat/',EchoConsumer()), path('ws/chat/<str:username>/',ChatConsumer()), ]) ) }) I think the problem is here in auth.py: @database_sync_to_async def get_user(scope): """ Return the user model instance associated with the given scope. If no user is retrieved, return an instance of `AnonymousUser`. """ # postpone model import to avoid ImproperlyConfigured error before Django # setup is complete. from django.contrib.auth.models import AnonymousUser if "session" not in scope: raise ValueError( "Cannot find session in scope. You should wrap your consumer in " "SessionMiddleware." ) session = scope["session"] user = None try: user_id = _get_user_session_key(session) … -
Django Form: How to create a new related object to a multiple select widget
I am quite sure I am missing something obvious at this point. Lets say I want to create a planed trainingssession which model looks like this: class PlannedTrainingSession(models.Model): created_by = models.ForeignKey(Member, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) aimed_date = models.DateField(null=True, blank=True) team = models.ForeignKey(Squad, null=True, blank=True, on_delete=models.CASCADE) run = models.ForeignKey(PlannedRun, null=True, blank=True, on_delete=models.CASCADE) and a run which model looks like this: class PlannedRun(models.Model): name = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=5000) distance = models.PositiveIntegerField(null=True, blank=True) effort = models.CharField(max_length=8, choices=[('low', _('low')), ('moderate', _('moderate')), ('intense', _('intense'))], blank=True) Now I basically want to recreate the functionality of the django admin interface, where I could create a PlannedTrainingSession with a form and select or add a related PlannedRun. So basically an add button next to the selection drop down which then opens a new form in a tab. How would I achieve that? -
How to select different ModelForms based on select value for DJANGO model form
I have a list of values. Within the list of values is a status which has a hyperlink to a particular model form. I want to dynamically change the hyperlink based on the select value to direct the user to different forms based on the select value. So, for example, when the Model value is pending, I want the hyperlink to go to the pending form. When the status is invoice sent and the use clicks the hyperlink I want the user to to go to the payment form. The code is below <table id="example1" class="table table-bordered table-striped" data-order='[[ 0, "desc" ]]' data-page-length='25'><button onClick="refreshPage()" class="btn btn-secondary float-right" title="Refresh"><i class="fa fa-sync"></i></button> <thead> <tr> <th>Script No.</th> <th>Entered on</th> <th>Script Type</th> <th>Patient</th> <th>Address</th> <th>Email</th> <th>Contact No</th> <th>Product</th> <th>Form</th> <th>Units</th> <th>Dispensing Price</th> <th>Status</th> <th>Dispatch Date</th> <th>Worksheet ID</th> <th></th> </tr> </thead> <tbody> {% for script in scripts %} <tr> <td>{{script.pk}}</td> <td>{{script.entered_on}}</td> <td>{{script.get_script_type_display}} <td>{{script.patient}}</td> <td>{{script.patient.address}}&nbsp;{{script.patient.city}}&nbsp;{{script.patient.AU_states}}&nbsp;{{script.patient.postal_code}}</td> <td>{{script.patient.email}}</td> <td>{{script.patient.mobile_number}}</td> <td>{{script.product}}</td> <td>{{script.product.form.description}}</td> <td>{{script.quantity}}</td> <td>$&nbsp;{{ script.dispensing_price }}</td> {% if script.dispatch_date is not none %} <td>{{script.get_script_status_display}}</td> {% else %} <td> <a class="edit" href="#" data-url="{% url "script:script_update_status" script.pk %}">{{script.get_script_status_display}}</a></td> {% endif %} {% if script.dispatch_date is none %} <td>Not Sent</td> {% else %} <td>{{script.dispatch_date}}</td> {% endif %} {% if script.document_id is none … -
When user registers to my app I have to collect: landing url and timestamp of landing url
Scenario: User clicks a link on some forum or ad and he lands on: myapp.com/?lg=1231231 ( or myapp.com/landing/bobby - we don't have these yet but I mean this should be global - not just on home route ) we have to store that landing page url and timestamp when he landed in session. User can then browse the site ( unregistered ) - and then he might decide to sign up - and we want that information stored. How can I accomplish this task? -
Django foreign key field read and write
I am using Django rest framework for a project. In the project, there is a Student model, which has a foreign key referring to a user object. class Student(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) When I read from Student, I would also like to get all the fields of the nested user. I can do that with nested serializers: class StudentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Student fields = '__all__' However, if I want to create a new user I cannot use the same serializer, because there is no way to pass a foreign key to the user field, and Django does no support nested create. I am currently using an additional field user_id = serializers.IntegerField(write_only=True) to get the foreign key for write, and customized the create method to handle the logic. I also tried using two different serializers for creating and fetching data. Both way worked, but I am just wondering if there is a more intuitive way to implement this? A more convenient or standard way perhaps? Is there some syntax that works like: if read: user = UserSerializer() that avoids creating two different things for the same serializer field under different conditions? -
How to change url path to name in django instead of id
sorry if I ask very a simple question, I'm just starting to learn about WebDev and I have a question about django url and I used rest framework. I have http://localhost:8000/api/projectList/1 and I want to change id to the name in the url, for example http://localhost:8000/api/projectList/project This is the code: model.py class ProjectList(models.Model): project = models.CharField(max_length=200) project_name = models.CharField(max_length=200) category = models.CharField(max_length=200) academic = models.CharField(max_length=200) view.py class ProjectListSerializer(serializers.ModelSerializer): class Meta : model = ProjectList fields = '__all__' class ProjectListViewset(viewsets.ModelViewSet): queryset = ProjectList.objects.all() serializers_class = ProjectListSerializer class ProjectListListView(generics.ListAPIView): serializer_class = ProjectListSerializer def get_queryset(self): return ProjectList.objects.all() class ProjectId(generics.RetrieveUpdateDestroyAPIView): queryset = ProjectList.objects.all() serializer_class = ProjectListSerializer urls.py urlpatterns = [ path("", include(router.urls)), path("projectList/", ProjectListListView.as_view()), path("projectList/<int:pk>", ProjectId.as_view()), ] Thank you, sorry for my simple question and my bad English. -
How can I adjust the user search of Django Guardian?
I'm using the GuardedModelAdmin of Django Guardian to let the Admin set the permissions. I get this "User identification" field with the helptext "Enter a value compatible with User.USERNAME_FIELD": Instead, I would like to have the helptext "Enter the users email address". How can I get that? -
Need to return the object from the celery shared task queue process
I have faced the error "kombu.exceptions.EncodeError: Object of type 'JsonResponse' is not JSON serializable " In my settings.py : CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' So it only accepts response as a json value. But i need to return the object or instance Example : I need to return file path. Thanks in advance. @shared_task def celery_upload(path, id , user_id): upload = Upload() result = upload.file_generation_validation(path, id , user_id) excel = Excel() file_path = excel.Export(result["error"], "aaa") return file_path if I return result it will be successful, But file_path object throws error. -
Django orm left join return data like mysql
I have two table like this: class Classroom(models.Model): name = model.ChartField() class Student(models.Model): name = model.ChartField() classroom = model.ForeignKey(to='Classroom', related_name='students') there has some data like this: | Classroom | Student | | ----- | ------- | | Classroom_A | student_1, student_2, student_3 | | Classroom_B | (no Student) | Now I want to get the data by Django orm like this (return 4 rows data): | Classroom_name | student_name | | --- | --- | | Classroom_A | student_1 | | Classroom_A | student_2 | | Classroom_A | student_3 | | Classroom_B | null | How can I write the orm? The result is similar this (This is not what I want): data = [] for classroom in Classroom.objects.all(): students = classroom.students.all() if students: for student in students: classroom.student = student data.append(classroom) else: classroom.student = None data.append(classroom) -
Dynamically render select choices Django
I posted a screenshot below to hopefully make this easier to understand so I will reference it in my question. I am trying to create a recipe cost calculator app. I have 3 model namely Recipe, RecipeIngredient and Ingredient The user will add ingredients to the database and then create recipes using those ingredients throught the RecipeIngredient model. When creating an Ingredient the user selects a unit eg. (grams). Now when the user goes to create a Recipe (see screenshot below) I want to only display the units that are relevant to that ingredient and not all of them for eg. A user added Beef and the unit was grams now when the user is adding a RecipeIngredient to the Recipe I want them to only be able to select from the "Weight" category in the example (see screenshot below). The reason for this is because grams can't be converted to milliliters and so it shouldn't even be a choice. If anything is unclear or you need more information just let me know. Models Recipe Models from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model from ingredients.models import Ingredient class Recipe(models.Model): """Store recipe information and costs""" class … -
TypeError: __init__() got an unexpected keyword argument 'service' error using Python Selenium ChromeDriver
When i am running the code on pycharm idle the code is going good without errors. when i converted #into exe file by using pyinstaller or auto-py-to-exe i am getting this type of error. # #i am not getting where i have to change.# ''' import time,datetime from datetime import date import selenium from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import pyautogui from pywinauto.keyboard import send_keys import calendar import openpyxl import tkinter as tk from tkinter import * from tkinter import messagebox as mb from pywinauto import application import pywinauto import comtypes.client driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) ''' -
Q object filter returns wrong queryset - inherited foreign key relations
I have the models User, Club, Investment and Match where a User can make multiple Investments related to Clubs who have multiple Matches. I want to query all matches of clubs, where a user is invested in. Models # User is Django base user # Club class Club(models.Model): """ A table to store all clubs participating """ country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30) # Investment class Investment(models.Model): """ A table to store all investments of an investor/user and associated clubs """ investor = models.ForeignKey(User, on_delete=models.CASCADE) target = models.ForeignKey(Club, on_delete=models.CASCADE) # Match class Match(models.Model): """ A table to store matches and their results """ home = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='home_team') away = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='away_team') Query idea in human language: Query all matches, where 'home' or 'away' club is an 'investment' 'target' of the 'user' View def render_dashboard_overview(request): qs_matches = Match.objects.filter( Q(home__investment__investor=request.user) | Q(away__investment__investor=request.user) ) context = { 'qs_matches': qs_matches } return render(request, 'dashboard/dashboard_overview.html', context) This is what I came up with but it returns a queryset of Clubs rather than matches.. -
Django, DRF: To get two different models in one query set
Two models exist as follows. class Video(models.Model): title = models.CharField(max_length=300) image_url = JSONField() sample_image_url = JSONField(blank=True, null=True) sample_movie_url = models.URLField(max_length=1000, blank=True, null=True) review = JSONField(blank=True, null=True) ... class UserVideo(models.Model): title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000, unique=True) preview_url = models.URLField(max_length=1000, blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) ... I would like to retrieve data with two mixed models as follows. We also need to do some sorting, etc. How should I describe the query set? [ { "title": "", "image_url": {}, "sample_image_url": {}, "sample_movie_url": "", "review": {} }, { "title": "", "thumbnail_url": "", "preview_url": "", "tags": [ {} ] } ... ] Also, in this case, only one Model can be specified for the DRF Serializer, but how can Is it possible to give two Models to Serializer? class Video_UserVivdeo_Serializer(serializers.ModelSerializer): class Meta: model = #Video, UserVideo ? fields = '__all__' -
404 Not found Page in Django when deploy with docker and cookiecutter
I'm having a weird problem when deploying to the production of Django. Previously when accessing https://gae-gw.systems. I work very normally, but today when I try to access again all 404 errors. Currently, I use Traefik as a proxy server. Consider the following configs: Traefik.yml entryPoints: web: # http address: ":80" http: # https://docs.traefik.io/routing/entrypoints/#entrypoint redirections: entryPoint: to: web-secure web-secure: # https address: ":443" certificatesResolvers: letsencrypt: # https://docs.traefik.io/master/https/acme/#lets-encrypt acme: email: "khoadautay@gmail.com" storage: /etc/traefik/acme/acme.json # https://docs.traefik.io/master/https/acme/#httpchallenge httpChallenge: entryPoint: web http: routers: web-secure-router: rule: "Host(`gae-gw.systems`) || Host(`www.gae-gw.systems`)" entryPoints: - web-secure middlewares: - csrf service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: accessControlAllowOriginList: "*" hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 urls.py urlpatterns = [ path("", index, name="index"), path("home/", HomeView.as_view(), name="home"), path(settings.ADMIN_URL, admin.site.urls), path("users/", include("erp_greenwich.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
javascript loop doesn't work for django formset field calculation only calcuate one formset field with id such as id_forms-0-rate
This is the code in my template it takes value from input field id and calculate the value. The code only works for one formset field or item such as one having id= id_form-0-rate. I dont know why loop doesnot work for added formset such as one having id= id_form-1-rate. template.html <script type = "text/javascript" > var id= $("#id_form-TOTAL_FORMS").val(); console.log(id); for(let i=0; i<10; i++) { console.log(i); $("#id_form-" + i + "-quantity").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); $("#id_form-" + i + "-rate").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); $("#id_form-" + i + "-discount").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); } </script> -
"message": "At least one block must be specified" error line-bot-sdk
I am making video component with this sample https://developers.line.biz/en/docs/messaging-api/create-flex-message-including-video/ and this sdk for line messaging app https://github.com/line/line-bot-sdk-python import linebot.models as lm message = lm.FlexSendMessage( alt_text='hello', contents={ "type": "bubble", "size": "mega", "hero": { "type": "video", "url": "https://example.com/video.mp4", "previewUrl": "https://example.com/video_preview.jpg", "altContent": { "type": "image", "size": "full", "aspectRatio": "20:13", "aspectMode": "cover", "url": "https://example.com/image.jpg" }, "aspectRatio": "20:13" } } ) push_message(line_user,message) error message is like this, LineBotApiError: status_code=400, request_id=a7ef5dbd-333e-4a69-b1ea-b8f277829485, error_response={"details": [{"message": "At least one block must be specified", "property": "/"}], "message": "A message (messages[0])\u00a0in the request body is invalid"}, What does it mean?