Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django pagination very slow because of count how i can pass objects count
django pagination very slow because of count it is any way make me pass the number of object -
Passing instance method result to class attribute
Let's say I have two models, the first referencing a third User model: class Parent(models.Model): user = models.ForeignKey(User) ... class Child(models.Model): parent = models.ForeignKey( Parent, limit_choices_to={'user': get_user()} ) def get_user(self): return self.request.user I want to limit choices for the child model to instances bound to current user. One way to do it would be to pass the request to the form class and solve it inside __init__, but it present's other limitations. Is there a way to do this inside the model class, kind of like in the example above? -
supervisor: couldn't exec /home/clouditech/bin/gunicorn_start: ENOEXEC: supervisor: child process was not spawned
I continuously get this error message when trying to deploy my Django app with Nginx and Gunicorn. I've almost read and implemented all suggestions about this issue on ST.Overflow I've already implemented the following. 1. Ensured there is a shebang: #!/bin/bash 2. Put sh in front of command in /etc/supervisor/conf.d/clouditech.conf Please find my configuration files /etc/supervisor/conf.d/clouditech.conf [program:clouditech] command =sh /home/clouditech/bin/gunicorn_start user=clouditech autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/clouditech/logs/gunicorn-error.log gunicorn_start file /home/clouditech/bin/gunicorn_start #!/bin/bash NAME="core" DIR=/home/clouditech/clouditech USER=clouditech GROUP=clouditech WORKERS=3 BIND=unix:/home/clouditech/run/gunicorn.sock DJANGO_SETTINGS_MODULE=core.settings DJANGO_WSGI_MODULE=core.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- -
Is there a Bootstrap option for a list in django that you can click?
I built a app for my employer in PowerApps and now learned to code so attempting to recreate my program in Django/Python. Is there a bootstrap option or another way to create a similar gallery in django like there is in PowerApps? I want to be able to display a phone list from a db then when you click the name of the contact it opens and shows phone number,email,details,ect about the contact. -
Please how can i fix this?
No default language could be detected for this app. Hello, I have a problem on my git hoping you can help me this is an error (No default language could be detected for this app.) And I have no idea how to handle this problem. I did it all on the internet, but nothing clear. Thanking you, can you orient me please? LITTLE NOTE the procfile file and the requirements file had some sort of? on it and were not which clickable. So I transformed them into a textmate file by going through: right click, Override File type puire Textmate. Besides, are File text and File textmate really different? Windows 10 64bit -
django not rendering template in html but as ordinariny textfile on browser
all my codes are working correctly but showing as text on browser. they are not rendering as an html page here is what my views is like @login_required def product_list(request, template_name='product/product_list.html'): ppix = Profilepix.objects.filter(user=request.user) product = Product.objects.filter(username=request.user).order_by('-postdate') data = {} data['object_list'] = product return render(request, template_name, data, {'Profilepix': ppix}) -
Django 'QuerySet' object has no attribute '_deferred_filter'
Just upgrading from Django 2.2 to 3.2 and encountered this error: 'QuerySet' object has no attribute '_deferred_filter' From stacktrace: File "/Users/jlin/projects/mp2/ext_db/models.py", line 434, in get_queryset return super(SOActiveManager, self).get_queryset().exclude( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 949, in exclude return self._filter_or_exclude(True, args, kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 966, in _filter_or_exclude_inplace self._query.add_q(~Q(*args, **kwargs)) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q child_clause, needed_inner = self.build_filter( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1295, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1087, in resolve_lookup_value value = value.resolve_expression( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 1365, in resolve_expression query = self.query.resolve_expression(*args, **kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 196, in query if self._deferred_filter: AttributeError: 'QuerySet' object has no attribute '_deferred_filter' And this is the code that raised the error class SOActiveManager(models.Manager): def get_queryset(self): return super(SOActiveManager, self).get_queryset().exclude( status__in=SOStatuses.closed_statuses() ) called by sos = ServiceOrders.active.filter(account__number=customer_id).count() -
'null' and 'None' has been automatically added to my product dictionary
I am working on a Django project where I have coded a logic for customer to add products in their cart(product id as key and quantity as value). But whenever customer adds a product to cart, sometimes 'null' or sometimes 'None'is being add as a key to the cart. Here is the code how I add products to cart when server gets request to add product; Cart = request.get(product) If cart: cart[product] =+1 else: cart ={} cart[product] = 1 request.session['cart']=cart How can I delete those two keys from cart? I am new here pardon my mistakes -
Model class xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm trying to integrate scrapy with django. I'm new to django and I can't figure out what I have done wrong. I have read previous questions but none of the answers seem to solve my problem. I keep getting this error raise RuntimeError( RuntimeError: Model class emails.models.Email doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. email_spider.py from scrapyy.items import EmailItem class firstSpider(scrapy.Spider): name = "emails" ... def parse(self, response): ... item = EmailItem() item['email'] = text_list2 ... process = CrawlerProcess() process.crawl(firstSpider) process.start() item.py import scrapy from scrapy_djangoitem import DjangoItem from emails.models import Email class EmailItem(DjangoItem): django_model = Email INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scrapyy', 'emails', ] emails/models.py from django.db import models # Create your models here. class Email(models.Model): email = models.CharField(max_length=100) here is the structure of my project -
Does Django need more resources of a server than Laravel? If the both are the same kind of application
Suppose I want to build a social Media Platform Website and App with API. Then which will be less resource-hungry between Django and Laravel ? Which framework can perform faster for the application in a same config server? and why ? Thanks in Advance -
Django not checking paths in DIRS for files
I have a folder outside my templates file which I want to render I tried this: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'projects')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] It doesn't work I want to render it like this: return render(request, f"{username}/{name}/index.html") Please help! Happy Coding! -
Django search bar and capital letters
Hello i am making Django app and I have a question. I have made a search bar. Everything would work correctly as I want but the problem is when the Item has capital letter or vice versa, quering does not work as I would like to. I wanted to make it search for the item when it is written 'tea' or 'TEA' or 'TeA'. I hope you understand me. :) Code: views.py def searchView(request): if request.method == "GET": context = request.GET.get('search') items = Item.objects.all().filter(title__contains=context) urls.py: urlpatterns = [ path('', ShopListView.as_view(), name='home-page'), path('signup', views.signup, name='signup-page'), path('login', views.loginView, name='login-page'), path('logout', views.logoutView, name='logout-page'), path('detail/<int:pk>/', ShopDetailView.as_view(), name='detail-page'), path('search/', views.searchView, name='search-page') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I think here is an issue in quering 'items'. If you want me to paste more code, just write it. -
How can I make a receiver listen to a user-specific signal in Django?
I'm writing a Django blog site where blog posts need to be approved by an admin (superuser) before they can be posted. In my BlogPost model, there is a Boolean field "approved". I've managed to implement all of this. However, I also want the user to be notified (via a django message) when their post is approved. (The user can go and do whatever else they want in the interim, before the admin gets around to approving their post, and so the message must appear on whatever page the user is currently on. Furthermore, if the user has multiple pages open at the same time (say, on different tabs), the message should appear on all of them.) This is what I am having some issues with implementing. I've drafted a small code snippet which encapsulates what I want to do. @receiver(post_save, sender=BlogPost) def message_on_approve(sender, instance, **kwargs): if instance.user != (the current user who is logged in): return if instance.approved: messages.success((request, to be sent to the page user is currently on), 'Your post has been approved!') else: messages.error((the same request), 'Your post has not been approved.') There are two issues that I am facing now. Firstly, due to the fact that … -
xlsxwriter to http response (download file) but with user data (forms) in django
I'm stuck, I want to user on page create template to input data on based witch will be created a template. Here is what I got so far, but it wont work, I have tried with examples online, but those are usually don't take a data from users to create template. This is views.py from django.http import HttpResponse from django.shortcuts import render import xlsxwriter from xlsxwriter import workbook from django.forms import Form, CharField, ChoiceField, IntegerField from django.core.validators import MaxValueValidator, MinValueValidator def home(request): return render(request, 'my_app/home.html') def create_template(request): return render(request, 'my_app/create_template.html') class TemplateForm(Form): doc_name = CharField(label='Document name') sheetnames = CharField(label='Sheetnames') choices = [] for year in range (1900, 2050): choices.append( (year, year) ) year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices) year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices) row_names = CharField(label='Column names') def create_template(request): if request.method == 'GET': form = TemplateForm() return render(request, 'my_app/create_template.html', {'form':form}) else: form = TemplateForm(request.POST) def create_form(doc_name, sheetnames, years, row_names): workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx') worksheet_introduction = workbook.add_worksheet( "introduction" ) for i in sheetnames: worksheet_data = workbook.add_worksheet(i) worksheet_data.write_row(0, 1, years) worksheet_data.write_column(1, 0, row_names) workbook.close() return workbook This is my_app/templates/my_app/create_template.html {% extends "my_app/base.html" %} {% block content %} <form action="create_template" method="GET"> {% csrf_token %} <h1>Create your template</h1> <div class="item"> <table> {{ … -
Error 400 on appengine ping, by python requests
Hello beautiful people! I have a Django server deployed to google AppEngine. I am trying to send a json request with python to a views.py function that looks like this: def my_test_json_data(request): json_data = (json.loads(request.body.decode('utf-8'))) #print(json_data) if json_data['apikey'] != 'YOUR_API_KEY_HERE': return HttpResponseNotFound('not today') data = {'test':'ok'} return JsonResponse(data) and the python code looks like this: import requests data = {'test1':'1'} url = 'https://fliby.eu/my_test_json_data/' headers = {'Content-Type':'application/json',} payload = {'json_payload': data, 'apikey': 'YOUR_API_KEY_HERE'} session = requests.Session() r = session.get(url,headers=headers, json=payload) print(r.status_code) When the server is hosted locally there is no problem and everything works correctly! (code 200) When I try to requst trough appengine it returns code 400 Can I get some hints please, Thank you! -
An error NoReverseMatch appears when I try to edit a post using UpdateView in Django
When I click on the update post link, an error appears: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P[-a-zA-Z0-9_]+)$']. My Post model looks like this: class Post(models.Model): title = models.CharField(max_length=200, verbose_name='Заголовок') slug = AutoSlugField(populate_from=['title']) title_image = models.ImageField(upload_to=user_img_directory_path, blank=True, verbose_name='Изображение') description = models.TextField(max_length=500, verbose_name='Описание') body = FroalaField(options={ 'attribution': False, }, verbose_name='Текст') post_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации', db_index=True) post_update_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата обновления публикации') post_status = models.BooleanField(default=True, verbose_name='Опубликовано') class Meta: ordering = ['-post_date'] def get_absolute_url(self): return reverse('articles:post_detail', kwargs={'slug': self.slug}) def __str__(self): return self.title My DetailView and UpdateView classes in views.py: from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView class PostDetail(DetailView): model = Post template_name = 'articles/post_detail.html' context_object_name = 'post' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class UpdatePost(UpdateView): model = Post template_name = 'articles/update_post.html' fields = ['title', 'title_image', 'description', 'body'] My urls.py file: from .views import PostsList, PostDetail, CreatePost, UpdatePost app_name = 'articles' urlpatterns = [ path('', PostsList.as_view(), name='posts_list'), path('post/<slug:slug>', PostDetail.as_view(), name='post_detail'), path('create/', CreatePost.as_view(), name='create_post'), path('post/edit/<slug:slug>', UpdatePost.as_view(), name='update_post'), ] update_post.html template looks like this: {% extends 'layout/basic.html' %} {% load static %} {% load django_bootstrap5 %} {% block content %} <form method="post" class="form"> {% csrf_token %} {{ form.media }} {% bootstrap_form form %} {% bootstrap_button button_type="submit" … -
How do I implement Google Sign-In, keep getting Forbidden CSRF Error
I'm building a simple Login page using Python and Django. I want to give the users the choice to login using either the Django account or Google Sign-In. I've build some simple HTML and functions to flow between 4 pages: Main, login_success,logout_success and already_logged_in As far as I've understand, I've set up at the very least a button on my login page, with some relevant scripts. So, then I deploy to my Google Cloud, access the site, see the button and click on it and it redirects me to a Google Sign-In page where I can choose my account. I click on the account and I get a Forbidden: CSRF Error. Am I missing something? I am not sure how to debug this. This is my Main login HTML.(I'm not sure if the rest are needed to be shown?) {% load i18n %} {% block content %} <!DOCTYPE html> <html> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" media="all" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script> <head> <title>Google Signin Testing</title> <style> .left { float: left; width: 40%; padding-left:32%; padding-top:13%; height: 75% } .right { float: left; width: 40%; padding-top:5%; height: 100% … -
Can I detect ManyToManyField mutations before they are applied?
I have a Django app that broadcasts changes of some of its models to its clients, to keep them up-to-date. I have a separate app for that, that binds to the post_save signal of these models and triggers the broadcast. Problems have come with models with ManyToManyFields. I am not very familiar with Django's handling of this but I understand that these fields are actually updated after the model is saved. I was able to use the m2m_changed signal to react to the post_* actions and dispatch the broadcast after the object is all up-to-date. However, in the post_save handler, I still need to detect that the m2m field is going to be mutated, to avoid broadcasting incomplete data. How can I detect this , either in the post_save signal handler or the model's save method ? Is there a way to raise a flag on an object when a m2m field is about to be mutated ? Here's what I've tried : Handle the pre_* actions of the m2m_changed signal to detect incoming mutation of the field but that does not work, because the signal gets fired after post_save, which is too late (data has already been broadcasted). Store … -
Issue with mock return value in py test?
I have the following post function in my view and I want to mock the return values of customer.get_customer_data and customer.update_customer_data in my test function. However, it seems like only one of the mock return values is getting allocated. def post(self, request, *args, **kwargs): try: data = request.data status_code, response = customer.get_customer_data( data["customer_id"], "id," ) if status_code == 401: auth.generate_new_access_token("buyer") status_code, response = customer.get_customer_data( data["customer_id"], "id," ) if status_code == 401 or status_code == 200: id = response[0]["message"][0]["id"] status_code, response = customer.update_customer_data(id, data) tests.py @patch("app.views.customer.get_customer_data") @patch("app.views.customer.update_customer_data") def test_customer_view(self, mock_customer_data, mock_update_customer_data): customer_update_data = { .... } mock_customer_data.return_value = 200, [{"message": [{"id": 1234}]}] mock_update_customer_data.return_value = 200, 'Success' req = RequestFactory().post("/app/customer/create/", customer_update_data, content_type='application/json') resp = views.EditCustomerView.as_view()(req) resp.render() assert json.loads(resp.content) == "Success" assert mock_customer_data.called assert resp.status_code == 200 I am getting the following error when I run the test id = response[0]["message"][0]["id"] TypeError: string indices must be integers Seems like this one is getting called for the wrong function. It's getting patched with the get_customer_data function instead of update_customer_data What could I be doing wrong? -
Why does Django/console give me an error of missing value for stripe.confirmCardPayment intent secret, saying it should be a client secret string?
I'm trying to learn this tutorial, the custom payment flow last bit to integrate stripe with Django https://justdjango.com/blog/django-stripe-payments-tutorial in my views.py, I have these views class StripeIntentView(View): def post(self, request, *args, **kwargs): try: req_json = json.loads(request.body) customer = stripe.Customer.create(email=req_json['email']) price = Price.objects.get(id=self.kwargs["pk"]) intent = stripe.PaymentIntent.create( amount=price.price, currency='usd', customer=customer['id'], metadata={ "price_id": price.id } ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) except Exception as e: return JsonResponse({'error': str(e)}) class CustomPaymentView(TemplateView): template_name = "custom_payment.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") prices = Price.objects.filter(product=product) context = super(CustomPaymentView, self).get_context_data(**kwargs) context.update({ "product": product, "prices": prices, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY }) return context and in my urls I have from django.contrib import admin from django.urls import path from products.views import stripe_webhook from products.views import StripeIntentView, CustomPaymentView urlpatterns = [ path('admin/', admin.site.urls), path('create-payment-intent/<pk>/', StripeIntentView.as_view(), name='create-payment-intent'), path('custom-payment/', CustomPaymentView.as_view(), name='custom-payment') and in my custom_payment.html I have {% load static %} <!DOCTYPE html> <html> <head> <title>Custom payment</title> <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script> <script src="https://js.stripe.com/v3/"></script> <link rel="stylesheet" href="{% static 'products/global.css' %}"> </head> <body> <section> <div class="product"> <div class="description"> <h3>{{ product.name }}</h3> <hr /> <select id='prices'> {% for price in prices %} <option value="{{ price.id }}">${{ price.get_display_price }}</option> {% endfor %} </select> </div> <form id="payment-form">{% csrf_token %} <input type="text" id="email" placeholder="Email address" /> <div id="card-element"> <!--Stripe.js injects the … -
Django data from RichTextField renders with html tags
I have a website which in its one page it renders data from a specific object which has 1 integer, 1 string and 2 rich text values (ckeditor, RichTextField). The class is represented belov; class Chapter(models.Model): chapter_id = models.IntegerField(primary_key=True, default=None) chapter_title = models.CharField(max_length=100, default=None) chapter_text = RichTextField(default=None) chapter_footnotes = RichTextField(default=None, blank=True) When I try to render the data from RichTextFields it renders with the html elements as a text. Example: <p><span style="color:#757575"><span style="background-color:#ffffff">Why a sword?&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">There are so many different weapons in the world, so why did I choose the sword?&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">That&#39;s because swords represent perfection.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">A sword has two edges.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">One edge to hurt the enemy, one edge to protect me.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">It protects me by killing my enemies.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">That is the purpose of a sword.&nbsp;</span></span></p> <p><span style="color:#757575"><span style="background-color:#ffffff">And that is exactly how I use my chosen weapon, my sword.&nbsp;</span></span></p> How can I make it so that It renders itself without showing but applying its html element tags. Note: The code that renders the data: {% block chapters %} <div class="chapter_text"> <h1>{{ chapter_info.chapter_id }}: {{ chapter_info.chapter_title }}</h1><br> {{ chapter_info.chapter_text }} <hr> {{ chapter_info.chapter_footnotes }} </div> {% endblock chapters … -
Why I need to clear local storage manually from console. Every time my site load
I made a shopping cart and make update cart function in JavaScript that working fine but when I navigate to other page my cart no automatically turn to (1 ) and an error rise in console like this: Uncaught TypeError: Cannot set property 'innerHTML' of null at updateCart ((index):447) at (index):411 My java script code is: <script> // Find out the cart items from localStorage if (localStorage.getItem('cart') == null) { var cart = {}; } else { cart = JSON.parse(localStorage.getItem('cart')); document.getElementById('cart').innerHTML = Object.keys(cart).length; updateCart(cart); } // If the add to cart button is clicked, add/increment the item $('.cart').click(function() { var idstr = this.id.toString(); if (cart[idstr] != undefined) { cart[idstr] = cart[idstr] + 1; } else { cart[idstr] = 1; } updateCart(cart); }); //Add Popover to cart $('#popcart').popover(); updatePopover(cart); function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + " <h5>Cart for your items in my shopping cart</h5><div class='mx-2 my-2'>"; var i = 1; for (var item in cart){ popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0,19) + "... Qty: " + cart[item] + '<br>'; i = i+1; } popStr = popStr + "</div>" console.log(popStr); document.getElementById('popcart').setAttribute('data-content', popStr); … -
Why does Django/Postgres appear to save but doesn't, gives 'connection already closed'?
I'm using Django + Postgres on Windows 10 WSL Ubuntu 18.04.5 LTS. Saving data to postgres seems to work, yet when I access the table using psql on the command line, the data isn't there. Refreshing the webpage (reloading Django) also shows the old data previous to the save. There are no errors in the postgresql log. I don't have caching explicitly turned on in Django's settings.py. It all worked perfectly for years, but to be sure I upgraded Django to 3.2.6, Python to 3.8.11, postgresql to 12, and psycopg2 to 2.9.1, plus the necessary dependencies. Same result. Here's the code in Django: try: nodeToUpdate.save() # Hit the database. node = Node.objects.get(pk=itemID, ofmap=mapId) # Retrieve again to confirm it was saved # This shows the correct data: print("STORE TO MAP:" + str(node.ofmap_id) + " NODE:" + str(node.id) + " label:" + str(node.label)) except psycopg2.InterfaceError as err: print(str(err)) raise Exception(err) except ValidationError as err: raise Exception(err) The clue to what's going on comes when I run unit tests: Traceback (most recent call last): File "/var/www/mysite/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 237, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/var/www/mysite/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/var/www/mysite/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor cursor = self.connection.cursor() **psycopg2.InterfaceError: connection … -
how to make a data fetch form in django?
I want the user to have a form for fetching data from the database, for example, as in /admin: Form in admin So that the user can select multiple entries and, for example, delete them, how can I do this? -
Why doesn't this django url run on Mac?
I'd like to apply pose estimation Python code in url below to the Django view. But it works well on Windows, but not on Mac. 127.0.0:8000/pose_feed doesn't work without any error messages. I installed requirement.txt in venv, and Python version is 3.7 for both venv. https://www.analyticsvidhya.com/blog/2021/05/pose-estimation-using-opencv/ urls.py urlpatterns = [ path('pose_feed', views.pose_feed, name='pose_feed'), ] views.py def index(request): return render(request, 'streamapp/home.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def pose_feed(request): return StreamingHttpResponse(gen(PoseWebCam()), content_type='multipart/x-mixed-replace; boundary=frame') cameras.py class PoseWebCam(object): def __init__(self): # self.vs = VideoStream(src=0).start() self.cap = cv2.VideoCapture(0) # self.mpPose = mp.solutions.pose self.mpPose = mp.solutions.mediapipe.python.solutions.pose self.pose = self.mpPose.Pose() self.mpDraw = mp.solutions.mediapipe.python.solutions.drawing_utils self.pTime = 0 def __del__(self): cv2.destroyAllWindows() def get_frame(self): success, img = self.cap.read() imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = self.pose.process(imgRGB) if results.pose_landmarks: self.mpDraw.draw_landmarks(img, results.pose_landmarks, self.mpPose.POSE_CONNECTIONS) for id, lm in enumerate(results.pose_landmarks.landmark): h, w,c = img.shape cx, cy = int(lm.x*w), int(lm.y*h) cv2.circle(img, (cx, cy), 5, (255,0,0), cv2.FILLED) cTime = time.time() fps = 1/(cTime-self.pTime) self.pTime = cTime cv2.putText(img, str(int(fps)), (50,50), cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0), 3) # cv2.imshow("Image", img) # cv2.waitKey(1) frame_flip = cv2.flip(img,1) ret, jpeg = cv2.imencode('.jpg', frame_flip) return jpeg.tobytes() home.html <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <!-- <img src="{% url 'video_feed' %}"> --> <!-- <img src="{% …