Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trigger action after file upload into server(File exist on the server path)
I hit one question below, could you please help to give some suggestions? Appreciate. I want to get duration of a videofile upload by user, then update this “duration” into database after file uploaded. I find "post_save", but it looks this execute before the file upload(before this file exist in this server path, so if I use "post_save", I will hit the error that this file is not exist). Here is my step: 1.Create Voice Model include Field: videoFile(FileField) and the duration of this video(FloatField) 2.After user upload this file into server, I will run my algorithm in the file path and calculate this duration of this file(input: filepath and this filename; output: duration) 3.After get this duration of this file, I need to update this database immediately So my question is, how to execute my algo immediately after this file already uploaded into server? And then update database. -
Is this possible to invoke the method of QGroundControl from a Django(Python) web application?
I have a Django web application hosted on Ubuntu 18.04 and on the same machine I have installed the QGroundControl. In my Django Web Application there are two buttons (Take Off & Return to Land). Is this possible that when I press the Take Off button from my Web Application, it should invoke the Take Off method of QGroundControl? How can I connect the Django (Python) Web Application & QGroundControl? There will be some API or Web Service etc? Any idea? -
How to move user authentication permissions from django admin to html select input
How to move user authentication permissions from django admin to html select input Cannot make status selectable from frontend <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <div class="container-fluid bg-light p-4"> <div class="form-group" > <label for="name">Name</label> <input type="text" class="form-control" id="name" placeholder="Enter name"> </div> <div class="form-group" > <label for="name">Surname</label> <input type="text" class="form-control" id="surname" placeholder="Enter Surname"> </div> <div class="form-group"> <label for="select1">Select status</label> <select class="form-control" id="select1"> <option>Supervisor</option> <option>Staff</option> <option>Active</option> </select> </div> <button class="btn btn-success">Add new user</button> </div> -
PayTm gateway integration
I'm trying to integrate Paytm gateway in my e-commerce website, but I get this error when I am checking out. Additional information: - I have used the same order parameters in another website I developed so there's nothing wrong with that. -
Running a group of tasks from another task celery
I'm having some trouble solving how to call tasks from another task in celery. Lets say I have the following tasks @shared_task def task_1(arg1, arg2): return @shared_task def task_2(arg1, arg2): return @shared task def task_3(arg1, arg2): return At the moment I'm calling tasks the following way. def task_caller(): task_1.apply_asyng(args=[arg1,arg2], queue='queue_1') task_2.apply_asyng(args=[arg1,arg2], queue='queue_1') task_3.apply_asyng(args=[arg1,arg2], queue='queue_2') I know i can check whether a task has finished or not with something along the lines of res = AsyncResult('task_id') res.ready() But, can this be done from inside another celery task? This way I can create custom tasks that call another tasks without stopping execution. I think about something like this @shared_task def super_task(arg1, arg2): task_1 = task_1.apply_async(args=[arg1,arg2], queue='queue_1') res_1 = AsyncResult(task_1.id) if res_1.ready(): # .... task2 and task3 But i'd have to check if each task has finished individually this way. Can tasks be grouped in some way and be called from another task? In my case task_2 does not need info from task_1 but I'd want to know if both tasks have finished. -
Getting The Multi Value dictketError when passing data through URL in Django contains spaces
This is the my Django URL looks like http://127.0.0.1:8000/viewpro.html?d=5%20STAR. But my passing data like d =5 STAR. But my problem is when using pname=request.GET['d'], it shows multivalueDictKeyError and i can't bind the data in the variable. Can u please help me to solve it.... -
How to put condition in django signals
I working on hospital management system.In this user first register as Doctor or patient for that i had userprofileinfo model.I also have profile model for the user which is create as soom as user register,here problem arise i want profile is only created if user type is pateint but i dont know how to check condition in django Signals. i tried some way but it show following error type object 'UserProfileInfo' has no attribute 'instance' files:- userprofileinfo.py patientprofile.py -
Why Is Django Creating Blank Text File With Project Name As Filename?
Python 3.8.2 Django 3.0.9 Ubuntu 20.04 I've been away from coding for a couple years & I went through the tutorial again to refresh my memory. After starting a new project, I wanted to rename the directory that contains asgi.py, settings.py, urls.py, & wsgi.py, so I can organize my project better. So I renamed that dir to config, & then changed the appropriate code in manage.py, asgi.py, settings.py, & wsgi.py, so it refers to "config.settings" & not "projectname.settings", since that dir is no longer called projectname. Now, when I run the server, it runs fine but it mysteriously creates a blank text file in the directory with manage.py, & the filename is the project name. Why is this happening? How do I stop it? -
How to get comment for the particular Blog Post in Django?
#Models.py #BlogPost Model class BlogPost(models.Model): POST_CATEGORY = ( ('Education','Education'), ('Tech','Tech'), ('Automobile','Automobile'), ('Other','Other') ) title = models.CharField(max_length=150) thumbnail = models.ImageField(upload_to='Blog Thumbnail') category = models.CharField(max_length=100, choices = POST_CATEGORY ) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=200, unique=True, null=True) tags = models.CharField(max_length=150, null=True, blank=True) writer = models.ForeignKey(User,on_delete=models.CASCADE,null=False) def __str__(self): return self.title #BlogComment Model class BlogComment(models.Model): post = models.ForeignKey(BlogPost,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True) timestamp = models.DateTimeField(auto_now_add=True) #Views Code def blogPost(request, slug): post = BlogPost.objects.filter(slug=slug) '''How to get comment for particularly this post''' comments = BlogComment.objects.filter(post=post) # It is giving a wrong answer '''The error I am getting ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.''' print(comments) context = { 'Post':post, 'Comments':comments } return render(request,'blogpost.html',context) How to get the comment for the particulary for this blog post? The error I am getting -" ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing." -
Crispy Field (combobox) depend of another Crispy Field(combobox)
I need Cbo 2 to work depending on the selection of Cbo 1. Excuse my english, I took the translator, pls help! I tried with a for and if, but, don't worked Model: class Producto(models.Model): """Clase Producto""" id_prod = models.AutoField(primary_key=True) nombre_producto = models.CharField(max_length=200) familia_producto_id_familia = models.ForeignKey(FamiliaProducto, models.DO_NOTHING, db_column='familia_producto_id_familia', verbose_name="Familia de Producto") tipo_prod_id_tip_prod = models.ForeignKey('TipoProd', models.DO_NOTHING, db_column='tipo_prod_id_tip_prod', blank=True, null=True, verbose_name="Tipo de Producto") precio_compra = models.BigIntegerField(verbose_name="Precio de Compra") precio_venta = models.BigIntegerField(verbose_name="Precio de Venta") stock = models.BigIntegerField() stock_critico = models.FloatField(verbose_name="Stock Critico") codigo_barra = models.BigIntegerField(verbose_name="Codigo de Barra") kilos_litros_id_kg_lt = models.ForeignKey(KilosLitros, models.DO_NOTHING, db_column='kilos_litros_id_kg_lt', verbose_name="Unidad de Medida") descripcion = models.CharField(max_length=50, blank=True, null=True) fecha_vencimiento = models.DateField(blank=True, null=True) imagen = models.ImageField(blank=True, null=True, max_length=100) class FamiliaProducto(models.Model): """Clase Familia de Producto""" id_familia = models.AutoField(primary_key=True) nombre_familia = models.CharField(max_length=50) class Meta: managed = False db_table = 'familia_producto' def __str__(self): return self.nombre_familia class TipoProd(models.Model): """Clase Tipo de Producto""" id_tip_prod = models.AutoField(primary_key=True) nombre_tipo = models.CharField(max_length=100) familia_producto_id_familia = models.ForeignKey(FamiliaProducto, models.DO_NOTHING, db_column='familia_producto_id_familia', blank=True, null=True, verbose_name="Familia del Producto") class Meta: managed = False db_table = 'tipo_prod' def __str__(self): return self.nombre_tipo I don't know much python and this simple thing is frustrating View: def agregar_producto(request): """Definimos los datos necesarios para agregar producto""" data = { 'producto':ProductoForm(), 'familia':FamiliaForm(), 'tipo':TipoForm() } if request.method == 'POST': formulario = ProductoForm(request.POST) if formulario.is_valid(): … -
'static'. Did you forget to register or load this tag?
This code WAS working, and now it's not. Is this a bug? I load static, but it says I am not. I don't know how to resolve it HERE'S MY CODE -
forbidden error 403 get in console while direct uploading to S3
I was upload image through server to s3. but I want to use direct uploading to S3 because of fast uploading. I used django-s3direct package for direct uploading. I follow all step but still I get this error. I am new at it. please Help while uploading I get error in console POST https://s3-ap-south-1.amazonaws.com/collegestudentworld-assets/img/mainpost/amar.jpg?uploads 403 (Forbidden) initiate error: collegestudentworld-assets/img/mainpost/amar.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403 settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME =os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_ENDPOINT_URL = 'https://s3-ap-south-1.amazonaws.com' #'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' #"https://collegestudentworld-assets.s3-website.ap-south-1.amazonaws.com/" AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' S3DIRECT_DESTINATIONS = { 'primary_destination': { 'key': 'uploads/', 'allowed': ['image/jpg', 'image/jpeg', 'image/png', 'video/mp4'], }, 'mainpost':{ 'key':'img/mainpost/', 'auth': lambda u:u.is_authenticated }, } bucket policy { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListAllMyBuckets" ], "Resource": "arn:aws:s3:::*" }, { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads", "s3:ListBucketVersions" ], "Resource": "arn:aws:s3:::collegestudentworld-assets/*" }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:*Object*", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::collegestudentworld-assets/*" } ] } CORS Configuration <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://127.0.0.1:8000</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>x-amz-server-side-encryption</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> <CORSRule> <AllowedOrigin>*.collegestudentworld.com</AllowedOrigin> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <ExposeHeader>ETag</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> … -
output to html results in JSON format clean
I have a django app that is executing some python scripts and returning results to webpage .... unfortunately the results that are in JSON format look nasty as hell and hard to read .. I am using Visual Studio Code and using the Terminal in that the JSON output is lovely and nice to read which is not good for this .... Anyone know a way to present the results in nice standard JSON Format on my webpage from django.shortcuts import render import requests import sys from subprocess import run, PIPE def button(request): return render(request,'homepage.html') def external(request): out=run([sys.executable,'//home//testuser//data-extract.py'],shell=False,stdout=PIPE) print(out) return render(request,'homepage.html',{'data':out}) -
Access class method inside AJAX call
I have two models with single to one relation. class myModel1(models.Model): fk = ForeignKey(myModel2) status = ChoiceField class myModel2(models.Model): def status(self): last = self.mymodel1_set.last() // Get last instance of related myModel1 status = last.status return status Then I send a queryset via ajax call. qs = MyModel2.objects.all() qs_json = serializers.serialize('json', qs) return HttpResponse(qs_json, content_type='application/json') Now how can i access status in my template in a way like qs_json[0].status? -
Error connecting Django 3.0.6 and Mysql with mysql-connector 2.2.9
I am trying to connect Django and MySQL, but I am getting the error below Error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/amitgupta/env1/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
How to test if it is a list or a value in a Django template?
In a template in Django I am importing a list of dicts and in one of the keys (tested) I can have either a single value or a list of values depending on the case. My context dict in the template looks something like this: context_dicts.append({'url': p.url, 'type_': p.type, 'error': error, 'tested': p.tested}) In the html template I want to if test the tested key to do something if it is a single value and something else if it's a list. So when looping through the dicts, if I use {% if value|length > 1% } it will give me the string size of the value when it's just a value and the length of the list when it's a list. How can I test the if to tell me if it's a "list of one value" or more? -
how to find issue in Django TemplateDoesNotExist - basic code
I cannot find issue that causing TemplateDoesNotExist. urls in main project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('quality.urls')) ] urls in quality app from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', view.index, name='index') ] and views from django.shortcuts import render def index(request): return render(request, 'index.html') -
Django - ImportError: cannot import name Attribute
Hello guys I've been developing a project with django in which I'm having this error. File "/home/naqi/Documents/projects/revolution-master-v2/revolution-master/calculation_engine/models.py", line 3, in <module> from asset_herarchi.models import Attribute ImportError: cannot import name 'Attribute' I've got two apps: asset_herarchi calculation_engine code for asset_herarchi/models.py : from djongo import models import uuid from django.core.exceptions import ValidationError from calculation_engine.models import AttributeCalculationConfiguration class Attribute(models.Model): DATA_TYPE_CHOICES = (("Double", "Double"), ("String", "String"), ("Boolean", "Boolean"), ("Float", "Float")) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) dataType = models.CharField(choices=DATA_TYPE_CHOICES, null=False, blank=False, default="Double", max_length=20) loggingFlag = models.BooleanField(default=False) calculatedAttribute = models.BooleanField(default=False) def __str__(self): return self.name def clean(self): if self.calculatedAttribute: try: print(self.attribute_calculation_configuration) except(KeyError, AttributeCalculationConfiguration.DoesNotExist): print("doesnot exist") code for calculation_engine/models.py: from djongo import models import uuid from asset_herarchi.models import Attribute # Create your models here. class AttributeCalculationConfiguration(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) variables = models.ManyToManyField(Attribute, related_name="as_calculation_variable", null=False, blank=False) expression = models.CharField(max_length=250, null=False, blank=False) attribute = models.OneToOneField(Attribute, on_delete=models.CASCADE, related_name="attribute_calculation_configuration") The problem is when I remove the import inside asset_herarchi/models.py that is "from calculation_engine.models import AttributeCalculationConfiguration" the error goes away but I need the import inside asset_herarchi/models.py to perform a custom validation when saving a new object of Attribute. Can anyone help? -
Django, how to group models by date?
Lets say that I have MyModel that has created_at and name fields. created_at is DateTime. Lets say that I have models with that kind of values: <id: 1, name: A, created_at: 04.06.2020T17:49> <id: 2, name: B, created_at: 04.06.2020T18:49> <id: 3, name: C, created_at: 05.06.2020T20:00> <id: 4, name: D, created_at: 06.06.2020T19:20> <id: 5, name: E, created_at: 06.06.2020T13:29> <id: 6, name: F, created_at: 06.06.2020T12:55> I want to make query that will return to me these models in this order: [ 04.06.2020: [<id: 1, name: A, created_at: 04.06.2020T17:49>, <id: 2, name: B, created_at: 04.06.2020T18:49>], 05.06.2020: [<id: 3, name: C, created_at: 05.06.2020T20:00>] 06.06.2020: [<id: 4, name: D, created_at: 06.06.2020T19:20>, <id: 5, name: E, created_at: 06.06.2020T13:29>, <id: 6, name: F, created_at: 06.06.2020T12:55>] ] I want to group all models by created_at field, but only using Date part of DateTime field. I know that I can make that kind of result just by using python loops, but are there any Django ORM way to solve this problem? -
Does cutting down code to different files cost more ressources and reduce performance?
I'm developing a Flask app, I got concerned about splitting out a python script to several files where they going to have repeated imports because of that. My current directory tree: ├───MyApp │ ├───routes.py │ └───app.py │ └───models.py │ └───forms.py routes.py import simplejson as json from flask import Blueprint, render_template, url_for, redirect, request, session, jsonify from flask_login import login_user, logout_user, current_user, login_required from forms import LoginForm from models import User users_blueprint = Blueprint( 'users_blueprint', __name__, static_folder='templates' ) posts_blueprint = Blueprint( 'posts_blueprint', __name__, static_folder='templates' ) # Function to get user details... @users_blueprint.route('/api/users/get', methods=['GET']): @login_required def get_users(): response = {} args = request.args # ... # Ban user, admin only can use. @users_blueprint.route('/api/users/ban', methods=['POST']) @login_required def ban_user(): # checks then ban given id # ... # ... # Function to get posts details given id or without id... @posts_blueprint.route('/api/posts/get', methods=['GET']): # ... # ... My desired directory tree: ├───MyApp │ ├───routes │ │ └───api │ │ └───users.py │ │ └───posts.py │ └───app.py │ └───models.py │ └───forms.py routes.api.users import simplejson as json from flask import Blueprint, render_template, url_for, redirect, request, session, jsonify from flask_login import login_user, logout_user, current_user, login_required from forms import LoginForm from models import User users_blueprint = Blueprint( 'users_blueprint', __name__, static_folder='templates' … -
Adding A Section To Admin Page
Ive changed certain parts of my admin page and played around extending the templates (so I have the file structure set up and working). I now want to go a bit further. I want to add a column next to the 'recent activity' column on the admin page which would list all the most recent django-notifications the admin has received. I am guessing I'd extend the base.html and add my notifications there. My first question is is this the best place to do this? The next, bigger thing is that I would need to modify the original views.py file to do this. Surely this isnt a good idea? Poking around in the Django Admin views.py sounds like a terrible idea and makes me think that this kind of thing shouldnt be done, however id still like to know for sure before I give up on it. I can find information on adding views to Django Admin, but nothing on adding content like this to the admin front page. Thank you. -
How to pass in variable into Django Form?
I've been reading lots of questions like this on stackoverflow but none seem to work. All I want to do is make a filtered form dropdown. I'm not sure how do go about doing it. I get the error that main is not defined... but I'm sure that's because it's not initialized or something? I'm very confused lol. My form code looks like this: class AssignForm(ModelForm): class Meta(): model = Address fields = ['overseer','publisher', 'status'] def __init__(self, *args, **kwargs,): super(AssignForm, self).__init__(*args, **kwargs) self.fields['publisher'].queryset = Publisher.objects.filter(service_group=main) Here is my View: def assignment(request, pk_a): assign = Address.objects.get(id=pk_a) num = request.user.overseer.publisher_set.first() main = num.service_group.id print(main) I would like to use the variable: main inside my form dropdown so I can limit the dropdown relative to the overseer. How can this be accomplished? Thanks! form = AssignForm(main, request.POST, instance=assign) context = {'form':form,} return render(request, 'sms/assign.html', context ) -
Storing and rewriting a constant variable (session key) in Django
Need advice. I have a program that sends a request for getting data to an external service. In order to receive data from this service, I must have a session key that is valid for 24 hours. A prerequisite for this service is to receive the key once a day. I created a constant in settings.py for key storage AUTHENTICATION_KEY = "" I created a task that makes a request for a key clock.py from apscheduler.schedulers.blocking import BlockingScheduler import os from django.conf import settings from clients.authentication import get_session_id # session key request function sched = BlockingScheduler() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') @sched.scheduled_job('cron', hour=0, minute=0, timezone='Europe/Kiev') def sess_id(): settings.AUTHENTICATION_KEY = get_session_id() return settings.AUTHENTICATION_KEY sched.start() Then I execute this program on Heroku. Of course, at first I performed this task at intervals and checked that the request for the key was successful, but when I call this key in another part of the program (where the request for data is received, session key comes with a request), the key variable (settings.AUTHENTICATION_KEY) is empty. As I understand it, rewriting a constant variable does not occur? Any suggestions on how to rewrite this variable globally? Perhaps there are other options how to get the key once a … -
Checked rows are not being deleted from HTML table/ Database (Django)
I created an html table in a django template <form action="/delete_team/" method="POST" > {% csrf_token %} <input type="submit" name = "delete" class="btn btn-danger float-right" value="Delete"> <table> <thead> <tr> <th><input type="checkbox" class="checkAll" name="checkAll"></th> <th>Team ID</th> <th>Male</th> <th>Female</th> <th>Officer</th> <th>Deadline</th> </tr> </thead> <tbody> {% for team in teams %} <tr> <td><input type="checkbox" name="check" class="case"></td> <td>{{ team.team_id}}</td> <td>{{ team.male }}</td> <td>{{ team.female }}</td> <td>{{ team.officer }}</td> <td>{{ team.date }}</td> </tr> {% endfor %} </tbody> </table> </form> here is the code that i wrote in my views.py: def delete_team(request): if request.method == "POST": pkm = request.POST.getlist("check") selected_objects = mtch_tbl.objects.filter(team_id__in=pkm) selected_objects.delete() return HttpResponseRedirect("/main/") now when i check a row and click delete nothing happens...i only get returned to my page again with the same data. Kindly point out my mistake, i can't figure out how to write the views -
Django shell_plus: How to access Jupyter notebook in Docker Container
I am trying to access a Jupyter Notebook created with the shell_plus command from django-extensions in a Docker container. docker-compose -f local.yml run --rm django python manage.py shell_plus --notebook My configuration is based on the answers of @RobM and @Mark Chackerian to this Stack Overflow question. I.e. I installed and configured a custom kernel and my Django apps config file has the constant NOTEBOOK_ARGUMENTS set to: NOTEBOOK_ARGUMENTS = [ '--ip', '0.0.0.0', '--port', '8888', '--allow-root', '--no-browser', ] I can see the container starting successfully in the logs: [I 12:58:54.877 NotebookApp] The Jupyter Notebook is running at: [I 12:58:54.877 NotebookApp] http://10d56bab37fc:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6 [I 12:58:54.877 NotebookApp] or http://127.0.0.1:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6 But I can't open the url. I have forwarded the port 8888 in my docker-compose, tried to use localhost instead of 127.0.0.1 and also tried to use the containers IP w/o success. It feels like I am missing the obvious here … Any help is appreciated.