Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when modifying Django data from HTML
I have a small error when trying to modify data stored in Django Oracle, when trying to add the link that takes me to the function and modifies me the user throws me the following error: NoReverse Match at/administration Reverse for 'editar/' not found. 'editar/' is not a valid view function or pattern name. I leave you part of my code urls.py urlpatterns = [ path('', views.index, name = "index"), path('galery', views.galery, name = "galery"), path('toregister', views.toregister, name = "toregister"), path('register', views.register, name = "register"), path('administration', views.administration, name = "administration"), path('editar/<int:id>', views.editar, name = "editar") ] views.py: def administration(request): #Administracion usuarios = Usuario.objects.all() datos = { 'usuarios': usuarios } return render(request, 'store/administration.html', datos) def editar(request, id): usuario = Usuario.objects.get(id = id) if request.method == 'GET': form = UsuarioForm(instance = usuario) contexto = { 'form': form } return render(request, 'store/register.html', contexto) models.py: class Usuario(models.Model): nombre = models.CharField(max_length = 60, verbose_name = 'Nombre del Usuario') apellidos = models.CharField(max_length = 60, verbose_name = 'Apellidos del Usuario') email = models.CharField(max_length = 50, verbose_name = 'Email del Usuario') rut = models.CharField(max_length = 10, primary_key = True, verbose_name = 'Rut del Usuario', unique = True) contraseña = models.CharField(max_length = 15, verbose_name = 'Contraseña del Usuario') def … -
How to add a task from a celery task to the main process loop:django
I want to add a task to the asyncio loop of the main process from celery that runs periodically. I've looked into this to the point where it might be feasible with multiprocessing. However, in the end it looked like I would need to check periodically in the main process to see if the task was added. Is it possible to directly add a task from another process to the main process loop? loop.py import asyncio LOOP = None def run_loop(): global LOOP LOOP = asyncio.new_event_loop() LOOP.run_forever() init.py from celery import app as celery_app from project import loop import threading __all__ = ('celery_app',) threading.Thread(target=loop.run_loop).start() tasks.py from celery import shared_task from project.celery import app from app1 import task @shared_task def add_task(): asyncio.run_coroutine_threadsafe(task.task1(), loop.LOOP) app1/task.py import time def task1(): time.sleep(1) print("abcd") -
Trouble linking CSS stylesheet to HTML in Django
I've formatted my base page properly and I have used the correct tags in my HTML pages, yet my local css file (main.css) will not load. base.html <!DOCTYPE html> <html lang="en"> <head> {% block 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"> {% load static %} <link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/main.css' %}"/> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@300&display=swap" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% block script %} <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/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <script src="https://kit.fontawesome.com/07a07b3c8d.js" crossorigin="anonymous"></script> {% endblock %} <title>{% block title %}Edward's Portfolio{% endblock %}</title> <style> body { font-family: "Source Code Pro", monospace; } </style> {% endblock %} </head> <body> {% block content %} <h1>My Portfolio</h1> {% endblock %} </body> </html> I have set my STATIC_ROOT and STATIC_URL correctly in settings.py but I have still found no success. If I could get some assistance I would appreciate it. -
Best way to do user authentication with Django backend and React frontend?
I know this is a really general question but I really wanted advice on how to approach this. I have a Django backend running on AWS Elastic Beanstalk and a React frontend. I want to implement user authentication but I'm not sure on how to approach it. Should I do Django default user authentication by creating models and etc? Or should I instead use something else through the React frontend and JWT? I'm new to this and wanted to make sure what is the best approach for this. Thank you so much -
Entering URL in browser causes Python Django ReverseMatchError to be thrown
I am working on a python project while following a book to create an online shop website, I have created the models, views and urls for the app named 'Shop' the project overall is called 'My shop'. Whenever I try to type in the 'product list' url I am returned with the following error: Reverse for 'product_list_by_category' with arguments '(3, 'accessories')' not found. The expected result is the list.html page to be shown which includes all products because no category has been chosen in the URL. I have followed the code in the book exactly and have tried it multiple times yet the error still appears. I have two categories currently and two games, the games are Minecraft and GTA 5, the categories are Accessories and Games. Below is the code from all of the relevant files, if any more are needed let me know. Shop views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product # Create your views here. #Product List view def product_list(request, category_slug=None): #Setting current category to none category = None #Retrieiving categories categories = Category.objects.all() #Getting all unfiltered products that are available products = Product.objects.filter(available=True) #Filtering products based on category if category_slug: #Get category … -
How to create post request in DRF
I m working on this POST request in drf and I lost it somewhere please help. my models.py class TargetDefination(models.Model): targetName=models.CharField(max_length=50) displayName=models.CharField(max_length=100) def __str__(self): return self.targetName class Target(models.Model): targetDefn=models.ForeignKey(TargetDefination,on_delete=models.CASCADE) roleId=models.ForeignKey(Role,on_delete=models.CASCADE) empId=models.ForeignKey(Employee,on_delete=models.CASCADE) startDate= models.DateField(default=datetime.date.today) endDate= models.DateField(null=True,blank=True) value=models.PositiveIntegerField(default=0) def __str__(self): return str(self.empId) + ' ' +str(self.targetDefn) serializer.py class TargetSerializers(serializers.ModelSerializer): targetDefn=TargetDefinationSerializers() roleId=RoleSerializers() empId=OnlyEmployeeSerializers() class Meta: model = Target fields = ( 'id', 'targetDefn', 'roleId', 'empId', 'startDate', 'endDate', 'value' ) and this is what I have tried: views.py @api_view(['GET','POST']) def setTarget(request, *args, **kwargs): if request.method=='GET': setTrgt=Target.objects.all() serial=TargetSerializers(setTrgt,many=True) return JsonResponse(serial.data,safe=False) elif request.method == 'POST': data=JSONParser().parse(request) serial=TargetSerializers(data=data) if serial.is_valid(): print("working") target = serial.save() serializer = TargetSerializers(target) return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I need to create POST request and the formate will be: this is an example with just values in it. { "id": 6, "targetDefn": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" }, "roleId": { "id": 1, "roleName": "CEO", "description": "Chief executive officer", "roleReportsTo": null, "roleReportsToName": null }, "empId": { "id": 5, "empName": "Emp05", "startDate": "2021-05-04", "termDate": null }, "startDate": "2021-05-05", "endDate": null, "value": 123 } -
How do I append new data into a textField
I have a TextField on my page and I have multiple buttons representing different values, each time a button is clicked i want it to append the integer value and a ',' so that when multiple buttons are pressed it would create "1,2,3,4,5,6," but my current code only replaces the value and after multiple presses only "6," is displayed. <input type="text" id="cardRemove"> <button class="edit-Button" type="button" onclick="document.getElementById('cardRemove').setAttribute('value', value + '{{ forloop.revcounter }},')">append</button> the button is within a for loop that is how it retrieves each value, -
Docker behaves differently per server
Local environment: Arch linux Server a (digitalocean): Ubuntu latest Server b (digitalocean): Docker Ubuntu latest (one click app) My Django project which is running in a container can't run well only on the Server a. The error I get is "No module named main". I am using docker-compose. My project structure: web/ ├── Dockerfile ├── apps │ ├── __init__.py │ ├── api │ ├── seiko │ ├── tirami │ ├── users │ └── takao ├── main │ ├── __init__.py │ ├── asgi.py │ ├── celery.py │ ├── settings │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt The error seems directly related to Python but how could it be possible with Docker? I can't get overcome this issue. I checked every question asked on stackoverflow and contains similar error messages, but none of them helped. -
How should I upload a Django project to GitHub?
This is probably a very dumb question. But I have a little project in Django and I would like to upload it to GitHub to just have it there. I know how GitHub works and I know how to upload the project. But I'm wondering if just uploading the whole folder is the right way to do it. I mean. I have a data base with my project, that has some information. So is the database JUST in my computer right? It won't get uploaded next to the project to github? So basically I'm asking: Should I just simply upload the whole folder? And if I were to download my project from GitHub from another computer. Should I just have to run migrations to make it work locally? -
implement web push notification from my server to a third-party site through a javascript
i want to implement web push notification from my server to a third-party site through a javascript, I want to send notifications to the third-party website through a form on my website, I can already send notifications but only on my own website, I want to ask my customers to include a js on their website and I can send notifications for their website too, the project is in django. -
Django-channels permessage-deflate compression
I'd like to implement compression as the permessage-deflate rfc specifies in Django channels. Is there a way to add a middleware to achieve this? I've taken a look at a few different libraries like brotli-asgi, but that seems to only work for http protocol requests. -
What is the best way to integrate a react and django application?
I am making a full stack website using react and django. I came across various ways to integrate them both. Having them both as two separate projects and interacting using API, or putting react in the django folder and calling the backend. Which method would be better and much easier? And can you also mention the pros and cons of each method. -
IntegrityError a NOT NULL constraint failed : Submit a form through django
I'd like to make a POST REQUEST with an existing HTML FORM, to store it in a database, but everytime I tried to submit data through the form, it gives me the following error By the way I'm doing this following those post: Django form using HTML template MultiValueDictKeyError generated in Django after POST request on login page Registro.html {% extends "RegistrarProyecto/layout.html" %} {% block title %} {% endblock %} {% block content %} <h1>Crear Usuario</h1> <form class="CrearUsuario" action="{% url 'registro' %}" method="POST"> {% csrf_token %} <input type="text",name="NombreProyecto", placeholder="Nombre del Proyecto" > <br> <br> <input type ="text", name="ResponsableProyecto", placeholder ="Responsable del proyecto"> <br> <br> <textarea name="DescripcionProyecto", rows="4", cols="50"></textarea> <br> <br> <input type="submit" value="Registrar"> </form> <br> <a href="{% url 'index' %}">Ir a Bienvenido</a> {% endblock %} views.py def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto,ResponsableProyecto=ResponsableProyecto,DescripcionProyecto=DescripcionProyecto) return redirect("RegistrarProyecto/index.html") return render(request, 'RegistrarProyecto/Registro.html') models.py from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" class Evaluador(models.Model): NombreEvaluador = models.CharField(max_length=64) Proyecto = models.ManyToManyField(Proyecto, blank=True, related_name="Evaluador") def __str__(self): return f"{self.NombreEvaluador} {self.Proyecto}" urls.py from django.urls import path from . import … -
Celery how to create a task group in a for loop
I need to create a celery group task where I want to wait for until it has finished, but the docs are not clear to me how to achieve this: this is my current state: def import_media(request): keys = [] for obj in s3_resource.Bucket(env.str('S3_BUCKET')).objects.all(): if obj.key.endswith(('.m4v', '.mp4', '.m4a', '.mp3')): keys.append(obj.key) for key in keys: url = s3_client.generate_presigned_url( ClientMethod='get_object', Params={'Bucket': env.str('S3_BUCKET'), 'Key': key}, ExpiresIn=86400, ) if not Files.objects.filter(descriptor=strip_descriptor_url_scheme(url)).exists(): extract_descriptor.apply_async(kwargs={"descriptor": str(url)}) return None Now I need to create a new task inside the group for every URL I have, how can I do that? Thanks in advance -
django djongo DatabaseError
// serializers.py class PizzaSerializer(ModelSerializer): size_pizza = PizzaSizeSerializer(many=False) topping_pizza = PizzaToppingSerializer(many=False) class Meta: model = Pizza fields = ( 'name', 'type_pizza', 'size_pizza', 'topping_pizza', 'description' ) def get_size_pizza(self, obj): return obj.size_pizza.name def get_topping_pizza(self, obj): return obj.topping_pizza.name def create(self, validated_data): size_pizza = validated_data.pop('size_pizza') topping_pizza = validated_data.pop('topping_pizza') if size_pizza is not None: size_pizza_obj = PizzaSize.objects.get(**size_pizza) else: size_pizza_obj = PizzaSize.objects.first() if topping_pizza is not None: topping_pizza_obj = PizzaTopping.objects.get(**topping_pizza) else: topping_pizza_obj = PizzaTopping.objects.first() pizza = Pizza.objects.create( size_pizza=size_pizza_obj, topping_pizza=topping_pizza_obj, **validated_data ) pizza.save() return pizza // models.py class Pizza(models.Model): name = models.CharField(max_length=250, blank=False, null=False) PIZZA_TYPE = ( ('regular', 'REGULAR'), ('square', 'SQUARE'), ('pie', 'PIE'), ) type_pizza = models.CharField( max_length=20, choices=PIZZA_TYPE, default='regular', verbose_name='Type Of Pizza' ) size_pizza = models.OneToOneField( PizzaSize, related_name='pizza', verbose_name='Size Of Pizza', on_delete=models.CASCADE ) topping_pizza = models.OneToOneField( PizzaTopping, related_name='pizza', verbose_name='Topping For Pizza', on_delete=models.CASCADE ) description = models.TextField(blank=True, null=True) objects = models.DjongoManager() class Meta: verbose_name = "Pizza" verbose_name_plural = "Pizzas" def __str__(self): return str(self.name) // views.py class CreatePizzaView(CreateAPIView): serializer_class = PizzaSerializer // error File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 75, in _execute_with_wrappers return executor(sql, params, many, context) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 84, in _execute return self.cursor.execute(sql, params) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/utils.py, line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 84, in _execute return self.cursor.execute(sql, params) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute raise … -
Django i18n using translation.activate
I have configured Django i18n and it works just fine if you change the browser language using the browser configuration UI. I have tested both English and Spanish. However, when I try to let the user pick the language from the navigation bar and set a new LANGUAGE_SESSION_KEY based on the selection made by the user it would not work. The browser language will continue to be the selected language instead. Here follows my code: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... LANGUAGE_CODE = 'en' LANGUAGE_SESSION_KEY = 'en' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('en', _('English')), ('es', _('Spanish')), ('pt', _('Portuguese')) ) The view that is triggered by the navbar: def setLanguage(request, language_code): language = get_language() try: request.session[LANGUAGE_SESSION_KEY] = language_code translation.activate(language_code) request.LANGUAGE_CODE = translation.get_language() request.session[translation.LANGUAGE_SESSION_KEY] = language_code request.session.save() except Exception as e: print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Oops!", e.__class__, "occurred.") translation.activate(language) return redirect('home_index') I have debugged that the language_code passed corresponds correctly to the selected language (e.g. es instead of en) but it is not activated. The browser language remains as the active language. I would appreciate any ideas. Thanks! Alberto -
How I render content page to another html page
I have already base.html page. How I can get my specific contact page information into my home page with jinja -
Is it possible to check if a function has a decorator from a class attribute in DRF and Django?
I'm currently thinking of how to implement permissions in my Django application using DRF. My idea is to have several generic classes that inherit BasePermission and to define those classes in the view, ex: class ExampleView(ModelViewSet): permission_classes = (ExamplePermissionClass,) However, this might not suffice for some views that I have i.e. I might declare a generic class on the whole view but I might also want one @action to use different permissions. For this, I though of making decorator permissions which would check permissions on a per method basis. However, I do think that permission_classes are executed first and this won't work. Is there a way arround this? Example: class ExampleView(ModelViewSet): permission_classes = (ExamplePermissionClass,) @permissions(PermissionName etc...) @action(...) def example_action How can I circumvent the permission class and only check the decorator here? -
Use an existing HTML Template Form and submit data through Django
I'd like to make a POST REQUEST with an existing HTML FORM, to store it in a database, but everytime I tried to submit data through the form, it doesn't do nothing. it doesn't add data to the database. What should I do? By the way I'm doing this following those post: Django form using HTML template MultiValueDictKeyError generated in Django after POST request on login page Registro.html {% extends "RegistrarProyecto/layout.html" %} {% block title %} {% endblock %} {% block content %} <h1>Crear Usuario</h1> <form class="CrearUsuario" action="{% url 'registro' %}" method="POST"> {% csrf_token %} <input type="text",name="NombreProyecto", placeholder="Nombre del Proyecto" > <br> <br> <input type ="text", name="ResponsableProyecto", placeholder ="Responsable del proyecto"> <br> <br> <textarea name="DescripcionProyecto", rows="4", cols="50"></textarea> <br> <br> <input type="submit" value="Registrar"> </form> <br> <a href="{% url 'index' %}">Ir a Bienvenido</a> {% endblock %} views.py def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') NombreProyecto = request.POST.get('ResponsableProyecto') NombreProyecto = request.POST.get('DescripcionProyecto') return render(request, 'RegistrarProyecto/Registro.html') else: return render(request, 'RegistrarProyecto/Registro.html') models.py from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" class Evaluador(models.Model): NombreEvaluador = models.CharField(max_length=64) Proyecto = models.ManyToManyField(Proyecto, blank=True, related_name="Evaluador") def __str__(self): return … -
How to connect jupyter-lab in my Django project to the Django's models?
I am a bit new to Django and was wondering on how to do this. I have a jupyter-lab called forecasting.ipynb in the same folder as my manage.py and db.sqlite3. I want to connect to the db.sqlite3 to access the models that are in my models.py. I have a model called Coin. I want to basically be able to do Coin.objects.all() and access all my coins but I'm a bit confused on how to do this. In my jupyter-lab file I have this: forecasting.ipynb import sqlite3 connection = sqlite3.connect('db.sqlite3') for row in cur.execute('SELECT * FROM Coin;'): print(row) connection.close() I tried this but it says 'OperationalError: no such table: Coin'. I also tried both coin and COIN as well but both didn't work. I'm really confused because I have a model called Coin in my models.py. models.py from django.db import models class Coin(models.Model): ticker = models.CharField(primary_key=True,max_length=10, unique=True) baseVolume = models.BigIntegerField(default=0) coin_name = models.CharField(default="", max_length=50) coin_description = models.TextField(default="") # price = models.FloatField() def __str__(self): return "{}-{}".format(self.ticker,self.baseVolume) And when I do Coin.objects.all() in my tasks.py, it works perfectly. Is my syntax/code wrong or am I misinterpreting something? Thank you so much! -
Django: Corresponding values to String options
Let's say, I have a hotel booking form and I want to have 'room types' with different prices. Then after selecting a room type, I add its corresponding price to the Total Price. So my questions are: How do I make such option list with corresponding prices, where I can use the price and add it to the total? (maybe through javascript). Right now, I have the models & forms set up, and the javascript code for adding the other option (one being an input field for no. of nights, and another being a checkbox for including breakfast). I was thinking of using a list of tuples, but I don't particularly know how to implement it. -
Populate Django database(SQL)
I am learning Django, a little difficult for me, so i have some problem with Fields M2M, OTO, FK and i'm stuck, I'm trying to fill in the database(SQL), everything seems to work, but there is an intermediate field authors = models.ManyToManyField(Author) book_authors this table is empty, read the documentation, didn't help :p models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField('date published') class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) admin.py from django.contrib import admin from annotate_aggregate.models import Author, Publisher, Store, Book admin.site.register(Author) admin.site.register(Publisher) admin.site.register(Book) admin.site.register(Store) management/commands/seed.py class Command(BaseCommand): def handle(self, *args, **options): User.objects.filter(~Q(is_superuser=True) | ~Q(is_staff=True)).delete() Publisher.objects.all().delete() Book.objects.all().delete() Store.objects.all().delete() authors = [Author(name=fake.name(), age=random.randint(20, 70)) for _ in range(1, 6)] Author.objects.bulk_create(authors) # create 5 publishers publishers = [Publisher(name=fake.company()) for _ in range(1, 6)] Publisher.objects.bulk_create(publishers) # create 20 books for every publishers books = [] counter = 0 for publisher in Publisher.objects.all(): for i in range(20): counter = counter + 1 books.append( Book( name=fake.sentence(), price=random.uniform(29.99, 225.9), pages=random.randint(50, 300), rating=round(random.uniform(1, 5), 2), pubdate=timezone.now(), publisher=publisher) ) Book.objects.bulk_create(books) # create … -
django-haystack relevants suggestions
I'm using Django-haystack + Elasticsearch. I have INCLUDE_SPELLING set to True and {{ suggestion }} tag in my template. When for example I search for émile zola I get émile zozo (which doesn't exist in the index or db) as suggestion instead of emile zola. Anyway to fix this? Thanks -
Google Cloud Video Intelligence Annotate Video JSON vs example code
Google Cloud Video Intelligence provides the following code for parsing annotation results with object tracking: features = [videointelligence.Feature.OBJECT_TRACKING] context = videointelligence.VideoContext(segments=None) request = videointelligence.AnnotateVideoRequest(input_uri=gs_video_path, features=features, video_context=context, output_uri=output_uri) operation = video_client.annotate_video(request) result = operation.result(timeout=3600) object_annotations = result.annotation_results[0].object_annotations for object_annotation in object_annotations: print('Entity description: {}'.format(object_annotation.entity.description)) print('Segment: {}s to {}s'.format( object_annotation.segment.start_time_offset.total_seconds(), object_annotation.segment.end_time_offset.total_seconds())) print('Confidence: {}'.format(object_annotation.confidence)) # Here we print only the bounding box of the first frame_annotation in the segment frame_annotation = object_annotation.frames[0] box = frame_annotation.normalized_bounding_box timestamp = frame_annotation.time_offset.total_seconds() timestamp_end = object_annotation.segment.end_time_offset.total_seconds() print('Time offset of the first frame_annotation: {}s'.format(timestamp)) print('Bounding box position:') print('\tleft : {}'.format(box.left)) print('\ttop : {}'.format(box.top)) print('\tright : {}'.format(box.right)) print('\tbottom: {}'.format(box.bottom)) print('\n') However, I want to parse the json file that is generated via output_uri. The format of the json file is as following : { "annotation_results": [ { "input_uri": "/production.supereye.co.uk/video/54V5x8q0CRU/videofile.mp4", "segment": { "start_time_offset": { }, "end_time_offset": { "seconds": 22, "nanos": 966666000 } }, "object_annotations": [ { "entity": { "entity_id": "/m/01yrx", "description": "cat", "language_code": "en-US" }, "confidence": 0.91939145, "frames": [ { "normalized_bounding_box": { "left": 0.17845993, "top": 0.44048917, "right": 0.5315634, "bottom": 0.7752136 }, "time_offset": { } }, { How can I use the example code to parse the JSON that is provided with output_uri ? What kind of conversion is needed for this … -
Identify updated field in update or create django
How do I detect which data has been updated and which has been created in a MyModel.objects.update_or_create() method? try: new_data = MyModel.objects.update_or_create( data_1 = active_sheet["{}{}".format("A", row)].value, data_2 = active_sheet["{}{}".format("B", row)].value, ) # default url url = reverse('admin:index') + 'some-url/' # if some users were only updated, not uploaded # pass the updated data to custom template # return the current page with a table of the entries that were not added self.message_user(request, 'Tagged Profile uploaded.') # redirect to selected url return HttpResponseRedirect(url) except Exception as e: messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e)