Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any way to make @periodic_task run on call only,it runs automatically on project starts?
is there any way to make periodic_task to run on call only,I see Pingit() starts as soon as i run my django-app python manage.py runserver @periodic_task(run_every=crontab(minute="*/1"),options={"task_id":task_name}) def Pingit(): print('Every Minute Im Called') I Would like to make it run the periodic task only if i call it by Pingit -
django error in url generated by form, url is not matching. getting unwanted comma between my query search
i want to submit a form and after that i want to call a specific view but my url is not matching "," is coming in between. my form <form action={% url "blog:post_search" %}, method="get"> <input type="text" name="query"> <input type="submit" value="search"> </form> view.py def post_search(request): if 'query' in request.GET: search_query = SearchQuery(request.GET['query']) search_vector = SearchVector('title', 'body') result = Post.objects.annotate(search=search_vector, rank=SearchRank(search_vector,search_query) ).filter(search=search_query).order_by('-rank') return render(request,'blog/post/search.html',{'query':search_query, 'result':result}) urls.py path('search/', views.post_search, name='post_search') error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/search/,?query=confused Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='post_list'] blog/ tag/<slug:tag_slug>/ [name='post_list_by_tag'] blog/ <int:year>/<int:month>/<int:day>/<slug:post>/ [name='post_details'] blog/ <int:post_id>/share/ [name='post_share'] blog/ search/ [name='post_search'] sitemap.xml [name='django.contrib.sitemaps.views.sitemap'] The current path, blog/search/,, didn't match any of these. -
Python / Django: Get var from cookies
I tried to get distinct_id with request.COOKIES.get('distinct_id'). However Mixpanel saves the data in a not extractable way for me. Anyone knows why there are all these %22%3A%20%22 and how to extraxt distinct_id? print(request.COOKIES): { 'djdt': 'hide', 'cookie_bar': '1', 'mp_1384c4d0e46aaaaad007e3d8b5d6eda_mixpanel': '%7B%22distinct_id%22%3A%20%22165edf326870-00fc0e7eb72ed3-34677908-fa000-165e40c268947b%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%2C%22__alias%22%3A%20%22maz%2B1024%40gmail.com%22%7D', 'csrftoken': 'nvWzsrp3t6Sivkrsyu0gejjjjjiTfc36ZfkH7U7fgHaI40EF', 'sessionid': '7bkel6r27ebd55x262cv9lzv61gzoemw' } -
Get values from mongoDB column into HTML table using Django
I want to get the values from a mongoDB column inside a HTML Table. This is in views.py import pymongo from pymongo import MongoClient from pymongo.read_preferences import ReadPreference myclient = pymongo.MongoClient("mongodb://00.00.00.0:27017") mydb = myclient["hermes"] mycol = mydb["thePages"] def pages(request): for x in mycol.find({},{ "pageName" }): return HttpResponse("<td>%s</td>") %x urls.py: path('page/thePages', views.thePages, name = 'thePages'), Error: unsupported operand type(s) for %: 'HttpResponse' and 'dict' I am new to Django. Please help. I know I need a loop to get all the values in column. I need a way to go about it. Any help would be extremely helpful. -
Restrict users in django
I have a panel to manage posts by admin or the users that are admin. How can I restrict panel and display it only for admins not other users that register in system. View: class IndexView(LoginRequiredMixin, ListView): model = Post template_name = 'panel/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context["posts"] = Post.objects.all() context["counter"] = self.post_counter(context["posts"]) return context def post_counter(self, posts): postNumber = 0 for post in posts: postNumber +=1 return postNumber -
How to pass data from one view to the next
Summary: I am trying to build a job site. On index.html the user enters a zip code into a form to see jobs in that zip code, this form is handled with the job_query view. This brings them to another page(search.html) where at first you only see jobs in that specific zip code but I am trying to add a filter that lets the user see jobs within X miles. How can I pass the zip code value entered in the from on index.html to the next page? index.html: <h2>Find a Job</h2> <!--Search Bar--> <form method = "GET" action = "{% url 'search' %}" > <div id = "form_grid"> <input name="query" type="text" placeholder="Zip Code"> <button type="submit">Search</button> </div> </form> search.html: <form method = "GET" action = "{% url 'search' %}" > <input class="search_bar" name="query" type="text" placeholder="Zip Code"> <button class="search_btn btn btn-outline-success " type="submit">Find Jobs</button> </form> <form id="within_miles_form" method = "GET" action = "{% url 'within_miles' %}" > <input class="search_bar" name="miles" type="text" placeholder="Within X miles of Zip Code"> <button type="submit">Filter</button> </form> <!--code to display jobs--> views.py: def job_query(request): if request.method == "GET": query = request.GET.get('query') jobs_matching_query = Job.objects.filter(zip_code__iexact = query) | Job.objects.filter(city__iexact=query) | Job.objects.filter(state__iexact=query) number_of_results = 0 for job in jobs_matching_query: number_of_results … -
Django session handling on WebGL?
If you read this https://docs.djangoproject.com/en/dev/topics/http/sessions/ This means that Django handle the session only with cookies. The problem is that my in my WebGL application, the browser itself handles the Cookies. Thus imagine the scenario on Chrome: open 2 tabs on the same WebGL URL, without connecting: they both display the connexion form. Tab A: you log as "Olivier". You get the set-cookie from Django "xaC2x..blabla". Chrome stores it in its "global" storage Tab B: you log as "Reivilo". Django gets the cookie "xaC2x..blabla", disconnects "Olivier", an connects "Reivilo" Tab A: from this point, whatever you will do on Tab A will be sent as "Reivilo" because "Reivilo" is connected with the cookie "xaC2x..blabla". So all in all, what you be your suggestion to handle this problem with Django? I could do very complex URL rewriting if needed, I'm just looking for a simple and easy to handle in Django (even if I do very complex URL rewriting in nginx) solution. -
Django Combine two templated from different apps
I have two apps with the following structure project-> main app-> templates-> dashboard.html my app-> templates-> mydashboard.html I want to include mydashboard into dashboard, well this is possible using include template tag. but my problem appears when I have to pass some parameters into mydashboard, let's say they are named param1 and param2 these parameters are the variables which I have to load from my app app. well one possible method is to filling these params in dashboardview in mainapp and pass them using include tag into mydashboard.html like below def user_dashboard(request): ...-->here I have to get data from my app (this view is in main app and I do not want to make main app be dependent to my app return render(request, 'dashboard.html', {'param1': 0, 'param2': 34}) then in dashboard.html I add this part {% is_app_installed "myapp" as is_myapp_installed %} {% if is_myapp_installed %} {% include "myappdashboard.html" with param1=param1 param2=param2 %} {% endif %} It seems the above method works but the main problem is that using this method mainapp is dependent to myapp and I do not want to this happens. is there any other method to load those param1 and param2 inside myapp? thanks -
Django/Djangotable2 html table on row click to edit form
sorry this post may be messy not sure how do explain what I am looking for very well but here goes nothing. I have a Django App and using DjangoTable2 to print a data model to a table, the next thing I am looking to do it when the user clicks on the table row to redirect the page to a equivalent edit form urls.py path('', CustomerView.as_view(), name='customer'), path('customer_edit/', views.customer_edit, name='customer_edit'), tables.py import django_tables2 as tables from customer.models import Customer class CustomerTable(tables.Table): account = tables.Column(attrs={'td': {'class': 'account'}}) class Meta: model = Customer attrs = {'id': 'table'} exclude = ('is_deleted',) template_name = 'django_tables2/bootstrap-responsive.html' views.py from django.shortcuts import render from django_tables2 import RequestConfig from customer.models import Customer from customer.tables import CustomerTable from django.views.generic import TemplateView class CustomerView(TemplateView): template_name = 'customer/customer.html' def get(self, request, *args, **kwargs): table = CustomerTable(Customer.objects.all().filter(is_deleted=False)) RequestConfig(request).configure(table) return render(request, 'customer/customer.html', {'table': table}) def customer_edit(request): return render(request, 'customer/customer_edit.html') html {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block head %} <title>Dev Genie - Customers</title> {% endblock %} {% block body %} <div class="input-group col-md-6"> <input type="button" class="btn btn-success" value="Add"> <input type="button" class="btn btn-danger" value="Delete"> <input class="form-control py-2" type="search" value="search" id="example-search-input"> <span class="input-group-append"> <button class="btn btn-outline-secondary" type="button"> <span class="glyphicon … -
How to send data from Django to outside python class or vice versa?
in my app folder I have views.py and bot.py. The bot.py is main brain of my project, there are all my functions that 'do' main stuff(backend). I import them and use in Django. Now somehow I need to send data from django to bot.py. How to do that? I have: views.py: bot = Instagram() class InstabotFormView(AjaxFormMixin, FormView): form_class = LoginInstagramForm template_name = 'instabot.html' success_url = 'runinstabot.html' def form_invalid(self, form): response = super(InstabotFormView, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(InstabotFormView, self).form_valid(form) login = form.cleaned_data.get('login') password = form.cleaned_data.get('password') tagi = form.cleaned_data.get('tags') tags = [] tagi = tagi.split(',') tags.extend(tagi) print(tags) if self.request.is_ajax(): print('It is AJAX') bot.login(login,password) bot.search(tags) print(form.cleaned_data) data = { 'message': "Succesfully opened Selenium." } return JsonResponse(data) else: return response bot.py: class Instagram(object): ... def changeTag(self): #if a list gets to the end reset it self.nextTag += 1 tagsNum = len(Instagram.tags) if self.nextTag == tagsNum: self.nextTag = 0 else: self.tags[0 + self.nextTag] return self.nextTag After I run my script it writes: AttributeError: 'Instagram' object has no attribute 'tags' I know that Instagram.tags does not exist but how to use data from Django inside my bot.py? How to put instead of Instagram.tags , tags=[] from … -
select_related on many to many with custom through table
I have two models, Foo and Bar, and I have created a many to many relationship with a custom through table, FooBar. class Foo(models.Model): foofield = models.CharField() class Bar(models.Model): barfield = models.CharField() foos = models.ManyToManyField('Foo', through='FooBar', related_name='foo_bar') class FooBar(models.Model): foo = models.ForeignKey(Foo, related_name='foobar') bar = models.ForeignKey(Bar, related_name='foobar') foobarfield= models.CharField() What I would like to do is display all Bar records for a given instance of Foo, and for each such record also display the corresponding value of foobarfield. So I would get something like barfield_value1, foobarfield_value1 barfield_value2, foobarfield_value2 barfield_value3, foobarfield_value3 ... I can't seem to construct the correct query to do this though. I tried something like Bar.objects.select_related('foobar').filter(foobar_foo = foo_instance) Since I would expect foobar to be unique for a give instance of Foo but this does not seem to work. How do I get the result I want? -
Model creation with Celery
I have a post_save signal which triggers a Celery task. That task have to get a list of clients from a readlonly table and create a record for every item, around 250k items. What is the best practice to deal with this using celery asynchronously? A single task looping all 250k clients @task def client_create(store_id): clients = Clientes.objects.all() for client in clients: Client.objects.create(**ClientSerializer(client).data) or a second task to throw everything into a queue @task def queue_client(store_id): clients = Clientes.objects.all() for client in clients: client_create.delay(ClientSerializer(client).data) @task def client_create(data): Client.objects.create(**data) -
Creating inbox of messages (from Django model)?
I'm trying to design an inbox for user messages. I have the Message model and I'm trying to display the created messages. models.py class Message(models.Model): subject = models.TextField(max_length=1000, blank=True) text = models.TextField(max_length=10000, blank=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True, related_name="sender" ) receiver = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True, related_name="receiver" ) profile.html ## SIDE BAR (COLUMN 1) <div class="tbody"> {% for message in received %} <div class="ui card mcard" onclick="openMessage(--insert--here)"> <div class="content"> <div class="header">{{message.subject}}</div> <div class="text">{{message.text}}</div> </div> </div> {% endfor %} </div> ## COLUMN 2 <div class="ui column"> <div class="row"> <div id="subject"> </div> <div id="firstname"> </div> <div id="lastname"> </div> </div> <div class="row" id="text"> </div> </div> I displayed a list of messages (just subject and sender) in a scrollable side bar. When you click on the card for the specific message, I want all the contents to display in the main (right) column. This is basically how Apple mail works if you know what that looks like. I'm having trouble getting the right column to display the content because I can't pass the Django Message object to the function (because it's basically running a loop to create cards). Is there a relatively easy solution to this? TLDR - basically, … -
Django - Displaying a user list takes over 14 seconds, how to speed it up?
I have a view that will display members based on the letter someone select(ex: clicking L on the webpage will display all the members whose firstname start with L, ordered by lastname) The problem is that it can take over 14 seconds to display the page(like"M", around 180 members to list, 17 seconds or so to do so.) . The SQL query doesn't seems the problem since Debug Toolbar reports that it takes less than a second for the query. Here is the view: def show_all_members(request, letter): members = MyUsers.objects.filter(firstname__istartswith=letter).order_by('lastname') alphabet = list(string.ascii_lowercase) request.session['url'] = request.get_full_path() context_dict = {'all_members': members, 'alphabet': alphabet} return render(request, "users/show_all_members.html", context_dict) Programming is a hobby so I'm a bit lost on what is happening here and how to optimize it. Any help and pointer is appreciated. Using Django 2.1.1 -
Time data does not match format YYYY-MM-DD
I have an issue getting the difference in days between 2 dates in python. I have the following block of code: last_used = models.DateTimeField(default=datetime.now().date(), editable=False) date_format = "%y-%m-%d" a = datetime.strptime(str(datetime.now().date()), date_format) b = datetime.strptime(str(last_used), date_format) days_since_use = models.IntegerField(default=(b-a).days, editable=False) I have tried with both the %y-%m-%d and YYYY-MM-DD formats but neither worked. ValueError: time data '2018-09-16' does not match format '%y-%m-%d' Any ideas? -
Serializer returns object instead fields
Using Django 2.1/Django Rest Framework. I am receiving the Model object output from DRF instead of the actual fields. I would like to recieve all the items for both the audio_links and release_artists tables. Here's what I have. Output { "title": "Attack The Dancefloor Volume Two", "audiolinks": [ "AudioLinks object (55708)", "AudioLinks object (55709)", "AudioLinks object (55710)", "AudioLinks object (55711)" ], "releaseartists": [ "ReleaseArtists object (140)", "ReleaseArtists object (141)" ] } models.py class AudioLinks(models.Model): release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id', related_name='audiolinks') track_number = models.IntegerField() class Meta: managed = False db_table = 'audio_links' class ReleaseArtists(models.Model): release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id', related_name='releaseartists') artists = models.CharField(max_length=100) class Meta: managed = False db_table = 'release_artists' views.py class ListReleaseDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = ReleasesAll.objects.all() serializer_class = ReleasesSerializer def get(self, request, *args, **kwargs): try: a_release = self.queryset.prefetch_related('releaseartists','audiolinks').get(pk=kwargs['release_id']) return Response(ReleasesSerializer(a_release).data) except ReleasesAll.DoesNotExist: return Response( data = { "message": "{} does not exist".format(kwargs["release_id"]) }, status=status.HTTP_404_NOT_FOUND ) serializers.py class ReleasesSerializer(serializers.ModelSerializer): audiolinks = serializers.StringRelatedField(many=True) releaseartists = serializers.StringRelatedField(many=True) class Meta: model = ReleasesAll fields = ('title','audiolinks','releaseartists') -
Calculate an average value for each month
I try to calculate the average amount for each month for the 13 last month. So I have a card with the date which has many amounts which are linked to a category. For example my card 1 has an amount for category A, an amount for category B an amount for category C .... Amount, Card and Category have their own class in the model. My objective is to calculate for one category, the average amount for each 13 last month. Here is my model: class Card(models.Model): date = models.DateField(auto_now_add=False, null=False) day = models.IntegerField(null=False) comment = models.TextField(null=False) worked = models.BooleanField(default=True) def __str__(self): return "<id={}, date={}, day={}, comment={}, worked={}>".format( self.id, self.date, self.day, self.comment, self.worked ) class Category(models.Model): name = models.CharField(max_length=100) icon = models.CharField(max_length=50) order = models.IntegerField(null=False, unique=True) image = models.CharField(max_length=255) def __str__(self): return "<id={}, name={}, icon={}>".format(self.id, self.name, self.icon) class Amount(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2) card = models.ForeignKey(Card, on_delete=models.CASCADE, related_name='amounts') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='amounts') def __str__(self): return "<id={}, amount={}>".format(self.id, self.amount) And I have really no idea of how to do this. Thanks for your help -
Polymorphic (derived model referred) model inheritance in Django
I have the following inheritance structure of my Django models: Transaction SimpleTransaction SubscriptionTransaction Item SimpleItem SubscriptionItem The model SimpleTransaction refers to the model SimpleItem and the class SubscriptionTransaction refers to the model SubscriptionItem. The most obvious way to do this is to define item field in Transaction: class Transaction(models.Model): # ... item = models.ForeignKey('Item') # ... But I would like t.item to refer to SimpleItem or SubscriptionItem (not the base class Item as in the above code) dependently on whether t is SimpleTransaction or SubscriptionTransaction. What are the ways to do this in Django? Or maybe referring to a derived class (SimpleItem or SubscriptionItem) instead of Item may somehow impact performance badly, as it would request to read SimpleItem or SubscriptionItem even when just Item fields are needed? and so better to refer to the base class and not to invent a question like this? However having references to a particular Item-derived class (not just Item base class) from either SimpleTransaction or SubscriptionTransaction benefits referential integrity. So should I do this to improve the DB "stability"? -
Simple query in Django
I'm trying to do a RAW Query like this: User.objects.raw("SELECT username FROM app_user WHERE id != {0} AND LOWER(username) LIKE LOWER('%{1}%')".format('1','john')) I get this error: django.db.utils.ProgrammingError: not enough arguments for format string The query works perfectly in SQLite but does not work in MySQL. -
aligning links horizontally css & Django
I seem to be having problems aligning my links so that they align horizontally. (see image below) I thought using display: inline-block would allow the links to align. The text above the links is whats causing the links to display at different levels. Any help would be appreciated. index.html <h1 class="row--gutters">Recent Posts</h1> {% for entry in entries %} <div class="row__3"> <div class="row--gutters"> <h2 class="recent-posts__title">{{ entry.topic }}</h2> <p class="recent-posts__text">{{ entry }}</p> <a href="{% url 'blogging_logs:topic' entry.topic_id %}" class="recent-posts__link">Continue Reading</a> </div> </div> {% empty %} <li> empty </li> {% endfor %} _recent-posts.css .recent-posts { &__title { font-size: 1.4rem; } &__text { font-size: 1rem; padding-bottom: 20px; } &__link { position: absolute; display: inline-block; text-decoration: none; } } _row.css .row { @mixin clearfix; &__3 { float: left; width: 25rem; @mixin atSmall { width: 35rem; margin-left: auto; margin-right: auto; } @mixin atMedium { float: left; width: 33.33%; } } &--gutters { padding-left: 2rem; padding-right: 4rem; text-align: left; } } -
django - Generate multiple PDF files in a loop condition using reportlab
I am in a django project and trying to generate multiple PDF files in a loop condition using reportlab. view.py def pdftest(request, *args, **kwargs): if request.method == 'POST': for x in range(0, 3): response = HttpResponse(content_type='application/pdf') buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=portrait(letter)) elements = [] ptext = 'Hellow World! --- %s' %x styles=getSampleStyleSheet() elements.append(Paragraph(ptext, styles['Normal'])) doc.build(elements) response['Content-Disposition'] = 'attachment; filename="{}"'.format('test.pdf') pdf = buffer.getvalue() buffer.close() response.write(pdf) return response context = {} context['title'] = 'PDF TEST' return render(request, 'companies/pdftest.html', context) But my program produce only one PDF. Do you have any idea about this problem? -
how to run app django channels with supervisor and gunicorn or daphne
I have a problem with my configuration from supervisor, my app is using django_channles well, when I run my app using of two codes below working well (myenv)/colonybit/colonybitbasics/python manage.py runserver 0.0.0.0:8000 or (myenv)/colonybit/colonybitbasics/daphne -b 0.0.0.0 -p 8000 and I have other app in vuejs, the code above is working, but when I try run my app with this code below like this (myenv)/colonybit/ ./bin/start.sh my file start.sh NAME="colony_app" DJANGODIR=/home/ubuntu/colonybit # Django project directory SOCKFILE=/home/ubuntu/colonybit/run/gunicorn.sock USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=colonybit.settings DJANGO_WSGI_MODULE=colonybit.asgi # ASGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ubuntu/colonybit/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec colonybit ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=0.0.0.0:8000 \ --log-level=debug \ --log-file=- the server is running well, but my app in vuejs, show me an error 500, can't cossuming my app in django_channels please told me, how to config my file start.sh for working using ASGI thanks for your time. -
Adding SumoSelect to Django
Hey I have been trying to add a dropdown with checkbox but I can only get to this point here where the widget is not applying stylesheets from my sumoselect.html. What I am going towards is this. Here is the repo for the sumoselect I am trying to use https://github.com/HemantNegi/jquery.sumoselect and I here is my hierarchy: Top Level ---|core ---|workItem ---|static ---|js ---|jquery-3.3.1.js ---|sumoselect folder Does anyone have any idea of how to fix this to apply the style sheets from the sumoselect folder sumoselect.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="{% static 'js/sumoselect/jquery.sumoselect.js' %}"> </script> <link rel="stylesheet" href="{% static 'js/sumoselect/sumoselect.css' %}"/> <script type="text/javascript"> $(document).ready(function () { window.test = $('.testsel').SumoSelect({okCancelInMulti:true, captionFormatAllSelected: "Yeah, OK, so everything." }); }); </script> <style type="text/css"> body{font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color:#444; font-size:13px;} p,div,ul,li{padding:0px; margin:0px;} </style> </head> <body> <form method="get"> <br /> <select multiple="multiple" placeholder="Hello im from placeholder" class="testsel"> <option selected value="volvo">Volvo</option> <option value="saab">Saab</option> <option disabled="disabled" value="mercedes">Mercedes</option> <option value="audi">Audi</option> <option value="bmw">BMW</option> <option value="porsche">Porche</option> <option value="ferrari">Ferrari</option> <option class="someclass" value="audi">Audi</option> <option class="someclass" value="bmw">BMW</option> <option class="someclass" value="porsche">Porche</option> <option value="ferrari">Ferrari</option> <option value="audi">Audi</option> <option value="bmw">BMW</option> <option value="porsche">Porche</option> <option value="ferrari">Ferrari</option> <option value="hyundai">Hyundai</option> <option value="mitsubishi">Mitsubishi</option> </select> </form> <br> </body> </html> backlog.html {% extends 'base.html' %} {% load django_tables2 … -
Postgres django.db.utils.OperationalError: could not connect to server: Connection refused
Trying to run my django server in a docker, but the postgres port is already being used? When I run "docker-compose up", I receive this error: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py migrate' returned a non-zero code: 1 sudo service postgresql status returns: 9.6/main (port 5432): online sudo lsof -nP | grep LISTEN returns: postgres 15817 postgres 3u IPv4 1022328 0t0 TCP 127.0.0.1:5432 I tried to run "sudo kill -9 15817", but docker-compose up still receives the same error. -
Elasticbeanstalk; How to authorize to create laod balancer?
I'm trying to deploy my Django project into eb. But this error happened when I create the environment. ERROR Creating load balancer failed Reason: API: elasticloadbalancing:CreateLoadBalancer User: is not authorized to perform: iam:CreateServiceLinkedRole on resource role/aws-service-role/elasticloadbalancing.amazonaws.com/AWSServiceRoleForElasticLoadBalancing I'm doing with IAM user so I need to add permissions manually. But I don't know the permission to do this. Which permissions do I need to add to deploy and manage project comfortably? Currently I just added AWSS3FullAccess and AWSElasticbeanstalkFullAccess.