Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot import models into view.py
I have following models.py and views.py . I am trying to change the date to workweek in views file. But when i try to import date , I get the following error: NameError at / name 'date' is not defined Any idea why ?? and how to fix it ?? ---------models.py--------------->> class metric(models.Model): metric = models.CharField(max_length=200) date = models.DateField() value = models.FloatField() goal = models.FloatField() Mowner = models.CharField(max_length=200) ---------views.py ---------------->> from dashboard.models import * from .models import metric import pandas as pd from plotly.offline import plot import plotly.express as px from datetime import datetime def index(request): # Convert date to workweek weeks = [] for date_str in date: date_obj = datetime.strptime(date_str, '%d-%m-%Y') week_num = date_obj.isocalendar()[1] weeks.append(week_num) I tried importing the metrics in views.py file in different ways but still doesnot seem to work . -
How to set a rate limit a specific query in Django?
I have a multithreading function that looks up and locks each item in a list. (I'm locking the query for each individual item so that other users can't hit it at the same time). I also want to limit the rate in which users can look up a specific item, i.e. item1 was just searched so I don't want anyone else to be able to query item1 for 3 minutes. def worker(): """ Item search Multithreading Function """ while True: item = q.get() try: with transaction.atomic(): """ Lock the API for specified item search """ locked = Models.objects.filter(name__icontains=item)[0] locked_search = Models.objects.select_for_update().get(pk=locked.pk) print("Search for " + str(locked_search) + ", " + str(item) + " is locked") ### ADD SERVER RATE LIMIT FOR ITEM SEARCHED HERE ### # ... Do work here I've looked into Django Throttling and django-ratelimit but can't seem to find anything that limits the query rate of particular object. Anyone have any experience in this? Thank you for your help -
Django running function every minutes even without request
I want to write a web application with django. The user choose a specific function (which is defined by developer) and gives the necessary arguments and a frequency (e.g. every 1 minute). Now Django should call the function every 1 minutes and save the required output in database. So I want to ask how can I do scheduling using Django? I heard something about Celery. However, I'm looking for an easier solution. I don't want to end up with queue and messaging concepts! -
Creating multiple objects in DRF failing with error "'int' object has no attribute 'pk'"
I use ListCreateAPIView to create new instances of the Review model. Running my code in debug mode I can see that once the line serializer.is_valid(raise_exception=True) is executed, the code fails with the error AttributeError: 'int' object has no attribute 'pk'. models.py class App(models.Model): name = models.CharField(max_length=200, unique=True) identifier = models.CharField(max_length=200, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) image_url = models.URLField(blank=True, null=True) image_file = models.ImageField( upload_to='images/app_icons/', blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): """ Custom save method which fetches the image_file from the image_url, if image_file does not exist """ if self.image_url and not self.image_file: image = urllib.request.urlopen(self.image_url).read() self.image_file.save(self.name + '.jpg', ContentFile(image), save=False) super().save(*args, **kwargs) class Review(models.Model): comment = models.TextField() rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) review_id = models.IntegerField(unique=True) review_date = models.DateTimeField() review_author = models.CharField(max_length=200) app = models.ForeignKey( App, on_delete=models.CASCADE, related_name='reviews') serializers.py class ReviewListSerializer(serializers.ListSerializer): def create(self, validated_data): items = [Review(**item) for item in validated_data] return Review.objects.bulk_create(items) class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' list_serializer_class = ReviewListSerializer views.py class ReviewList(generics.ListCreateAPIView): """Retrieves lists of reviews and creates new reviews Default list method is modified to: - Return count of data under key 'count' """ queryset = Review.objects.all() serializer_class = ReviewSerializer def create(self, request, *args, **kwargs): data = request.data … -
Django CBV with DropzoneJS and django-storages backend for multifile upload form won't validate
I am using django-storages with (GCS backend) and would like to be able to use DropZonejs to upload multiple files to a model that has a FK. This is where I've gotten so far. It always comes back what Bad Request, form not valid. Assuming you're getting to this view from a detail view that includes a pk for 'thing'. (the backend works just fine uploading through django admin) Models.py class Thing(models.Model): name = models.CharField(max_length=25, verbose_name="name") def image_dir_path(instance, filename): # specify file naming return 'folder/{}/{}'.format(instance.thing, filename) class Image(MetadataFields): thing = models.ForeignKey(Thing, on_delete=models.DO_NOTHING, related_name="things", verbose_name=_("Thing")) my_image = models.ImageField(upload_to=image_dir_path, null=True, blank=True, verbose_name=_("My image")) Forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' widgets = { 'my_image': forms.ClearableFileInput( attrs={'multiple': True}), } Views.py class ImageUploadView(FormView): form_class = ImageForm template_name = "appname/_uploadimages.html" def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file') # thing= self.kwargs.get('pk') if form.is_valid(): for uploaded_image in files: # image = models.Image.objects.create(thing=thing, my_image=uploaded_image) image = models.Image() image.my_image = uploaded_image thing_instance= models.Thing.objects.get(id=self.kwargs.get('pk')) image.thing= thing_instance image.save() return HttpResponse('Image upload succeeded.') return HttpResponseBadRequest("Image upload form not valid.") Urls.py path('thing_detail/<int:pk>/view/', views.ThingDetail.as_view(), name='thing_detail'), path('thing/<int:pk>/image/upload/', views.ImageUploadView.as_view(), name='image_upload'), _uploadimages.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> … -
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: …