Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Override form.errors messages on UserCreationForm
I'm trying to override (add languages) the messages of form.errors. I've tried this: forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(CreateUserForm, self).__init__(*args, **kwargs) self.error_messages['duplicate_username'] = 'some message' After the form is submitted, it's not saved because username are unique and the error is displayed on the template. I'd like to make the same with the password but I can't find out the errors' key for each password validation. Can you provide me it? -
How can i inspect the db again in django?
I created my class in models.py with python manage.py inspectdb how can i generate new class if exists somebody new table in db -
Display success message in Django after download
I am trying to trigger a download of an AWS S3 object using Django 3. views.py def pagelanding(request,slug): if some_condition: URL='URL_to_s3_file' return redirect(URL) So far everything works fine, when I trigger the condition in my template, the download is triggered. The problem is that I would like to display a success message. Since the redirect is occupied by the download directive, I can't for example use the Django messages framework on the template. Is there any way to trigger the download and display the message at the same time? -
Docker with Django/Wagtails has a critical error
I am trying to build a Docker image with a Django/Wagtails site, including API endpoints. This works locally, however when I try to build a Docker image and push it up, it throws an error. Here's what my Dockerfile looks like: FROM python:3.7 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ default-libmysqlclient-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools \ vim \ ffmpeg # Set environment varibles ENV PYTHONUNBUFFERED 1 ENV DJANGO_ENV dev COPY ./requirements.txt /code/requirements.txt RUN pip install --upgrade pip # Install any needed packages specified in requirements.txt RUN pip install -r /code/requirements.txt RUN pip install gunicorn # Copy the current directory contents into the container at /code/ COPY . /code/ # Set the working directory to /code/ WORKDIR /code/ RUN python manage.py migrate RUN useradd wagtail RUN chown -R wagtail /code USER wagtail EXPOSE 8000 CMD exec gunicorn appname.wsgi:application --bind 0.0.0.0:8000 --workers 3 If desired, I can put my settings file, my api.py and my urls.py file, but none of them are changed from my local copy which works. Here's the error I get: AttributeError: 'WSGIRequest' object has no … -
Django - Return Object of Arrays
I'd like to have my API endpoint send data in the format {'column_name1': [result_array1],'column_name2': [result_array2]} -
error: No module named 'register.forms', using crispy-forms django
I am trying to install a django user registration module in crispy-forms and I am getting the error: No module named 'register.forms' The exact line giving me issues appears to be from .forms import RegisterForm I do have crispy-forms installed (secret) user@client:~/www/src/exchange $ pip3 install django-crispy-forms Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple Requirement already satisfied: django-crispy-forms in /home/kermit/Env/secret/lib/python3.7/site-packages (1.9.0) . (secret) user@client:~/www/src/exchange $ cat register/views.py from django.shortcuts import render, redirect #from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("home/") else: form = RegisterForm() form = UserCreationForm() return render(response, "register/register.html",{"form":form}) (secret) user@client:~/www/src/exchange $ cat register/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate #from django.models import models class RegisterForm(UserCreationForm): email = models.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] . (secret) user@client:~/www/src/exchange $ cat exchange/urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view, user_view from userdash.views import userdash_detail_view, userdash_create_view from django.conf.urls import include from register import views as v from pages import views urlpatterns = [ path('', views.home_view, name='home'), path('', … -
(pre-receive hook declined) while deploying on heroku
When I try git push heroku master, this error pops up ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/web--dev.git' Also this is in my settings.py file where it can be an error import dj_database_url from decouple import config DATABASE = { 'default': dj_database.config( default=config('DATABASE_URL') ) } -
Now able to register using class based view.?
I want to work with company model where i am to register using subdomain and have to login using that same domain name. I created a model using following fields : models.py class Company(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=2000) sub_domain = models.CharField(max_length=30) user_limit = models.IntegerField(default=5) country = models.CharField(max_length=3, choices=COUNTRIES, blank=True, null=True) And my registration form is like something below: forms.py class RegistrationForm(forms.ModelForm): class Meta: model = Company fields = ['name', 'address', 'sub_domain', 'country'] def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs = {"class": "form-control"} But when it comes to views i dont know how to handle class based views and as i am a newbie facing problem to save data in db. views.py class RegistrationView(CreateView): model = Company form_class = RegistrationForm template_name = "company_register.html" def is_valid(self, form): company = Company.objects.create_company(form.cleaned_data['name'], form.cleaned_data['address'], form.cleaned_data['sub_domain'], form.cleaned_data['country']) company.save() return super(RegistrationView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(RegistrationView, self).get_context_data(**kwargs) Please someone help!!! -
TemplateSyntaxError while using typeform sdk to pass url parameter to class
I am using Django. I have pip installed typeform sdk using https://pypi.org/project/django-typeform/ I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0 But this gives me Exception Type: TemplateSyntaxError Exception Value: 'sekizai_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache django_typeform i18n l10n log static tz -
Type error Exception Value: 'Profile' object is not iterable
Not sure what's going wrong here. IF two users have both voted yes to each other, hence both having a vote attribute of True, I am attempting to add both of them to my matches database. But it's not working and I'm not clear why the Profile object is not iterbale. It works fine in my other methods when I try to get it this sort of way. traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 167, in create_vote npm = Profile.objects.get(request.user) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get clone = self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1187, in build_filter arg, value = filter_expr File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 257, in inner return func(self._wrapped, *args) TypeError: … -
After successfully installing mysql and mysql workbench i get this error message each time i run the pip install mysql-python command on virtualenv
ERROR: Command errored out with exit status 1: command: /Users/ebrima/Documents/djangoapp/computerinventory/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"'; file='"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-record-QYXGl9/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ebrima/Documents/djangoapp/computerinventory/venv/include/site/python2.7/mysql-python cwd: /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/ -
Unable to trigger Ajax click function in Django
Trying to update a model based on which download link was pressed in Django. Please see current code below, so fair it doesn't appear to be logging to console either. From profile.html {% for x in source %} {% if forloop.counter <= 4 %} <div class="content-section"> <div class="media-body"> <h2 class="account-heading">{{ x.video_id }}</h2> {% for y in records %} {% if x.video_id == y.sourcevideo.video_id %} <div class="media-body"> <video width="320" height="240" controls> <source src="{{ y.highlight.url }}" type="video/mp4"> Your browser does not support the video tag </video> <br> <a class="btn" id="download" href="{{ y.highlight.url }}" data-id="{{ y.highlight_id }}" download>Download</a> </div> {% endif %} {% endfor %} </div> </div> {% endif %} {% endfor %} <script type="text/javascript"> $("#download").click(function() { console.log( $(this).attr("data-id") ); var catid; catid = $(this).attr("data-id"); $.ajax({ type:"POST", url: "/downloaded", data: { highlight_id: catid }, success: function( data ) { console.log(data) } }) }) </script> From views.py def downloaded(request): if request.method == 'POST': highlight_id = request.GET('highlight_id') downloadedvideo = Highlight.objects.get(pk=highlight_id) downloadedvideo.used = True downloadedvideo.save() return else: return Any help is greatly appreciated! -
Django generic detail view must be called with an object pk or a slug but my URL has a PK already
AttributeError at /mini_fb/profile/1/delete_status/14 Generic detail view DeleteStatusMessageView must be called with either an object pk or a slug in the URLconf. Isn't my PK 1 and 14 already in the URL? Why am I getting this error? <a href="{% url 'delete_status' profile_pk=profile.pk status_pk=x.pk %}">delete</a> class DeleteStatusMessageView(DeleteView): '''A class for the view for deleting status messages.''' template_name = 'mini_fb/delete_status_message.html' queryset = StatusMessage.objects.all() def get_context_data(self, **kwargs): '''Return a dictionary with context data for this template to use.''' context = super(DeleteStatusMessageView, self).get_context_data(**kwargs) st_msg = StatusMessage.objects.get(pk=self.kwargs['status_pk']) context['st_msg'] = st_msg return context # return the dictionary -
User Serializer is showing null in AJAX fetch but shows data in DRF
I have below the details of my serializer for the current user serializers.py class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'email', 'first_name', 'last_name', ] views.py class UserViewSet(APIView): def get(self, request): serializer = UserDetailSerializer(request.user) return Response(serializer.data) urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^user/', accounts_views.UserViewSet.as_view()), ] going to http://localhost:8000/user/ shows the proper json/api data: { "id": 1, "username": "stormadmin", "email": "", "first_name": "", "last_name": "" } but when I try to use ajax to fetch the data: async getUser() { const response = await fetch('http://127.0.0.1:8000'+'/user/'); const resData = await response.json(); return resData; } I get this instead: {id: null, username: ""} My question is, how do I get the data I want with an AJAX call? Or is there a better way to do this? -
How to return a template from a function without the request argument?
I am not sure if this makes any sense but I am trying to figure out a way to get a function without request argument to return an HTML template. The code below will help you better understand my point. views.py def home(request): global running, row_count, thread if request.method == 'POST': row_count = 0 thread = threading.Thread(target=fun) thread.daemon = True thread.start() running = True return render(request, 'scraper/home.html', {'countries': countries, 'running': running}) else: return render(request, 'scraper/home.html') def fun(): global row_count, finished, thread while True: row_count += 5 if row_count == 15: finished = True thread.join() return time.sleep(5) What I am trying to achieve is to reflect that finished=Truein my 'scraper/home.html/ template. I want to make an element in my template based on the value of finished. Something like this: scraper/home.html {% if finished %} <p>Finished!</p> {% endif %} I'll appreciate your help on this. Thanks -
Django schema explorer simple recursive algorithm - confused by results / how to fix
I am using Django and have a couple of use cases for which the ability for objects to trace their relationships through several models is required. I don't want to hand-code this functionality for every model. Some example models: class Project(models.Model): project_name = models.CharField(max_length=200, default="development_project") class Question(models.Model): project = models.ForeignKey(Project, default=1, on_delete=models.CASCADE) question_text = models.CharField(max_length=200, default="question text") class Extra(models.Model): extended_q = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) summary_of = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) content = models.CharField(max_length=200, default="simple summary") class Answer(models.Model): question = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) Using models as nodes of a network and relationships as edges, this seems like it should be manageable, but for some complexity where there are 'redundant' edges - do we permit an Extra to summarise Answers from a different project? my use cases will be: a models.Manager class that can act as the default manager for a sub-class of Django apps that work together in a unified site and help do the sort of row-separating management that will keep users, even in the admin, from getting under each others feet. an overall app using ContentTypes that can help the user build datasets and organise tables for dataframes (taking fks and making them appropriate category … -
Label and input value overlaps with django-material and datepicker
So the idea is that I need a pop-up and in that pop-up there should be a form in which you have to choose the date, so the pop-up have a Form object with a TextField that emulates the a date input to use the datepicker of material, the problem comes with the label of that input that overlaps with the input itself like this. I tried using javascript to add the class "active" to the label when you click the input because that is what triggers the label to go up but it doesn't recognize it and doesnt apply the class. The html renders like this: <div class="input-field col s12 required" id="id_fecha_cobro_container"> <i class="material-icons prefix">insert_invitation</i><input id="id_fecha_cobro" name="fecha_cobro" type="date"> <label for="id_fecha_cobro">Fecha de Cobro</label> </div> This is the modal in django: {% block change_form %} {% form %} {% part form.fecha_cobro prefix %}<i class="material-icons prefix">insert_invitation</i>{% endpart %} {% endform %} {% prepopulated_fields_js %} {% endblock %} This is the form class: class AvisoVacacionForm(forms.Form): fecha_cobro = forms.DateField(label="Fecha de Cobro", required=True, widget=forms.TextInput(attrs={'type': 'date'})) def __init__(self, *args, **kwargs): super(AvisoVacacionForm, self).__init__(*args, **kwargs) This is what I've tried using javascript: $('#id_fecha_cobro').click(function(){ $("label[for='id_fecha_cobro']").addClass("active") }); -
I can't sort the date in the dictionary
I want to sort by the dictionary in my hand both by key and by year / month in it, but I could not {'120000.0': [['2020/01', 97000.0], ['2020/03', 98000.0], ['2020/02', 'null']], '150000.0': [['2020/01', 113750.0], ['2020/02', 97875.0], ['2020/03', 'null']], '180000.0': [['2020/02', 105083.33333333333], ['2020/03', 'null'], ['2020/01', 'null']], '30000.0': [['2020/02', 129000.0], ['2020/03', 179500.0], ['2020/01', 'null']], '60000.0': [['2020/02', 145700.0], ['2020/03', 155250.0], ['2020/01', 'null']], '90000.0': [['2020/02', 135000.0], ['2020/03', 158000.0], ['2020/01', 'null']]} I want to: { '30000.0': [['2020/01', 'null'],['2020/02', 129000.0], ['2020/03', 179500.0] ], '60000.0': [['2020/01', 'null'],['2020/02', 145700.0], ['2020/03', 155250.0] ], .... } -
integrity error: UNIQUE constraint failed: dating_app_uservote.user_id, dating_app_uservote.voter_id Django
Not sure what's going wrong here. IF two users have both voted yes to each other, hence both having a vote attribute of True, I am attempting to add both of them to my matches database. But it's not working and I'm not clear why. views.py/create_vote def create_vote(request, profile_id, vote): profile = Profile.objects.get(pk=profile_id) UserVote.objects.create( user=profile, voter=request.user, vote=vote ) if vote: if UserVote.objects.filter( user = request.user, voter=profile, vote=True ).count(): npm = Profile.objects.get(user=request.user) npm.matches.add(User.objects.get(username=profile.username)) npm = Profile.objects.get(user=profile) npm.matches.add(User.objects.get(username=request.user)) npm.save() return render(request, 'dating_app/matches.html', dict( match=profile, )) return redirect('dating_app:mingle') models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Profile(AbstractBaseUser): class Meta: swappable = 'AUTH_USER_MODEL' email = models.EmailField(verbose_name="email") username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = … -
MOD_WSGI Apache2 You don't have permission to access this resource
I am working on deploying a Django project with apache2 and MOD_WSGI. When I run the server, I am unable to access the website and I get the error on the site, Forbidden You don't have permission to access this resource. Apache/2.4.29 (Ubuntu) Server at testnexusstudy.com Port 8081 I have set up everything I think I need like the conf file, <VirtualHost *:8081> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Include conf-available/serve-cgi-bin.conf Alias /static /root/StudBud1/static <Directory /root/StudBud1/static> Require all granted </Directory> Alias /media /root/StudBud1/media <Directory /root/StudBud1/media> Require all granted </Directory> <Directory /root/StudBud1/StudBud1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /root/StudBud1/StudBud1/wsgi.py WSGIDaemonProcess StudBud1 python-path=/root/StudBud1 WSGIProcessGroup StudBud1 </VirtualHost> I have given all the permissions I thought were required for apache and here is my ls -la drwxrwxr-x 12 root www-data 4096 Apr 5 19:36 StudBud1 -rw-rw-r-- 1 root www-data 204800 Apr 5 19:36 db.sqlite3 Hopefully, some of you have experience with this type of error. -
Can't redirect to category list url - django
I'm so sorry for this silly issue, I'm learning django so I might have these issues, please take a look at my codes actually i can't figure out how can i redirect to category list page but url is working fine i just can't able to add correct redirect url by id into href tag :( html <div class="widget widget-catgs"> <h3 class="widget-title">Categories</h3> <ul> {% for cat in category %} <li> <a href="**{% url 'category-list' property.category.id %}**" title=""><i class="la la-angle-right"></i><span>{{ cat.category__title }}</span></a> <span>{{ cat.category__title__count }}</span> </li> {% endfor %} <!-- <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Condo</span></a> <span>15</span> </li> <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Townhouse</span></a> <span>4</span> </li> <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Coop</span></a> <span>1</span> </li> --> </ul> </div> views.py def property_by_category(request, category_id): property_list = Property.objects.all() category = get_object_or_404(Category, pk=category_id) category_list = Property.objects.filter(category=category) context = { 'category_list': category_list, 'category_name': category, 'property': property_list } return render(request, 'property/property-category.html', context) urls.py urlpatterns = [ path('', views.property, name='property-page'), path('details/<int:property_id>', views.property_details, name='property-details'), path('category/<int:category_id>', views.property_by_category, name='category-list'), path('add-property/', views.add_property, name='add-property'), ] -
How to show images using Lightbox in Django
I need your little help. I have set up everything according to the course that I am following but I am not getting images shown as in the course. Here is the issue: I have fetched some images from database and I want to show them using lightbox. I did everything right but images are not showing. My views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator from .models import Listing def listing(request, listings_id): listing = get_object_or_404(Listing, pk=listings_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) My listing.html {% extends 'base.html' %} {% load humanize %} {% block content %} <!-- Listing --> <section id="listing" class="py-4"> <div class="container"> <a href="{% url 'listings' %}" class="btn btn-light mb-4">Back To Listings</a> <div class="row"> <div class="col-md-9"> <!-- Home Main Image --> <img src="{{ listing.photo_main.url }}" alt="" class="img-main img-fluid mb-3"> <!-- Thumbnails --> <div class="row mb-5 thumbs"> <div class="col-md-2"> <a href="{{ listing.photo_1.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_1.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_2.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_2.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_3.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_3.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_4.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_4.url … -
Build an API with Django that display data based on user input
I am struggling with the structure of my api supposed to display a chart from a model primary key. The underlying issue that I have is to write a view that render attributes from the same model as the PK entered by the user and then pass it along with Ajax view.py class forecast(APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_res', None) data = {} if query and request.method == 'GET': reference = Item.objects.filter(reference = query) forecast1 = Item.objects.filter(reference = query).values('demand_30_jours') forecast2 = Item.objects.filter(reference=query).values('Lt2') forecast3 = Item.objects.filter(reference=query).values('Lt3') data.update({'reference': reference, 'forecastdata': [forecast1,forecast2,forecast3] }) return Response(data) and here is my graph on the html page <script> $(document).ready(function() { var endpoint = 'api/chart/forecast' var forecastdata = [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, data: {'search_res' : $('search_res').val(),}, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { labels: reference, datasets: [{ label: 'item demand planning', data: forecastdata, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, … -
Bootstrap caroussel not showing at all in home page (wagtail)
{# templates/home/home_page.html #} {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block content %} {% image self.banner_image width-3560 as img %} <div class="jumbotron" style="background-image: url('{{ img.url }}'); min-height: 400px; height: 40vh; background-size: cover; background-position: center top; display: flex; flex-direction: column; justify-content: center;"> <h1 class="display-4">{{ self.banner_title }}</h1> <div class="lead">{{ self.banner_subtitle|richtext }}</div> {% if self.banner_cta %} <a class="btn btn-primary btn-lg" href="#" role="button">@todo</a> {% endif %} </div> {# Example of an Orderable from home/models.py #} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for loop_cycle in self.carousel_images.all %} {% image loop_cycle.carousel_image fill-900x400 as img %} <div class="carousel-item{% if forloop.counter == 1 %} active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% for block in page.content %} {% include_block block %} {% endfor %} {% endblock %} -
HTTPConnectionPool(host='0.0.0.0', port=5000): Max retries exceeded with url
I am encountering this error, when i try to make a call to a service that is deployed using docker-compose on port 5000 from a django application also deployed using docker-compose on port 8000. I am also using nginx. ConnectionError at /documents/ HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /api/documents (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f976607f290>: Failed to establish a new connection: [Errno 111] Connection refused')) Here's the request object right before the request is made kwargs {'data': None, 'files': {'file': ('XXX', <InMemoryUploadedFile: XXX.pdf (application/pdf)>, 'application/pdf', {})}, 'headers': {'Authorization': 'Token token=XXX', 'Content-Type': 'application/pdf', 'PSPDFKit-API-Version': '2020.1.3'}, 'json': None} method 'post' session <requests.sessions.Session object at 0x7f954da972d0> url 'http://127.0.0.1:5000/api/documents' Here are the relevant files docker-compose version: '3.7' services: web: build: context: ./www dockerfile: Dockerfile.prod command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 volumes: - ./www:/usr/src/app - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: env.prod nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web pspdfkit: image: "pspdfkit/pspdfkit:2020.1" environment: PGUSER: XXX PGPASSWORD: XXX PGDATABASE: XXX PGHOST: db PGPORT: 5432 # Activation key for your PSPDFKit Server installation. ACTIVATION_KEY: XXXX # Secret token used for authenticating API requests. API_AUTH_TOKEN: XXXX # Base key …