Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Moving order creation to when customer completes checkout
our ecommerce site using django-oscar currently handles order creation after the user pays, which can result in the issue described in https://github.com/django-oscar/django-oscar/issues/2891. We would like to switch to creating the order with a pending status once the user completes checkout, and then fulfilling it once payment goes through. We're currently unsure what the consequences of this are, so I was hoping to find some examples of this order creation flow that I could look to for our transition. Does django-oscar use this flow by default out of the box, or are there existing open source applications that we could check for examples? Thanks in advance for any help Technical details: Python version: 2.7 Django version: 1.11 Oscar version: 1.6 -
Wrong alphabetical ordering by manytomany field in django
I am Django beginner and trying to figure it out why got wrong alphabetical ordering by m2m field when I have more than 2 records. Below provide dummy information for your better understanding. Created from scratch models.py: from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class Publisher(models.Model): name = models.CharField(max_length=50) pub_authors = models.ManyToManyField(Author, blank=True) After filling db with some data, tried simple query in python console for give all the publishers which are ordered by authors they have: from app.models import Publisher [print(i.pub_authors.all()) for i Publisher.all().order_by('pub_authors__name')] Example of output when have only 1 author to each publisher(correct ordering): <QuerySet [<Author: A>]> <QuerySet [<Author: A>]> <QuerySet [<Author: A>]> <QuerySet [<Author: B>]> <QuerySet [<Author: C>]> Example of output when have more than 1 author to each publisher(wrong ordering): <QuerySet [<Author: A>]> <QuerySet [<Author: A>]> <QuerySet [<Author: A>, <Author: B>]> <QuerySet [<Author: A>]> <QuerySet [<Author: B>]> <QuerySet [<Author: B>, <Author: A>]> <QuerySet [<Author: B>, <Author: C>]> <QuerySet [<Author: B>]> <QuerySet [<Author: A>, <Author: C>]> <QuerySet [<Author: C>]> Expected results: <QuerySet [<Author: A>]> <QuerySet [<Author: A>]> <QuerySet [<Author: A>]> <QuerySet [<Author: A>, <Author: B>]> <QuerySet [<Author: A>, <Author: C>]> <QuerySet [<Author: B>]> <QuerySet [<Author: B>]> <QuerySet [<Author: B>, <Author: A>]> <QuerySet [<Author: B>, … -
Using models.BooleanField() in my Django model causes an error within admin site AttributeError: 'NoneType' object has no attribute 'strip'
I have a Product model within my Django e-commerce project which looks like this: class Product(models.Model): slug = models.SlugField(max_length=40) image = models.ImageField() title = models.CharField(max_length=150) product_ref = models.Field.unique description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) stock_quantity = models.PositiveIntegerField() is_available = models.BooleanField(default=True) However this causes an error when I click on the Product option within Django admin, the wording of which is: AttributeError: 'NoneType' object has no attribute 'strip' Removing the Boolean Field stops this from happening and all works fine. How can I implement a Boolean Field without causing an error? I have tried leaving the optional arguments blank also. I have also Googled the issue. I am using the mysql.connector.django within settings. The application is linked to MySQL. -
How to translate GEOSGeometry object?
Is there a way to translate an object of GEOSGeometry type? The function exists in shapely package. I can't find the same function in Django's gis module. -
Django Pyhton Query Join
class Service(models.Model): invoice = models.Charfield() class Sparepart(models.Model): name = models.Charfield() service = models.Foreignkey(Service) class SparepartDetail(models.Model): type = models.Charfield() qty = models.IntegerField() sparepart = models.Foreignkey(Sparepart) How make query join like this : FROM service LEFT OUTER JOIN sparepart ON ( service.id = sparepart.service_id ) LEFT OUTER JOIN sparepartdetail ON ( sparepart.id = sparepartdetail.sparepart_id AND sparepartdetail.type = 'USED' ) -
Dynamically query database and output filtered results
Python 3.7.3 django 2.2.5 mysql 5.7.27 I have 4 tables in my legacy database (can't touch Assets, Employees and Assignments. I can alter Item however I want), that are of interest here: Assets class Assets(models.Model): id = models.AutoField(db_column='Id', primary_key=True) assettag = models.CharField(db_column='AssetTag', unique=True, max_length=10) assettype = models.CharField(db_column='AssetType', max_length=150) ......... etc. Employees class Employees(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. loginname = models.CharField(db_column='LoginName', max_length=30, blank=True, null=True) userpass = models.CharField(db_column='UserPass', max_length=30, blank=True, null=True) lastname = models.CharField(db_column='LastName', max_length=50, blank=True, null=True) firstname = models.CharField(db_column='FirstName', max_length=50, blank=True, null=True) ......... etc. Assignments class Assignments(models.Model): employeeid = models.ForeignKey('Employees', db_column='EmployeeId', default=0, blank=True, null=True, on_delete=models.SET_DEFAULT) assetid = models.ForeignKey('Assets', db_column='AssetId', default=0, blank=True, null=True, on_delete=models.SET_DEFAULT) ......... etc. Items class Item(models.Model): rfid_tag = models.CharField(max_length=24, unique=True, default='', help_text="Only HEX characters allowed",) asset = models.OneToOneField('Assets', default=None, null=True, on_delete=models.SET_DEFAULT,) date = models.DateTimeField(name='timestamp', auto_now_add=True,) assignment = models.ForeignKey('Assignments', default=None, on_delete=models.SET_DEFAULT,) Now, I have a view that looks like this: class IndexView(generic.ListView): template_name = template context_object_name = 'item_list' def get_context_data(self, **kwargs): # call the base implementation context = super().get_context_data(**kwargs) # Add own context information context['count'] = Item.objects.count() context['employee'] = Employees.objects.filter(loginname = self.request.user.username) return context def get_queryset(self): query = self.request.GET.get('q') if query: return Item.objects.filter( Q(asset__assettag__icontains = query) | Q(rfid_tag__icontains = query) | Q(assignment__employeeid__loginname__icontains = query) | … -
Page does not redirect on click but other buttons work/redirect properly?
I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening. I feel like I'm missing something very slight, I tried moving the Manager Options button into the form tags but this did not work either, so I'm not sure I'm missing an important piece as I am fairly new to Python/Django. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) elif 'manager_options' in self.request.POST: return redirect('enter_exit_area_manager_options_list') class EnterExitAreaManagerOptionsList(ListView): filter_form_class = EnterExitAreaManagerOptionsFilterForm default_sort = "name" template = "operations/list.html" def get_initial_queryset(self): return EmployeeWorkAreaLog.active.all() def set_columns(self): self.add_column(name='Employee #', field='adp_number') self.add_column(name='Work Area', field='work_area') self.add_column(name='Station', field='station_number') urls.py urlpatterns = [ url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'), url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'), ] enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" novalidate > {% csrf_token %} <div> <div> {{ form.adp_number.help_text }} {{ form.adp_number }} </div> <div> {{ … -
django mysql connectivity issue after SSL enabled
I have 2 different servers one for applicaton and another for db to make the communication secure between the servers, I have enabled ssl with a slf signed certificate. After the changes made server shows error error totally whack. I am using python 2.7, django 1.6 and mysql 5.7 I checked I am able to connect using stand alone python script but while consuming from django causes the error error totally whack. Thanks In Adance for help -
Transform Queryset Into string
I have a Django / Python QuerySet that Looks like this: [{'first_name': 'hans', 'last_name': 'baust'}] And I would like to only have something like variable name1 that contains 'hans' variable name2 that contains 'hans' I cannot make it with the current Google results... -
Jinja: combine several templates into one single document
I'm working with Django and want to dynamically merge several jinja templates into one single document. Each of those templates is a complete, independent document, that is, it contains all the markup it needs to be rendered individually. Do you know if this is possible, or if Jinja offers a special API or method for this kind of operation? -
How to build a queryset in a specific order in Django
I'm trying to list profiles of users. I want to list them in such a way that profiles with same city of the user should come first, then next priority should be state, then country, and finally, rest of the profiles. This is what I have tried. profiles_city = Profile.objects.filter(city=current_user.city) profiles_state = Profile.objects.filter(state=current_user.state) profiles_country = Profile.objects.filter(country=current_user.country) profiles_all = Profile.objects.all() profiles = (profiles_city | profiles_state | profiles_country | profiles_all).distinct() But it is yielding the same result as Profile.objects.all() Please help me. thanks in advance -
Hide a field from a django ModelForm depending on user's profile
I have a form that has two fields (mail and status). I want to have the status field hidden only when the user has a profile not equal to "tech" so that the user cannot change its value in that case. What I was trying to do, but I still didn't get it to work since it throws me TypeError error: __init __ () got an unexpected keyword argument 'user', is to overwrite the __init __ () method of RequestForm in forms.py and on the other hand, overwrite the get_form_kwargs () method to pass the user to the form. I post the code that I understand relevant: views.py: ... class RequestUpdate(UpdateView): model = Request form_class = RequestForm template_name = 'request/request_form.html' success_url = reverse_lazy('request:request_list') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs forms.py: class RequestForm(forms.ModelForm): class Meta: model = Request fields = [ 'mail', 'status', ] labels = { 'mail': 'E-Mail (including @domain.example)', 'status': 'Request's status:' } widgets = { 'mail': forms.EmailInput(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) if self.user.is_tech == False: self.fields.pop('status') models.py ... class Request(models.Model): mail = models.CharField(max_length=50) states = [('1','Pending'), ('2','In process'), ('3','Done')] status = models.CharField(max_length=50, choices=states, default='1') user = … -
How to make an api call from my django view
I'm using python 3.6.8 with django 2.2.5. I've built a rest api and I want to call it via the url using my django view login_request() function. Here is the source code: def login_request(request): """ This function is used to login all users except the admin of the entire site. It makes an api call to the LoginView defined in commons.apiviews with the necessary parameters and renders the necessary html file accordingly. It gets the necessary data from the request.session variable. """ if request.method == 'POST': # login_response = request_library.Response() try: user_data = { "username": request.POST.get('username'), "password": request.POST.get('password') } login_response = request_library.post( "http://localhost:8055/commons/login/", data=request.POST, headers={ 'content-type': "application/x-www-form-urlencoded" }, timeout=(3, 6) ) login_response.raise_for_status() except Exception as e: # TODO find a better thing to do with the exception with open('login_tries.txt', 'a') as login_response_objects: login_response_objects.write(str(e) + "\t" + str(request.body) + "\n\n") else: if login_response is not None: # user_token = login_response.token messages.info(request, f"You are now logged in as {request.data.get('username')}") return redirect('ui/dashboard.html') else: return HttpResponse("didn't work") return render(request=request, template_name="ui/login.html", context={}) What it's supposed to do is, whenever http://localhost:8055/commons/login/ is POSTed to with username & password it will return a 200 and an authorization token as a response. The above is being used by … -
How to connect my postgresql database with my django project?
When I run the command "pg_ctl -D -l logfile start", I have this result : waiting for server to start.... stopped waiting pg_ctl: could not start server Examine the log output And when I ckecked the logs, I have this : check-logs And this is my configuration: settings.py postgresql.conf pg_hba.conf Do I change the .conf files ? And which parameters ? Thank you for you answers ! -
How to sort list of dictionaries in Python
I have a list of dictionaries in Pyhton as follows: images = [{'uri': 'https://some-link.blob.core.windows.net.net/devthumbnails/1024x768/64/41/98/64419888297779407561461629073227065160696285270116603463558823470505654333611.jpg', 'position': '0'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/33/44/41/33444169622672594337676840600346050570907940224888845885580705086781040628903.jpg', 'position': '1'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/41/46/99/41469935475840270004889223861351938003980938652350786820222101550878440209095.jpg', 'position': '2'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/58/75/58/5875586317181716679126235880198721021684963481995594779485630886902274081554.jpg', 'position': '3'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/43/49/66/43496617617402984595952294447831932918405619473544645594784712841815014159696.jpg', 'position': '4'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/58/02/34/58023409863921180862667204492888551278254010639571762445601939880620855964505.jpg', 'position': '5'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/36/22/76/36227680451273880975070000838700274536225673420153023620631555589946521174102.jpg', 'position': '6'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/25/08/19/25081934413799694457632686505539828478363116795387601261763375409872686844488.jpg', 'position': '7'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/29/69/32/29693252042243727029651750357989431990778953906071901135228406135133977694240.jpg', 'position': '8'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/32/08/12/32081296724310348807184322021859931042996444008194149989050172920699516702708.jpg', 'position': '9'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/78/32/05/78320563911470703705431807857066302926786080992451285767704219765878587895294.jpg', 'position': '10'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/45/68/68/45686886529184531303217514851187276286410962612950239302976824977433885355299.jpg', 'position': '11'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/72/59/00/7259007439354083322229206921563369468125207106159648770203873465284114242890.jpg', 'position': '12'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/84/48/54/84485459564719601932735074276164902175816462482914733108723651993560201088913.jpg', 'position': '13'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/10/28/77/102877279417898628351098113431759126412045721643126079051218817213834246455153.jpg', 'position': '14'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/39/83/38/39833822893039666936949954403817914899073341336875871633644019565696649530535.jpg', 'position': '15'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/99/45/89/99458973667381587321791276054667596349042589326181154771316565893893148706844.jpg', 'position': '16'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/82/61/29/82612936862475837022828306892947119148350841132548959316321620668433031577983.jpg', 'position': '17'}, {'uri': 'https://some-link.blob.core.windows.net/devthumbnails/1024x768/11/19/56/111956100385260490476900173411198572352351708852063055906233069090064975146790.jpg', 'position': '18'}] I want to sort it and I want that the new list is as follows: [first_three_elements, last_three_elements, the_rest]. I've tried with something as follows: first_three = images[0:3] the_rest = images[3:int(len(images) - 3)] last_three = images[(int(len(images) - 3)):int(len(images))] result = first_three + last_three + the_rest But I get an error: unhashable type: 'slice' unhashable type: 'slice' unhashable type: 'slice' Any idea how to solve it? -
How to add like button in class based List view in django
I have added like button in detail view but could't able make the logic to add like button in List View. I have commented out the logic which I have used in Detail View below which is failed to create like button in List View. can somebody help me with the please. model.py Codes in models.py class AlbumVoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,album,user): try: return Vote.objects.get(album=album,user=user) except ObjectDoesNotExist: return Vote(album=album,user=user) class AlbumVote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) album = models.ForeignKey(Album, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) objects = AlbumVoteManager() class Meta: unique_together = ('user', 'album') form.py Codes in form.py class AlbumVoteForm(forms.ModelForm): class Meta: model = AlbumVote fields = ['like'] views.py Codes in views.py class AlbumListView(ListView): model = Album paginate_by = 5 # def get_context_data(self,**kwargs): # ctx = super().get_context_data(**kwargs) # if self.request.user.is_authenticated: # vote = AlbumVote.objects.get_vote_or_unsaved_blank_vote(album=self.object_list.object, user = self.request.user) # if vote.id: # vote_url = reverse('music:album_vote_update', kwargs={'album_id':vote.album.id,'pk':vote.id}) # else: # vote_url = reverse('music:album_vote_create', kwargs={'album_id':self.object_list.object.id}) # vote_form = AlbumVoteForm(instance=vote) # ctx['vote_form'] = vote_form # ctx['vote_url'] = vote_url # return ctx album_list.html Codes in album list view. <div class="container"> {% if object_list %} {% for album in object_list %} <div class="card … -
How to tell the cache_page decorator to use different cache_keys with regards to the Accept header?
I realized that the cache_page decorator will cache text/html or application/json responses and return one for the other without noticing. I'd like to give cache_page a list of header to use to generate a cache key so that it can take it into account. -
django-q does not stop with Ctrl-C
i installed django-q version 0.9.4 but i can not stop qcluster with Ctrl+C. Q_CLUSTER = { 'name': 'DjangORM', 'sync' : False, 'orm': 'default', 'retry': 18000, } 15:43:57 [Q] ERROR reincarnated worker Process-1:8 after death 15:43:57 [Q] ERROR reincarnated worker Process-1:17 after death 15:43:57 [Q] ERROR reincarnated worker Process-1:19 after death 15:43:57 [Q] ERROR reincarnated monitor Process-1:21 after sudden death 15:43:58 [Q] ERROR reincarnated pusher Process-1:22 after sudden death 15:43:58 [Q] ERROR reincarnated worker Process-1:14 after death 15:43:58 [Q] ERROR reincarnated worker Process-1:20 after death 15:43:59 [Q] ERROR reincarnated worker Process-1:18 after death 15:44:01 [Q] INFO Process-1:24 ready for work at 9312 15:44:01 [Q] INFO Process-1:23 ready for work at 4432 -
Customer search for an IT company
We are a small team of brilliant and self-motivated persons. For over 7 years, Owlab has been a business-oriented software engineering company committed to helping businesses kickstart, develop, and succeed. With profound technological expertise in a range of business domains such as financial services, healthcare, retail, and entertainment, Owlab implemented innovative ideas that allowed businesses - from startups to mid-sized and large companies - to scale, evolve, and prosper. Our quality policy includes functionality, usability, security, and crowd testing. We transfer all copyrights once the project is done. We will be able to sign NDA, and we never disclose information about the project. We provide the following services: Design Development: UI/UX Wireframing with Balsamiq/Sketch UI/UX Design with Photoshop/Sketch Website Development: Backend on Django/Python or PHP Frontend on React JS (or simple jQuery if requested) Restful API development on Django/Python Web Scraping/Crawling, Data collection on Python Mobile App Development: iOS Native Apps using Swift programming language Android Native Apps using Java programming language We are a small team of brilliant and self-motivated persons. For over 7 years, Owlab has been a business-oriented software engineering company committed to helping businesses kickstart, develop, and succeed. With profound technological expertise in a range of … -
My url not reading my function in views.py in DJANGO (found similar question not able to trace my issue)
mysite/urls.py from django.contrib.auth import views from django.views.generic.base import TemplateView urlpatterns = [ url('update_db/(<dbname>)/', include('polls.urls')), url(r'^admin/', admin.site.urls), url('mysite/login/', auth_views.LoginView.as_view(),name='login'), url(r'^fetch/',include('polls.urls')), url('mysite/logout/$', auth_views.logout, name='logout'), ] polls.urls.py from django.conf.urls import url from . import views from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse urlpatterns = [ url('update_db/(?P<dbname>\w+)/$', login_required(views.MyView.get), name='x'), url('', login_required(views.IndexView.as_view())), ] fetch.html <td><a href="{% url 'x' dbname=schdule.5 %}/?next='fetch'">click</a></td> polls/views.py from django.shortcuts import render from django.views.generic import TemplateView , ListView from django.views.generic.edit import UpdateView # Create your views here. from django.http import HttpResponse from .models import Item , DbRestorationLogDetails class MyView(UpdateView): logger.error('Something went wrong!') print "THANKS FOR UPDATING" template_name='fetch.html' model = DbRestorationLogDetails fields =['verification_status'] def get(self,request, dbname): usname=request.user print usname print dbname if request.method == "GET": dblog = DbRestorationLogDetails.objects.get(dbname=dbname) dblog.verification_status = 'Verified' print dblog.verification_status dblog.save() #.update(dblogdetails.verification_status = 'Verified') return HttpResponseRedirect(request.GET.get('next')) NOTE: NOT able to reach to MyView.get() and no db update happening. I assume my code is not able to read my function. -
Update another Model value through DRF perform_create (viewset) or post_save signal of Model
I have a model which's field values are updated through other models. For example, Model (Post), and creating a Post updates the post_exist value of Model (Onboarding). The method that updates the post_exist value is put into a redis queue as I dont want it to be blocking. Which of the following two ways is the best way considering speed and safety: The post is created using Django Rest Framework. The method that updates the post_exist value (in redis queue) is called in the perform_create method of the Post its Viewset or The method that updates the post_exist value (in redis queue) is called in the post_save signal of the Post model. -
requirements.txt Issues while deploying Django on AWS Elastic Beanstalk
I am trying to deploy a Django APP on AWS Elastic Beanstalk, but i have been dealing with this requirements.txt file invalid error for hours. Please any help would be apppreciated Erros Trace: 019-11-04 11:54:26 INFO createEnvironment is starting. 2019-11-04 11:54:27 INFO Using elasticbeanstalk-us-west-2-607492160452 as Amazon S3 storage bucket for environment data. 2019-11-04 11:54:50 INFO Created security group named: sg-07294ef34f2e0aaa2 2019-11-04 11:55:06 INFO Created load balancer named: awseb-e-y-AWSEBLoa-9P7Z3Q0VIKKW 2019-11-04 11:55:06 INFO Created security group named: awseb-e-yrxmhgfrfe-stack-AWSEBSecurityGroup-1D5BSG71QUTBX 2019-11-04 11:55:06 INFO Created Auto Scaling launch configuration named: awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingLaunchConfiguration-117EXRROI4681 2019-11-04 11:56:10 INFO Created Auto Scaling group named: awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI 2019-11-04 11:56:11 INFO Waiting for EC2 instances to launch. This may take a few minutes. 2019-11-04 11:56:11 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:607492160452:scalingPolicy:bcdf6ff5-32b9-4b0a-9aba-274fbedbba1a:autoScalingGroupName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI:policyName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingScaleDownPolicy-LOVVFGQVBP2Z 2019-11-04 11:56:11 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:607492160452:scalingPolicy:9fbbafea-cca9-4279-84fb-faec4f0cc934:autoScalingGroupName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingGroup-GFXMDJHNG2WI:policyName/awseb-e-yrxmhgfrfe-stack-AWSEBAutoScalingScaleUpPolicy-1WYK2Q8WDWHDT 2019-11-04 11:56:11 INFO Created CloudWatch alarm named: awseb-e-yrxmhgfrfe-stack-AWSEBCloudwatchAlarmLow-T33T5Y5CO17U 2019-11-04 11:56:11 INFO Created CloudWatch alarm named: awseb-e-yrxmhgfrfe-stack-AWSEBCloudwatchAlarmHigh-1D20PAP6VBZGH 2019-11-04 11:56:42 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-11-04 11:56:45 ERROR [Instance: i-0985fbc7c7272a213] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log … -
Where to even begin investigating issue causing database crash: remaining connection slots are reserved for non-replication superuser connections
Occasionally our Postgres database crashes and it can only be solved by restarting the server. We have tried incrementing the max connections and Django's CONN_MAX_AGE. Also, I am trying to learn how to set up PgBouncer. However, I am convinced the underlying issue must be something else which is fixable. I am trying to find what that issue is. The problem is I wouldn't know where or what to begin to look at. Here are some pieces of information: The errors are always OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections and OperationalError: could not write to hash-join temporary file: No space left on device. I think this is caused by opening too many database connections, but I have never managed to catch this going down live so that I could inspect pg_stat_activity and see what actual connections were active. Looking at the error log, the same URL shows up for the most part. I've checked the nginx log and it's listed in many different lines, meaning the request is being made multiple times at once rather than Django logging the same error multiple times. All these requests are responded with 499 Client Closed Request. In addition … -
How do I make Open CV work on deployed web app
I have an application that I can run locally and have it open my web camera then detect a qr code. It works well when I run the app locally but then I used the app on my web server and it gets a Server Error (500). The app was made on Django, then for deployment I used digital ocean(ubuntu) and I also use nginx and gunicorn. html <li style= "margin: auto; width:auto"><a style="color:white" href="{% url 'attendees:qrscanner' %}" target="_blank"><button style="margin:15px; width:200px" class="btn btn-outline-primary">Check QR Scanner</button></a></li> views.py from django.shortcuts import get_object_or_404, render, redirect from django.utils import timezone from django.db.models import Sum from .models import Attendee, ActivityLog import re, qrcode, cv2, csv, io, os import numpy as np import pyzbar.pyzbar as pyzbar def qrscanner(request): cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_PLAIN frame_width = int(cap.get(3)) frame_height = int(cap.get(4)) aid = None while aid is None: _, frame = cap.read() decodedObjects = pyzbar.decode(frame) for obj in decodedObjects: aid = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data)) try: attendee = Attendee.objects.get(pk=str(aid[0])) attendee.present = True attendee.timestamp = timezone.now() attendee.activity.update_or_create(time_log=attendee.timestamp) attendee.save() context = { 'scan': 'QR Successfully Scanned', 'attendee': attendee, } except: context = { 'noscan': 'QR Scan Unsuccessful' } cv2.imshow("QR Reader", frame) if aid is not None: cv2.destroyAllWindows() break key = cv2.waitKey(1) … -
Cannot install "psycopg2" on Windows 10
Yesterday I uninstalled python 3.7 version by mistake. Then I install python again (this time 3.8 version) and again set up my environment. But I could not start my Django project which has Postgres connection. Actually I cannot install "psycopg2" in my environment. I searched for hours and implement every solutions I get from online but it does not work. Let me tell you what I did so far. First it said to add Postgres in my PATH so I added C:\Program Files\PostgreSQL\12\bin\ in my PATH. A new problem then arise with a huge ERROR report with 2 vital Error. ERROR: Failed building wheel for psycopg2 .......................... Running setup.py install for psycopg2 ... error I try to upgrade wheel but it says, Requirement already up-to-date http://initd.org/psycopg/docs/install.html#install-from-source I learned from this site that psycopg2 requires python2 version. So I installed python 2.7 also. I reinstalled PostgreSQL but it does not work. I deleted my virtual environment and create again but it does not work. Some says they solve this problem by running pip install psycopg2-binary But it does not work for me. Please help me to get rid of this. I stuck for hours.