Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Including the correct amount of White Space when printing a receipt
I'm writing a till system for a local coffee shop. I'm stuck on printing the itemized receipt. I don't know how many characters in width standard receipt paper is, or barring that how to nicely format the paper -- with items sold, item name, white space, total cost For example, 5 x Coffee 10.00 15 x Tea 10.00 Any tips on having the correct amount of white space? Or how many ASCII characters in width is standard receipt paper? Thanks in advance -
I want to make a changing "array" of color options and size options per item in the admin panel
Title and code. I'm working on an E-Commerce site where I will have multiple options per item (color/size). In the code you can see price, price(1-3), the idea is to create a button or option for the admin to add additional sizes and therefor prices without hard coding sizename(1-4) and the same goes for colorName(1-4). I hope that you can understand what I'm going for, I just started learning python and all of this bootstrap and django stuff yesterday. BTW If you know of an easier way to handle all of this, please do let me know, I'm lost as to how to make a shopping cart. I just started this class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(decimal_places=2, max_digits=20) stock = models.IntegerField() image_url = models.CharField(max_length=2083) category = models.CharField(choices=MY_CHOICES, max_length=25, default='Default') multSizes = models.BooleanField(default=False) numberSizes = models.IntegerField(default=1) price1 = models.DecimalField(decimal_places=2, max_digits=20, default=0) price2 = models.DecimalField(decimal_places=2, max_digits=20, default=0) price3 = models.DecimalField(decimal_places=2, max_digits=20, default=0) sizename1 = models.CharField(max_length=255, default='N/A') sizename2 = models.CharField(max_length=255, default='N/A') sizename3 = models.CharField(max_length=255, default='N/A') sizename4 = models.CharField(max_length=255, default='N/A') numberColors = models.IntegerField(default=1) colorName = models.CharField(max_length=255, default='N/A') colorName1 = models.CharField(max_length=255, default='N/A') colorName2 = models.CharField(max_length=255, default='N/A') colorName3 = models.CharField(max_length=255, default='N/A') colorName4 = models.CharField(max_length=255, default='N/A') I want to be able to change the amount … -
Django throwing ValueError: too many values to unpack (expected 2) with no change to the code
I have written a new function in a subfolder and my django project that was running fine is now throwing the following error: File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\urls.py", line 4, in <module> from .views import ( File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\views.py", line 15, in <module> from .forms import IndicatorForm, SearchForIndicatorMetaData File "C:\Users\me\PycharmProjects\IndicatorAnalyserWebapp\Analyser\Indicators\forms.py", line 24, in <module> class IndicatorForm(forms.ModelForm): File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 252, in __new__ opts.field_classes) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\forms\models.py", line 166, in fields_for_model formfield = f.formfield(**kwargs) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 1873, in formfield return super(IntegerField, self).formfield(**defaults) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 872, in formfield defaults['choices'] = self.get_choices(include_blank=include_blank) File "C:\Users\me\AppData\Local\Continuum\anaconda37\envs\py34\lib\site-packages\django\db\models\fields\__init__.py", line 802, in get_choices for choice, __ in choices: ValueError: too many values to unpack (expected 2) Similar questions have been asked in the past and it has always been that someone has used a dictionary rather than an iterable to define choices. I have not done this, but I am getting the same error. The traceback seems to think the issue is somewhere in my forms.py. My forms.py is below: from django import forms from .models import Indicator def get_indicator_ids(): ids = [] indicator_objects = Indicator.objects.all() for indicator in indicator_objects: ids.append(indicator.id) return ids class IndicatorDropDown(forms.Form): def __init__(self, *args, **kwargs): super(IndicatorDropDown, self).__init__(*args, **kwargs) self.fields['indicators'] = forms.ChoiceField(choices=get_indicator_ids()) class IndicatorForm(forms.ModelForm): class Meta: model = … -
Django - How to load paginated Page (next page) into my Template?
I have a model named "Person" (List of names). 6 Persons named "Anne". My Pagination is 2 per Page. When i start a search query on my page for "Anne". I get the Response of "6 Results", it shows me the first two Results and it displays "Page 1 of 3. Next. So far everything fine. but when i press "next" the Browser only updates to ..../post_searchtwo/?page=2 but the next two Results will not show up. (Using Django version 2.2.2 with PostgreSQL 11) thanks in advance. views.py def post_searchtwo(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Person.objects.annotate( search=SearchVector('city', 'last_name', 'first_name') ).filter(search=query) paginator = Paginator(results, 2) # --- Show 2 items per page page = request.GET.get('page') try: post_list = paginator.page(page) except PageNotAnInteger: post_list = paginator.page(1) except EmptyPage: post_list = paginator.page(paginator.num_pages) context = { 'form': form, 'query': query, 'page': page, 'post_list': post_list, 'results': results } return render(request,'search/post_searchtwo.html', context) my template / post_searchtwo.htnl {% extends 'base.html' %} {% load static %} {% block custom_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}"> {% endblock %} {% block content %} <form action="." method="get"> {{ form.as_p }} <input type="submit" … -
How to manage many tags in html?
I have written CSV file in HTML but the problem I am facing is that it has only one big column and I want to manage it in rows So that I don't have to scroll the page. Instead of managing it in HTML manually by giving rows to it, how could I write it in python with some lines of code and manage it in rows? import csv html_about = '' names = [] with open('filo.csv') as data_file: csv_data = csv.reader(data_file) for line in csv_data: names.append(f'{line[0]}') html_output = '\n<ul>' for name in names: html_output += f'\n\t<ul>{name}</ul>' html_output += '\n</ul>' print(html_output) import pandas as pd df = pd.read_csv('filo.csv') with open('table.html', 'w') as html_file: df.to_html(html_file,index=False) -
Local host page not found
Okay so I am a new learner and am following a tutorial https://www.youtube.com/watch?v=D6esTdOLXh4 My problem is that the last part of that video shows a posting site's posts when you click the linking to the post: Page not found (404) Request Method: GET Request URL: http://localhost:8000/posts/details/1%3E/ Using the URLconf defined in djangoproject1.urls, Django tried these URL patterns, in this order: [name='index'] details/<int:id>/ [name='details'] admin/ posts/ [name='index'] posts/ details/<int:id>/ [name='details'] The current path, posts/details/1>/, didn't match any of these. Here's the .py and .html files that I was editing that may be the best place to search for errors posts/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('details/<int:id>/', views.details, name='details') ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def index(request): # return HttpResponse('HELLO FROM POSTS') # allows post to be shown in posts connected to index.html/ posts = Posts.objects.all()[:10] context = { 'title': 'Latest Posts', 'posts': posts } return render(request, 'posts/index.html', context) def details(request, id): post = Posts.objects.get(id=id) context = { 'post': post } return render(request, 'posts/details.html', context) details.html {% extends 'posts/layout.html' %} {% block content %} <h3 class="center-align red lighten-3">{{post.title}}</h3> <div class="card"> … -
Django saving image from URL to model causes UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I have simple model with overrided save() method, I want to save image from given url, every time save mehod is called. Here is my code: def save(self, *args, **kwargs): super().save(*args, **kwargs) # Creating URL to request URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=" + settings.KEY URL += "&photoreference=" + self.reference result = urllib.request.urlretrieve(URL) self.image_file.save( os.path.basename(self.reference), File(open(result[0])) ) self.save() I found solution with addding: with open(path, 'rb') as f: contents = f.read() But i dont know where to place it, if i tried i got 'invalid syntax error' -
How can I fix Exception Value: 'module' object is not callable
My problem in this line: args.update(csrf(request)) My function in vews.py: def Login(request): args = {} args.update(csrf(request)) if request.POST: username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username = username, password = password) print(user, username, password) if user is not None: auth.login(request, user) return redirect('/') else: args['login_error'] = "Пользователь не найден" return render(request, 'HiPage/Login.html', args) else: return render(request, 'HiPage/Login.html', args) What is module here and why is it uncallable? (I made imports of csrf) File "C:\Users\Dmitry\Desktop\Shop-master\HiPage\views.py", line 51, in Login args.update(csrf(request)) TypeError: 'module' object is not callable -
Django extends tag makes JS charts not load
I am using a base.html file to create a navigation bar to all the child templates. The problem i'm facing is that this interferes with my JS charts (google charts) by not loading them anymore. Could anyone shine some light as to why this happens, and maybe a possible fix? base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block tab_menu %} <div class="topnav"> <a href="/index">Home</a> <a href="/index/devops">Devops</a> <a href="/index/qa">QA</a> <a href="/index/frontend">Frontend</a> <a href="/index/middleware">Middleware</a> <a href="/index/portal">Portal</a> < </div> {% endblock tab_menu %} </body> </html> child.html: <!DOCTYPE html> <html lang="en"> <head> {% extends "KPI/base.html" %} <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:["corechart"]}); google.charts.setOnLoadCallback(VelocityChart); function VelocityChart() { var data = google.visualization.arrayToDataTable([ ['Status', 'Number of Tasks'], ['Completed', {{completed_velocity}}], ['Incompleted', {{incomplete_velocity}}], ]); var options = { title: '', is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('velocity_chart')); chart.draw(data, options); } </script> </head> <body> {% block tab_menu %} {{ block.super }} <h2> QA Dashboard</h2> <div id="velocity_chart"></div> {% endblock tab_menu %} </body> </html> The code in the base.html file works fine on the other templates, but won't load the charts in the child templates. -
Objects in django setUp don't exist when running test
I have the following django view: @api_view(['GET']) @csrf_exempt def last_status_by_department_view(request, department_id=0): if request.META.get('HTTP_AUTHORIZATION') is None: return JsonResponse({'exception_message': 'No authorization provided.'}, status=401) try: return JsonResponse(last_status_by_department(department_id), safe=False) except Exception as e: return JsonResponse({'exception_message': str(e), 'full_traceback': traceback.format_exc()}, status=400) Which uses this function: from tokitimer.models import Activity def last_status_by_department(department_id): all_activities = Activity.objects.order_by('user__user_name', '-activity_datetime').distinct( 'user__user_name').exclude(bucket__bucket_name='Offline').filter( bucket__category__department_id=department_id) rts = [] for activity in all_activities: rts.append( { 'user_id': activity.user.user_id, 'user_name': activity.user.user_name, 'activity_datetime': activity.activity_datetime, 'bucket_id': activity.bucket.bucket_id, 'bucket_name': activity.bucket.bucket_name, 'category_id': activity.bucket.category.category_id, 'category_name': activity.bucket.category.category_name } ) return rts And I made the following test for it: class RealTimeStatusTests(TestCase): def setUp(self): self.user, self.master_account, self.category, self.bucket, self.activity, self.department, \ self.department_history = general_set_up2() self.tokens = json.loads(self.client.post(reverse('authenticate'), data={'username': self.user.user_name, 'password': 'abcd'}, content_type='application/json').content) def test_get_real_time_status(self): response = self.client.get(reverse('real_time_status_department', kwargs={'department_id': self.department.department_id}), follow=True, **{'HTTP_AUTHORIZATION': self.tokens['access']}) expected_response = [{ 'user_id': self.user.user_id, 'user_name': self.user.user_name, 'activity_datetime': self.activity.activity_datetime, 'bucket_id': self.bucket.bucket_id, 'bucket_name': self.bucket.bucket_name, 'category_id': self.category.category_id, 'category_name': self.category.category_name }] print(self.department.department_id) print(str(response.content, encoding='utf8')) print(expected_response) self.assertJSONEqual(str(response.content, encoding='utf8'), expected_response) The view basically provides the latest activity for all users. When i run this locally, the view returns the correct results. When running the tests, the objects "are created" because i have tests for all of them, but for this particular view, the return is an empty list instead of the activity created in the setUp. Am … -
Django OperationalError: SSL SYSCALL error: EOF detected
I'm running application that is using Django 1.10 as an ORM connecting to a Postgres DB (managed by AWS RDS). At time to time, I'm getting a lot of OperationalError: SSL SYSCALL error: EOF detected exceptions, and then everything goes back to normal like it never happened. I think its related to the error unexpected EOF on client connection with an open transaction as i see it in the log files, but i'm not sure. More useful information: This is not a firewall problem, as we use only AWS security groups which can only block things based on the port. The queries getting this exceptions are very simple, which usually takes milliseconds to return. Memory, cpu and disk space looking as usual during this episodes. I suspect that this is not a table locking problem, because everything goes back to normal after it happens, I cant say that for sure because Postgres is not displaying old locks, only current ones in realtime. We see a lot of idle connections in the DB. can it be related? -
Downloading PDF files using AJAX and POST
Hello guys I’m trying to make a web application with django to download pdf files. It seems to work fine if I use http://localhost/download, when I make these request it’s a GET request, I wonder if it’s possible to download a file but using AJAX and POST. I need to use post because there is an AJAX request and that view process some data before to download the file, or maybe I have to use necessarily an independent url just to download files and using the GET method. Is it possible? I have tried but the browser does not download the file if I set: If request.method = “POST” Thank you guys! -
Make Userprofile and make the user view its profile information
How to make the user view its profile information, after logging, even if another user is logged in in a different browser,and suggestion -
Tablesorter AJAX pagination. How to properly interact wiith a backend JSON?
Trying to make some of my tables work with Ajax pagination Actually created a clean empty template with just one table. Just for testing. {% extends 'base.html' %} {% load static %} {% block title %} TEST Skaters averages - NHL stats tracker {% endblock title %} {% block styles %} <link rel="stylesheet" href="{% static 'players/tablesorter.css' %}"> {% endblock styles %} {% block content %} <!-- SKATERS --> <table class="tablesorter"> <thead> <tr class="tablesorter-ignoreRow"> <td class="pager" colspan="5"> <button type="button" class="btn first"><i class="small material-icons">first_page</i></button> <button type="button" class="btn prev"><i class="small material-icons">navigate_before</i></button> <span class="pagedisplay"></span> <button type="button" class="btn next"><i class="small material-icons white">navigate_next</i></button> <button type="button" class="btn last"><i class="small material-icons">last_page</i></button> <select class="pagesize"> <option value="25">25</option> </select> </td> </tr> <tr> <th>1</th> <th>2</th> <th>3</th> </thead> <tbody> </tbody> </table> {% endblock content %} {% block scripts %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.js"></script> <!-- Widgets --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/jquery.tablesorter.widgets.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.1/js/extras/jquery.tablesorter.pager.min.js"></script> <script src="{% static 'players/sorting_averages.js' %}"></script> {% endblock scripts %} sorting_averages.js $("table") .tablesorter({ }); .tablesorterPager({ container: $(".pager"), ajaxUrl: 'http://127.0.0.1:8000/skaters_averages_json/{page}', }); In players.views I'm making slices with JSON data for every page. def skaters_averages_json(request, page): start = utils.PAGE_SIZE_2*(page - 1) end = start + utils.PAGE_SIZE_2 skaters = Skater.objects.select_related('team') one_page_slice = skaters.order_by('-points', 'games', '-goals')[start:end] skaters_json = json.loads(serializers.serialize('json', one_page_slice)) data = {} data["total_rows"] = utils.PAGE_SIZE_2 data["headers"] = ["ID", "Name", … -
Annotating 2 different model in Django to calcualte conversion rate
I have 2 models, pageview and transaction, my goal is to calculate the conversion rate using this formula = ( total transaction / total pageview ) * 100% . This is my models structure. class Transaction(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, null=True ) transaction_id = models.CharField(max_length=64, null=True, blank=True) datetime = models.DateTimeField(null=True) products = models.ManyToManyField("Product") . . . class PageView(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) organization = models.ForeignKey( "Organization", on_delete=models.CASCADE, null=True ) datetime = models.DateTimeField(null=True) url = models.CharField(max_length=2048, blank=True) page_name = models.ForeignKey( "PageName", on_delete=models.SET_NULL, null=True, blank=True ) products = models.ManyToManyField("Product", blank=True) . . . I have tried using some of this method: User.objects.filter(pageview__datetime__range=(startdate,enddate)).annotate( y=ExtractYear('pageview__datetime'), m=ExtractMonth('pageview__datetime'), d=ExtractDay('pageview__datetime')).values( 'y', 'm', 'd').order_by( 'y', 'm', 'd').annotate( total=(Cast(Count('conversion__id'), FloatField()) / Cast(Count('pageview__id'), FloatField())) * 100, pv=Count('pageview__id', distinct=True), cv=Count('conversion__id', distinct=True)) the result is . . . { "y": 2019, "m": 4, "d": 3, "total": 87.9093198992443, "pv": 397, "cv": 349 } . . . the problem is, total number of transaction when I check using this query is different Transaction.objects.filter( pageview__datetime__range=(startdate,enddate)).annotate( y=ExtractYear('pageview__datetime'), m=ExtractMonth('pageview__datetime'), d=ExtractDay('pageview__datetime')).values( 'y', 'm', 'd').order_by( 'y', 'm', 'd').annotate(cv=Count('id')) result : . . . { "y": 2019, "m": 4, "d": 3, "cv": 99 } . . . the pageview is correct, but the transaction is … -
How to find cause if error points to line with "application = get_wsgi_application()"
I'm trying to deploy a django app to pythonanywhere following their official guide; I've created a virtualenv, installed packages listed in my requirements.txt, created the web app and ammended the wsgi file listed in the dashboard as suggested. But I'm receiving this TypeEerror pointing to nowhere. ''' 2019-06-27 12:13:32,270: Error running WSGI application 2019-06-27 12:13:32,271: TypeError: 'function' object is not subscriptable 2019-06-27 12:13:32,271: File "/var/www/corebots_pythonanywhere_com_wsgi.py", line 25, in <module> 2019-06-27 12:13:32,271: application = get_wsgi_application() 2019-06-27 12:13:32,271: 2019-06-27 12:13:32,271: File "/home/corebots/.virtualenvs/myvirtualenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-06-27 12:13:32,271: django.setup(set_prefix=False) 2019-06-27 12:13:32,272: 2019-06-27 12:13:32,272: File "/home/corebots/.virtualenvs/myvirtualenv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup 2019-06-27 12:13:32,272: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-06-27 12:13:32,272: 2019-06-27 12:13:32,272: File "/home/corebots/.virtualenvs/myvirtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ 2019-06-27 12:13:32,272: self._setup(name) 2019-06-27 12:13:32,272: 2019-06-27 12:13:32,272: File "/home/corebots/.virtualenvs/myvirtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup 2019-06-27 12:13:32,272: self._wrapped = Settings(settings_module) 2019-06-27 12:13:32,272: 2019-06-27 12:13:32,273: File "/home/corebots/.virtualenvs/myvirtualenv/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ 2019-06-27 12:13:32,273: mod = importlib.import_module(self.SETTINGS_MODULE) 2019-06-27 12:13:32,273: 2019-06-27 12:13:32,273: File "/home/corebots/portfolio_pa/WEB/settings.py", line 177, in <module> 2019-06-27 12:13:32,273: # MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "WEB/media_cdn") # for: user uploaded 2019-06-27 12:13:32,273: 2019-06-27 12:13:32,273: File "/home/corebots/portfolio_pa/example_storages/settings_s3boto.py", line 24, in <module> 2019-06-27 12:13:32,273: #AWS_ACCESS_KEY_ID = os.getenv['AWS_ACCESS_KEY_ID'] 2019-06-27 12:13:32,273: *************************************************** 2019-06-27 12:13:32,273: If you're seeing an import error and don't know why, 2019-06-27 12:13:32,273: we have a … -
Creating the first Celery task - Django. Error - "ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//:"
I'm trying to create my first Celery task. The task will send the same e-mail every one minute to the same person. According to the documentation, I create my first task in my project. from __future__ import absolute_import, unicode_literals from celery import shared_task from django.core.mail import send_mail @shared_task def send_message(): to = ['test@test.com', ] send_mail('TEST TOPIC', 'TEST MESSAGE', 'test@test.com', to) Then, in my project's ja folder, I add the celery.py file, which looks like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings') app = Celery('app_rama') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) app.conf.beat_schedule = { 'send-message-every-single-minute': { 'task': 'app.tasks.send_message', 'schedule': crontab(), # change to `crontab(minute=0, hour=0)` if you want it to run daily at midnight }, } Then in the __int__.py file of my project I added: from __future__ import absolute_import, unicode_literals # This will make sure … -
Create Django LOGIN - Rest API (Takes: 'username', and 'password')
I want to create a django api that takes the username and password to make it possible to login. I don't want to use tokens because only the logged in user can view its own api anyways. I Just want a way to send a POST request via like POSTMAN or FLUTTER APP. And then get a response that says the login was either successful or failed. -
Access Oracle Database v.10 using Python/cx-Oracle?
I'm trying to connect to an Oracle DB v10.1 using Python/Django. Therefore cx_Oracle is needed. cx_Oracle (Current version, down to v5.3) needs a minimum oracle_instantclient version of 11.2. Which is incompatible with the OracleDB 10.x. So when I use client 10.2 to connect to DB 10.1, it works from the Oracle client side, but Python/cx_Oracle fails because it needs minimum client 11.2 Using an newer Version of the client (11.2+), cx_Oracle is happy, but the client says that the server (10.2) is too old to connect. Even trying to install an old cx_Oracle from the Pypi archive (5.2.1) fails, because it either doesn't support Python3 (my project), or I can't even install it in a Python2.7 test environment. [...] File "/home/<snip>/.local/lib/python3.6/site-packages/pipenv/patched/notpip/_internal/utils/misc.py", line 705, in call_subprocess % (command_desc, proc.returncode, cwd)) pipenv.patched.notpip._internal.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/tmp0B1fptbuild/cx-oracle/ Is there any way to connect to an old Oracle 10.x DB from Python (maybe without cx_Oracle), or even better, from Django? -
How to display all titles of posts related to a post using tags
I want to display related posts using django filter with tag. I wrote this filter, but the Queryset won´t filter with title. Maybe someone can give me a hint how to rewrite my filter to display all posts related with the same tag. My filter in app_tags.py @register.filter(name='related_posts') def related_posts(tag): posts = Post.objects.filter(tags__name__in = [tag]) return posts.title() My Html: <div class="containernav"> <div class="mt-3 p-3 bg-white rounded box-shadow border border-gray"> <h6 class="border-bottom border-gray pb-2 mb-0">Verwandte Posts</h6> <div class="media text-muted pt-3"> {% load app_tags %} <a href="{% url 'post_detail' post.slug %}">({{ tag|related_posts }})</a> </p> </div> </div> </div> -
Writing subquery in django which contain derived columns
I want to fetch records entities which lies within radius of a certain longitude and latitude. With the help of stackoverflow post Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location I found the query SELECT * FROM( SELECT *,(((acos(sin((@latitude*pi()/180)) * sin((Latitude*pi()/180))+cos((@latitude*pi()/180)) * cos((Latitude*pi()/180)) * cos(((@longitude - Longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM Distances) t WHERE distance <= @distance where @latitude and @longitude are the latitude and longitude of the point. Latitude and longitude are the columns of distances table. Value of pi is 22/7 I want to do something similar be done in django ORM. -
Django CONN_MAX_AGE is set to 0 but connection remains open after executing query
I'm using Django 1.10 as an ORM connecting to a Postgres DB. I have a problem where old connections stay open in idle state in the db. My request is: MyTable.objects.all().first().id I use the following query to verify that the connection remains open: SELECT * FROM pg_catalog.pg_stat_activity WHERE usename = 'my_user_name' ORDER BY backend_start DESC limit 3; The result is: This only disappears when i close my ipython or add django.db.connection.close() to my code. According to Django's documentation, if MAX_CONN_AGE is set to default (0) the connection supposed to close after the end of the request, but its not closing as expected. -
"Choose Term" button that filters to get a query that is in between two dates
I am trying to implement a drop down button that that lists the last 6 terms (as in spring, fall, winter, etc.) where the current term is bolded. Here's a picture: I have how I want it to look now, it's just not functional. I'm having a hard time implementing this alongside how I amnestying current categorizing other options in this view. It's hard to explain, so here's my view code: class RewardPointsEarnedReport(TemplateView): template_name = 'admin/hr/reward_points_earned_report.html' @user_is_staff def dispatch(self, request, *args, **kwargs): return super(RewardPointsEarnedReport, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(RewardPointsEarnedReport, self).get_context_data(**kwargs) employees = get_active_users(self) page = self.request.GET.get('page') report_list = RewardPointsEarned.objects.all().order_by('-date_earned') point_types = RewardPointsType.objects.all() if page is None: page = 1 try: header = point_types[int(page)-1] except: header = point_types[point_type_list.count()-1] reports_by_category = [report for report in report_list if report.reward_points_type == header] this_term = AcademicTerm.objects.get(date_start__lte=datetime.now(),date_end__gte=datetime.now()) current_reports = [report for report in reports_by_category if report.date_earned > this_term.date_end and report.date_earned < this_term.date_start or 0] point_type_list = [] for point_type in point_types: point_type_count = RewardPointsEarned.objects.filter(reward_points_type=point_type).filter(date_earned__gte=this_term.date_end).count() if point_type_count: point_type_list.append((point_type, point_type_count)) else: point_type_list.append((point_type, 0)) context['point_type_list'] = point_type_list context['current_reports'] = current_reports context['academic_terms'] = AcademicTermType.objects.all() context['this_term'] = this_term context['header'] = header return context and here's my html: {% extends "admin/hr/index.html" %} {% load i18n %} {% load … -
Django Rest Framework doesn't return Response code from condition
I'm trying to return a 405 response from DRF if the object is not allowed to be deleted, but I keep getting a Response 204_NO_CONTENT. Even though the instance is not deleted and the if statement works as should, the returned response is not correct. What am I doing wrong here? Here's my code: def perform_destroy(self, instance): if not instance.deletable: return Response({'error_message': 'Cannot delete last journal entry line.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) sje_id = instance.journal_entry.id instance.delete() sje = PurchaseJournalEntry.objects.get(pk=sje_id) sje.regenerate_mutations() sje.save() -
Processing live RTMP stream using OpenCV and then streaming to browser [on hold]
Below is the use case with which i need some help. I am working on Windows platform and using Django for web development. 1) Get live stream from a drone. The drone uses RTMP to stream video feed. Hence, I setup nginx server(nginx 1.7.11.3 Gryphon) which has RTMP support. Using this, I was able to stream the feed to my nginx server(tested succesfully using VLC player). 2) Process the live stream. The live RTMP stream then needs to be processed for object detection using OpenCV with Python. ## capture video stream using OpenCV libray ## Process the stream using OpenCV library 3) The above processed video needs to be displayed in browser(in localhost itself) on Django server, as I am building a web application. This is what I need help with. I am not sure how to return an HTTP/HLS stream from the view to the web page. I understand we can configure the Nginx server to convert RTMP to HLS, but am not sure how to proceed now that processing is involved in the middle. I tried searching for packages in Django/OpenCV which will help convert, and found approaches using FFMPEG libraries, but I am not sure if it …