Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field id expected a number but got <Cart: John's cart>
I have this view I would like to create a cart or update the entries if the cart is already created and if a product is already in the cart then just update its quantity. I am getting an error saying Field id expected a number but got <Cart: John's cart>. Why is the id field even mentioned when I specifically put cart to filter, because I do not have the id of the Entry class CreateCart(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = CartSerializer def post(self, request): user = User.objects.get(id=request.data.get("user")) total = request.data.get("carttotal") usercart = Cart.objects.update_or_create(user=user, cart_total=total) products = request.data.getlist("products") for product in products: obj = json.loads(product) id = obj.get("id") qty = obj.get("qty") product = Product.objects.get(id=id) exists = Entry.objects.all().filter(cart=usercart, product=product) if exists: exists.quantity = qty else: Entry.objects.create(product=product, cart=usercart, quantity=qty) return Response("Items added or updated", status=HTTP_201_CREATED) This line Django is complaining about: exists = Entry.objects.all().filter(cart=usercart, product=product) -
Problem with tags in Django | used taggit for storing tags
<div id="tab-2" class="tab-pane fade show p-0"> {% for event in events %} {% for tag in event.tags.all %} {% if tag == 'Tech' %} <div class="row g-3"> <div class="col mb-5"> <div class="d-flex h-100"> <div class="flex-shrink-0"> <img class="img-fluid" src="{{event.e_image.url}}" alt="" style="width: 430px; height: 350px;"> <h4 class="bg-dark text-primary p-2 m-0">{{event.e_date}}</h4> </div> <div class="d-flex flex-column justify-content-center text-start bg-secondary border-inner px-4"> <h5 class="text-uppercase">{{event.e_name}}</h5> </div> </div> </div> </div> {% endif %} {% endfor %} {% endfor %} </div> class Events(models.Model): event_id = models.AutoField(primary_key=True, max_length=10) user_id = models.ForeignKey(User, on_delete=models.CASCADE) e_name = models.CharField(max_length=50) e_image = models.ImageField(null=True, blank=True, upload_to='eventimg') e_date = models.DateTimeField() e_url = models.URLField(null=True, blank=True) tags = TaggableManager() def __str__(self) -> str: return self.e_name When i try {% if tag == 'Tech'%} to display block only when tag is equal to Tech then its not workin. I mean that Block is not at all visible. There are multiple tags in a single event thus i am looping event.tags.all I already had installed, imported and mentioned taggit in settings Its working properly. But i am stucked in above situation -
raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'is_active' into field
I got this doubt, I'm creating a custom user model in Django and at the moment to apply the migrations, it throws me this error raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'is_active' into field. Choices are: cargo, centro, centro_id, direccion, fecha_nacimiento, id, imagen_perfil, last_login, logentry, nacionalidad, password, profesion, rut, sexo, telefono I share you my code, This is the model class Usuario(AbstractBaseUser): centro = models.ForeignKey(Centro, on_delete=models.CASCADE, verbose_name='Centro o Unidad', blank=True, null=True) telefono = models.CharField(max_length=100, unique=True, verbose_name='Teléfono') rut = models.CharField(max_length=100, unique=True, verbose_name='RUT') profesion = models.CharField(max_length=150, verbose_name='Profesión') cargo = models.CharField(max_length=150, verbose_name='Cargo') nacionalidad = models.CharField(max_length=100, verbose_name='Nacionalidad') sexo = models.CharField(max_length=10, choices=SEXO_CHOICES ,verbose_name='Sexo') fecha_nacimiento = models.DateField(auto_now=False, auto_now_add=False,verbose_name='Fecha de nacimiento', blank=True, null=True) imagen_perfil = models.ImageField(upload_to='perfil/', verbose_name='Imágen de Perfil', max_length='255', blank=True, null=True) direccion = models.CharField(max_length=250, blank=True, null=True, verbose_name='Dirección') objects = UsuarioManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['email', 'nombre'] def __str__(self): return self.first_name def get_email_user(self): return self.email.lower() def save(self, *args, **kwargs): self.email = self.email.lower() return super(Usuario, self).save(*args, **kwargs) def has_perm(self, perm, obj = None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_staff This is the serializer class UsuarioSerializer(serializers.ModelSerializer): class Meta: model = Usuario fields = '__all__' extra_kwargs = {'password': {'write_only': True}, 'id': {'read_only': True}} I was searching for a answer in several internet forums -
Abstract class and abastract Unitest
I use Django Rest Framework and I wrote something like this: class Vehicule(ABC): wheel = None roof = None def drive(): use wheel and roof, blabla... class Car(Vehicule): wheel = 4 roof = True class Bike(Vehicule): wheel = 2 roof = False It's working good and I want to write unitest with it.I want to write someting similar: class TestVehicule(ABC): wheel = None roof = None factory = None def test_how_many_wheel(self): self.assertEqual(factory.wheel, self.wheel) def test_is_roof(self): self.assertEqual(factory.roof, self.roof) class TestCar(Vehicule) wheel = 4 roof = True factory = CarFactory class TestBike(Vehicule) wheel = 2 roof = False factory = BikeFactory The goal is to write tests in TestVehicule and inherit in others class change variable and do all the tests with the child variable -
How to send a variable from javascript to html?
I would like to fill a table by data from database. I am developing my project using Django. However, required data are based on select elements (depended select), that why I used java script to get data from database. I was able to get required data with java script: const engineInput = document.getElementById('select_eng') const btnBox = document.getElementById('btn-submit') const aircraftForm = document.getElementById('ac-eng-form') const csrf = document.getElementsByName('csrfmiddlewaretoken') const flighInput = document.getElementById('flights') const tablePrint = document.getElementById('table_with_data') aircraftForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submittted') $.ajax({ type: 'POST', url: '/show-data/', data: { 'csrfmiddlewaretoken': csrf[0].value, 'engine': engineInput.value, 'flights': flighInput.value, }, success: function(response) { console.log(response) tablePrint.innerHTML = response }, error: function(error){ console.log(error) } }) }) Now, I want to transfer data from json response to html as a variable "table". How can I do this? I don't want to fill a table using javascript, instead I want to use template engine. <table> <thead> <tr> <th rowspan="2">Flight</th> <th rowspan="2">Date</th> <th colspan="2">Oil quantity, %</th> <th colspan="2">Oil temperature, %</th> <th rowspan="2">dt, hr</th> <th rowspan="2">Engine FH</th> <th colspan="4">Oil Consumption, Quarts/hr</th> </tr> <tr> <th>Qa</th> <th>Qb</th> <th>Ta</th> <th>Tb</th> <th>QH, raw</th> <th>Average for 10 flights</th> <th>Average for 20 flight</th> <th>Average for 30 flight</th> </tr> </thead> <tbody id="table_with_data"> {% for row in table %} <tr> <td>{{row.Flight_Num}}</td> <td>{{row.Flight_Date}}</td> <td>{{row.Oil_Quantity_Departure}}</td> … -
NOT NULL constraint failed when sending a post request with Django Rest Framework
I have a problem with my API. When I'm sending a Post request to create a new Message I got the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: chat_message.channel_id The models: class Channel(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(Account) created_date = models.DateTimeField(auto_now_add = True) class Message(models.Model): user = models.ForeignKey(Account, on_delete = models.CASCADE) channel = models.ForeignKey(Channel, on_delete = models.CASCADE) content = models.TextField(blank=False) created_date = models.DateTimeField(auto_now_add = True) The serializers: class ChannelSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only=True) class Meta: model = Channel fields = '__all__' class MessageSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) channel = ChannelSerializer(read_only=True) class Meta: model = Message fields = '__all__' class UserSerializer(serializers.ModelSerializer): """ Serializers For The User Object""" class Meta: model = Account fields = ["email","password","username","id"] extra_kwargs = {'password': {'write_only': True, 'min_length': 8 }} def create(self, validated_data): """ Create the user with encrypted password""" return Account.objects.create_user(**validated_data) def update(self, instance, validated_data): """Update The user""" user = super().update(instance,validated_data) return user And the views: class ChannelView(viewsets.ModelViewSet): """View for the channels""" serializer_class = ChannelSerializer queryset = Channel.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): """Retrieve channels linked to the authenticated user""" return self.queryset.filter(users = self.request.user) def perform_create(self, serializer): """ Create a new channel with users set in the request as users""" serializer.save(users = self.request.data.get('users')) class MessageView(viewsets.ModelViewSet): """View for … -
Serializing a ManyToMany field
I have two models in my django app, one user model and one keyterm model. When registering a new user, the user can specify one or multiple keyterms. And a keyterm can be affiliated to one or many users. The problem I am encountering is when registering a user with an existant/new keyterm. I think the issue is surfacing when I'm retrieving the data from the post request. Here is my code for : the user model, and the keyterm model Both the serializers class Keyterm(models.Model): keyterm = models.CharField(max_length=255, primary_key=True) class User(AbstractUser): name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = None keyterms = models.ManyToManyField('Keyterm', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class KeytermSerializer(serializers.ModelSerializer): class Meta: model = Keyterm fields = '__all__' class UserSerializer(serializers.ModelSerializer): keyterms = KeytermSerializer(many=True) class Meta: model = User fields = ['id', 'name', 'email', 'password', 'keyterms'] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): password = validated_data.pop('password', None) keyterm_data = validated_data.pop('keyterms', []) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() for keyterm in keyterm_data: name = keyterm['keyterm'] try: k = Keyterm.objects.get(keyterm=name) except Keyterm.DoesNotExist: k = Keyterm.objects.create(keyterm=name) instance.keyterms.add(k) return instance Here is the request I used to test: { "name": "User3", … -
Access django session and user asynch/in different (unix) process
I'd like to integrate a streamlit application - streamlit is based on tornado - into django via an <iframe>, while ensuring that streamlit requests only go through if there is an authenticated user in django running on the same domain - e.g. via nginx or both running on different ports. However, I'm experiencing issues with asynch-ness. I've set DJANGO_ALLOW_ASYNC_UNSAFE as a quick fix, but obviously don't get warm from database corruption due to concurrent access. So far I'm protecting myself from that by adding read-only access to the database, but can image particular django classes, e.g. the SessionStore, also aren't thread safe (although probably process safe?). Is there a safe way to do 'read-only' authentication via django in other wsgi(-ish) applications, like tornado? This is the tornado script, running next to it any django application with user authentication of whatever sort (default, saml2, etc). The django_authentication_middleware extracts the appropriate session id from the cookies and passes this the django's get_user function to then verify authentication. DJANGO_SETTINGS_MODULE should be set as for the django application. To get the error, disable DJANGO_ALLOW_ASYNC_UNSAFE. import os os.environ['DJANGO_ALLOW_ASYNC_UNSAFE'] = 'true' import asyncio from importlib import import_module from typing import Optional, Awaitable import django django.setup() from … -
Admin User model
My admin user model does not update new record when I register using UserCreationForm. Access the github code in the views I have imported Usercreationform has shown below and I did all the views coding. I do not know where I went wrong. I also rendered the form correctly into the template. But the annoying part comes after filling the form. It doesn't update in the admin panel once I accessed it // THE VIEWS from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def home(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'main/index.html', context) // THE TEMPLATES <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="register"> </form> </body> </html> -
Django formset of formsets, generates duplicate ids
Enough days were wasted already on trying to figure out how to work with formset_factory given the awful documentation. It generally works fine with multiple formsets combined in the same view as long as they do not overlap. Issues arise when a formset is composed of other formsets: forms.py from django import forms class FormA(forms.Form): field_a = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Field A', 'class': 'form-control'} ), label='', ) class FormB(forms.Form): field_b = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Field B', 'class': 'form-control'} ), label='', ) views.py from django.forms import formset_factory from django.shortcuts import redirect, render from myapp.forms import FormA, FormB def index(request): context = {} if request.method == 'POST': context['formset_a'] = formset_factory(FormA)(request.POST, prefix='A') context['formset_b'] = formset_factory(FormB)(request.POST, prefix='B') return redirect('new') context['formset_a'] = formset_factory(FormA, extra=2)(prefix='A') context['formset_b'] = formset_factory(FormB)(prefix='B') return render(request, 'index.html', context) index.html {% load static %} {% load bootstrap5 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My title</title> <link rel="stylesheet" href={% static 'css/bootstrap.min.css' %}> </head> <body> <form method="post"> {% csrf_token %} {{ formset_a.management_form }} {% for fa in formset_a %} {{ fa.field_a }} {% csrf_token %} {{ formset_b.management_form }} {% for fb in formset_b %} {{ fb.field_b }} {% endfor %} {% endfor %} <button class="btn btn-success" type="submit">Create</button> </form> </body> </html> urls.py … -
Nginx gives 502 bad gateway but only for a few http requests
I made a portfolio website using django and hosted it on a digitalocean droplet with Postgres, Nginx, and Gunicorn. After testing it I noticed that a few of the subpages of the portfolio projects gives back the 502 response after 1 second of loading but interestingly enough it's not all of them. The pages that fail tend to have more images but I tried excluding the images the views.py sends to the template, however the ones with the 502 response failed out again. (for context the images are provided by local server side and not by an online storage service) The issue seems to be resolved when I reload those pages manually. Here is the views.py: def project_view(request:HttpRequest, name:str) -> HttpResponse: project = Project.objects.filter(name=name).first() images = ProjectImages.objects.filter(project=project) # for every image in images this downscales that image and compresses it with PIL for projectimage in images: generate_projectimage(projectimage) # this downscales the thumbnail image of the project generate_downscaled_thumbnail(project) return render(request, "project.html", { 'project': project, 'images' : images, }) The template that receives it: <div class="carousel"> <div class="carousel-cell"> <img src="data:image/jpeg;base64,{{ project.downscale }}" data-src="/media/{{ project.thumbnail }}"> </div> {% for projectimage in images %} <div class="carousel-cell"> <img src="data:image/jpeg;base64,{{ projectimage.downscale }}" alt="" data-src="/media/{{ projectimage.image }}"> … -
Get data from get request. Django
After authorization in some social network, it (social network) transmits the value of the code in the GET request and redirects the user to the profile page, I try to extract data from the GET request, but in response I get None. views.py @login_required def vk_auth(request): params = { 'client_id': '51568560', 'client_secret': 'bE8JDZO9qHTOaVb4XdcT', 'redirect_uri': 'http://127.0.0.1:8000/profile', 'display': 'page', 'response_type': 'code', } return redirect('https://oauth.vk.com/authorize?' + parse.urlencode(params)) @login_required def vk_link(request): code = request.GET.get('code') return HttpResponse(code) There is a GET request in the debug toolbar in the reguest, and there is also a code variable with the desired value, but I still can't get this data How can I get this code? -
How to import packages that are outside a django project
I have the following folder structure my project, the backend directory is a django project, when I run python manage.py runserver from the backend, I get an import error whenever I import functions from TwitterChatBot package, what's the problem and the solution? ├── backend │ ├── backend │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── chatbot │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── conftest.py ├── dockerfile ├── document_scraping │ └── scrape.py ├── index │ ├── build_index.py │ └── index.jsonl ├── nginx.conf ├── prompts │ ├── passage_summarization.txt │ └── question_answering.txt ├── README.md ├── requirements.txt ├── start-server.sh └── TwitterChatBot ├── chat.py ├── gpt_3_manager.py ├── index.py ├── __init__.py ├── main.py ├── prompt.py ├── tests │ ├── chat_test.py │ ├── gpt_3_manager_test.py │ ├── index_test.py │ ├── prompt_test.py │ └── utils_test.py └── utils.py -
Django ImproperlyConfigured("The SECRET_KEY setting must not be empty.") error
I currently got a Django project and have been tasked to run it locally. Currently it is very large and so the settings e.t.c can get confusing. I'm trying to run manage.py runserver and it keeps giving me secret key not configured error. (Although my secret key is configured in settings like it ususally is) I read a previous post that this could be due to circular dependencies so i went through the settings code and found something that COULD possibly be an issue but I'm not completely sure. ### CELERY #### CELERY_IMPORTS = [ 'X.Y.tasks', 'mailchimp_synchronisation.tasks' ] When I open these files from their respective folders the first import I see is: from django.conf import settings I'm not sure if this is what's causing the error because: It seems like just information and not actually running this piece of code My settings file is saved inside a folder called settings and is saved as base.py instead of just settings.py I've tried adding the secret key to my docker compose, adding the settings file as well in the environment but it always seems to give the same error -
APScheduler not running in Django
APScheduler is not running in Django. I want to use the APScheduler library in a Djnago frame to get LINE notifications when a todo list deadline comes up, but I am not getting LINE notifications. Is there something wrong with the APScheduler settings? testapscheduler.py from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests import json from .models import Todo def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) #BackgroundSchedulerの設定 def start(): scheduler = BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=1)#1秒ごとに実行 scheduler.start() apps.py from django.apps import AppConfig class TodoConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'todo' def ready(self): from .testapscheduler import start start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
start Django project in vs code
Im trying to learn Django. I started a youtube tutorial managed to do some basic stuff etc. After closing the vs code, the server closed too. Now when I try to start the project using python manage.py runserver or python manage.py startapp, i get the error "zsh: command not found: python" im trying to do all that in vs code terminal -
Company - Worker Algorithm in Django
I want to ask a question about my algorithm. The operation should be like this; There is one or more companies, this is the top cluster. There are work fields affiliated with these companies. When the company receives a project, it gives it to the work fields, and at the same time, this project has a total price. It divides work packages into work fields and allocates a budget to each work field from the total price of the project. Each work field belonging to the company has its own work package to be completed, and there is a price for this package. When any work package is completed, I want to reduce both the price of the work completed from the work field budget and the total price of the project. But I was undecided on how to connect the payment. Can you help me? Here is the ERD Model link: https://ibb.co/ch0F3Bg I made a mistake on the worker part, ignore it. 🙂 More than one worker can work in a work field, I will fix it while connecting the diagram 🙂 I have given all the details above. -
How do I get the values out of a string object
I am sending some values to a Django back end and I would like to get the values from the object. This is the part that gets the data on the front end and sends it to the back end: function addCartToDB(cart) { let formdata = new FormData(); formdata.append("user", loggedUser); formdata.append("carttotal", cart.carttotal); for (var item of cart.items) { let data = { id: item.id, qty: item.qty, }; formdata.append("products", data); } axios .post("api/v1/cart/c/", formdata) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } This is the view that is supposed to process the request: class CreateCart(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = CartSerializer def post(self, request): entries = request.data.getlist("products") for entry in entries: breakpoint() Since there is just one product in the cart the entry object looks like this: [object Object] and the data that is supposed to be in there is the product id and the product quantity which will be strings. How do I get the values of out the object please? -
Nuxt 3 dynamic route not found
I have a problem with nuxt 3 frontend application: I use nuxt 3 as my frontend and django as my backend and api service. When I run npm run build (it executes nuxt generate) command in local, to get files ready to be send to production, the files like /blog/9, /blog/6, /blog/4 etc. are generated into /.output/public dir. These numbers are posts ids, and posts are fetching from backend using axios, and they are generated because they already exists on backend and are automaticly fetching by nuxt when command is ran. The thing is, when i enter the domain like https://example.com/blog/9 via button or link on website, that includes the id param, that has been previously generated via npm run build command, it's all good, even with blog posts that have been generated after deploying nuxt files the production server, like https://example.com/blog/12 or https://example.com/blog/27. But when I enter the url https://example.com/blog/12 manually, not via the link or buttom on the website, it returns me a default 404 error provided by the server, as the post wasn't found. I want it to automaticly get id param from url and execute the fetch method by axios. Axios method from Post.vue component: import … -
Enable CSRF TOKEN in Django html coded using element-ui
I am trying to add CSRF TOKEN (to ensure CSRF protection) to my html script in Django for the POST requests so that it will not be classified as an unsafe request. However I am unsure of where I should place it. When I place it within {% verbatim %}, it comes off as a text as shown on in the image. Really desperate and really appreciate any advice. {%extends "doctor.html" %} {% block emr %}active{% endblock %} {% block mainbody %} {% verbatim %} {% csrf_token %} <div id="app2" class="container"> <el-row :gutter="20" style="width: 90%; height: 120%;"> <el-col :span="12"> <div class="info-wrapper"> <div class="header">Add new medication delivery jobs</div> <el-form ref="deliveryInfoForm" :model="deliveryInfo" :rules="deliveryRules" label-width="110px" label-position="left"> <el-form-item label="Order ID" prop="order_id"> <el-select v-model="deliveryInfo.order_id" placeholder="Select an Order ID" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in order_id" :key="item.id" :label="item.order_id" :value="item.order_id"> <span style="float: left">{{ item.order_id }}</span> </el-option> </el-select> </el-form-item> <el-form-item label="Box Number" prop="box_number"> <el-select v-model="deliveryInfo.box_number" placeholder="Default: Box 1" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in box_options" :key="item.value" :label="item.label" :value="item.value"> <span style="float: left">{{ item.label }}</span> </el-option> </el-select> </el-form-item> <el-form-item> <el-button style="width: 100%;" type="primary" @click="onSubmit">Confirm</el-button> </el-form-item> </el-form> </div> </el-col> <el-col :span="12"> <div class="info-wrapper"> <div class="header"><center>Medications Delivery Status</center></div> <el-table :data="list" stripe style="width: 100%" :cell-style="{ textAlign: 'left' }" :header-cell-style="{textAlign: … -
Is there a way to make chatsocket.send send the data to all of the instances at the same time?
In a typical consumers class, we would have the following: class SomeConsumer(AsyncWebsocketConsumer): async def connect(self): ... async def disconnect(self, close_code): ... async def receive(self, text_data): ... async def chat_message(self, event): await self.send(text_data=json.dumps({"event": event})) In this example, self.send is called once for each instance of SomeConsumer. However, I don't think all of the chat_message methods get called concurrently, at the same time for each instance, since I notice a delay in the display of the javascript data when I have multiple windows open. Ideally, I would like the data to display at the exact same time across X number of windows. Is there a way to make this work? I tried to create tasks and then await them once number_of_chat_message_calls = number_of_instances, like this: async def chat_message(self, event): SomeConsumer.count+=1 SomeConsumer.tasks.append(asyncio.create_task(self.send(text_data=json.dumps({"event": event})))) if SomeConsumer.count == SomeConsumer.consumers: done, pending = await asyncio.wait(SomeConsumer.tasks) SomeConsumer.tasks.clear() SomeConsumer.count = 0 but it still doesn't display the data synchronously. Is there any way to achieve this? -
How to improve reliability of Django-Q Schedule Tasks
My project currently has about 300 scheduled tasks. Some of these run every hour on the hour and some run once a day (at midnight). The tasks make API calls to third party API's. This is the current set up of my Q_CLUSTER Q_CLUSTER = { 'name': 'DataScheduler', 'workers': 3, 'timeout': 15, 'retry': 300, 'queue_limit': 10000, 'bulk': 10, 'max_attempts': 1, 'orm': 'default' } Of the 300 tasks, about 120 of them fail (different ones every time). If I manually trigger these to run they pass so there isn't anything wrong with the actual request. I believe the q cluster can't process all of the tasks when they are triggered at the same time. I think this can be improved by tweaking the Q_CLUSTER settings but I'm unsure how best to do this. I've tried running through the documentation https://django-q.readthedocs.io/en/latest/configure.html But I'm unsure how to improve the success rates of the scheduled tasks. I've struggled to find any other articles or documentation to explain how best to utilise these settings. My question is - how can I improve these settings to ensure the tasks pass? With time I will have more scheduled tasks so looking to address now before it gets … -
Django generating a query in the group
I have models like this: class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) class Project(models.Model): name = models.CharField(max_length=128) class EmployeeProject(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='employee_projects', ) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) role = models.ForeignKey(ProjectRole, on_delete=models.CASCADE) skill_level = models.ForeignKey(SkillLevel, on_delete=models.CASCADE) hourly_rate = models.DecimalField(decimal_places=2, max_digits=9) class TaskRole(LogOnSaveMixin, DiffModel): task = models.ForeignKey( Task, on_delete=models.CASCADE, related_name='roles', ) estimated_hours = models.FloatField(null=True, blank=True) And I have a queryset like this: qs = Task.objects.all() user = self.request.user host_roles = EmployeeProject.objects.filter( employee=user.employee, ) qs = qs.annotate( total_estimated_hours=Sum('roles__estimated_hours'), ) open_tasks_qs = qs.filter( Q(project__in=host_roles.values('project_id')), ).filter( ( Q(total_estimated_hours__isnull=False) ), ) qs = open_tasks_qs | qs.filter(author=user).distinct() qs = qs.values('id') qs = qs.distinct() return qs The problem is that this query yields an error, saying that more than one row returned by a subquery used as an expression The corresponding sql looks like this: SELECT DISTINCT "tasks_task"."id" FROM "tasks_task" LEFT OUTER JOIN "tasks_taskrole" ON ( "tasks_task"."id" = "tasks_taskrole"."task_id" ) GROUP BY "tasks_task"."id", ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) HAVING ( ( "tasks_task"."project_id" IN ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) AND SUM( "tasks_taskrole"."estimated_hours" ) IS NOT NULL ) OR "tasks_task"."author_id" = 1 ) ORDER BY "tasks_task"."id" DESC There are two questions: How … -
How to send data from other Django app to other server
How to send data from other Django app to other server using HTML file (client side), with cors I’ve tried disabling cors -
How to handle POST net::ERR_CONNECTION_REFUSED error in Axios Vue.js django
I am using axios to send the data for the backend but it keeps break, what should i do? in .then(response => { this.$router.push('/Log-in') return response }) i returned the "response" because the console is saying "error 'response' is defined but never used" vue.js file import axios from 'axios' if (!this.errors.length) { const formData = { username: this.username, password: this.password, email: this.email } axios .post('/api/v1/users', formData) .then(response => { this.$router.push('/Log-in') return response }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)); } else if (error.massege) { this.errors.push('Something went wrong, Please try again!') console.log(JSON.stringify(error)); } }) } setting.py django CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', 'http://127.0.0.1:8000/' ]