Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template View received post of other url and not display data
Okay, my problem is about context data that is not displayed in the template. First of all, I am pretty new in Django and js programing. I have a first page with data sending, using ajax success (I have ajax for other needs in this page). Following, my templateView class : class displayResultPage(TemplateView): template_name = 'result.html' filename = 'None' protol_file = 'None' def get_context_data(self, **kwargs): kwargs = super(displayResultPage, self).get_context_data(**kwargs) kwargs["filename"] = self.filename kwargs["protocol_file"] = self.protol_file return kwargs def post(self, request, *args, **kwargs): self.filename = copy.deepcopy(request.POST.get("img_path")) self.protol_file = copy.deepcopy(request.POST.get("json_path")) context = self.get_context_data(**kwargs) #try without get_context_data defined to add element in the context #context["filename"] = copy.deepcopy(request.POST.get("img_path")) #context["protocol_file"] = copy.deepcopy(request.POST.get("json_path")) #second try with same goal #kwargs = { # "filename": self.filename, # "protol_file": self.protol_file, #} return self.render_to_response(context) I want to send to the templace the filename and the protocol file (name). When I redirect to this new page (result.html), data are not passed. So, I try to find a way to do it. First of all, I had to defined the post method to received these data. With the debugger, the break point stop in the post function. Here, the request.POST is okay and I have data inside. After that, the step is … -
How can I order a table in Django without refreshing the whole page?
There is a feature in a Django application I'm working on that allows users to search the database by things like customer name, invoice number etc. The search result is rendered as a Django table which gives an array of results with several columns such as "Expiry Date", "Product Name", "Issue Date" etc. My problem is however, that if I click on a column name (so that we can order the results as desired) the entire page gets refreshed and all the results are gone and the form has been cleared - which is definitely not what we want! Is there a way to fix this using DJango? Or am I better off using another web application language for this feature? If so, which one? -
Execute several scripts at the same time in the background
I have a page where the user selects a Python script, and then this script executes. My issue is that some scripts take a while to execute (up to 30m) so I'd like to run them in the background while the user can still navigate on the website. I tried to use Celery but as I'm on Windows I couldn't do better than using --pool=solo which, while allowing the user to do something else, can only do so for one user at a time. I also saw this thread while searching for a solution, but didn't manage to really understand how it worked nor how to implement it, as well as determine if it was really answering my problem... So here is my question : how can I have multiple thread/multiple processes on Celery while on Windows ? Or if there's another way, how can I execute several tasks simultaneously in the background ? -
Django Many to Many 'QuerySet' object has no attribute 'members'
First, here is my Location model. It has one ManyToManyField called members. Model: class Location(models.Model): name = models.CharField(max_length=200) # ... members = models.ManyToManyField(User, related_name="members") # ... (Note, "# ..." replaces more fields) And then in a view I did this. DetailView class LocationDetailView(DetailView): model = Location context_object_name = "location" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) location = Location.objects.filter(pk=self.get_object().pk) context["members"] = location.members.all() return context Error 'QuerySet' object has no attribute 'members' -
Is there a Django ManyToManyField with implied ownership?
Let's imagine I'm building a Django site "CartoonWiki" which allows users to write wiki articles (represented by the WikiArticle-model) as well as posting in a forum (represented by the ForumPost-model). Over time more features will be added to the site. A WikiArticle has a number of FileUploads which should be deleted when the WikiArticle is deleted. By "deleted" I mean Django's .delete()-method. However, the FileUpload-model is generic -- it's not specific to WikiArticle -- and contains generic file upload logic that e.g. removes the file from S3 when it's removed from the database. Other models like ForumPost will use the FileUpload-model as well. I don't want to use GenericForeignKey nor multi-table inheritance for the reasons Luke Plant states in the blog post Avoid Django's GenericForeignKey. (However, if you can convince me that there really is no better way than the trade-offs GenericForeignKey make, I might be swayed and accept a convincing answer of that sort.) Now, the most trivial way to do this is to have: class FileUpload(models.Model): article = models.ForeignKey('WikiArticle', null=True, blank=True, on_delete=models.CASCADE) post = models.ForeignKey('ForumPost', null=True, blank=True, on_delete=models.CASCADE) But that will have the FileUpload-model expand indefinitely with more fields -- and similar its underlying table will gain more … -
How to replace values between two curly brackets in python?
I want to replace values in strings between two curly brackets. e.g: string = f""" my name is {{name}} and I'm {{age}} years old """ Now I want to replace name, and age by some values. render_param = { "name":"AHMED", "age":20 } so the final output should be. my name is AHMED and I'm 20 years old. -
Unable install Django through Dockerfile
when I run 'docker build .' command, "ERROR: Invalid requirement: 'Django=>4.0.4' (from line 1 of /requirements.txt) WARNING: You are using pip version 22.0.4; however, version 22.1 is available. You should consider upgrading via the '/usr/local/bin/python -m pip install --upgrade pip' command." this error shows up. I have upgraded pip to the latest version. When I check version of pip , it shows 22.1. But when I run docker build command again, nothing changes. I have upgraded from this /usr/local/bin/python location. but still nothing changed. I am using Ubuntu 20.04, python version is 3.8. -
Django "SQLite 3.9.0 or later" error Cronjob
I'm trying to schedule a database import for Django with Crontab. The script looks as following: #!/usr/bin/python3 import csv import os from app.models import AppData path = "/home/ec2-user/PolisCheckV2/UpdateUploadCSV/VvAA/CSV/" os.chdir(path) with open('AppData.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: p = AppData(klantnummer=row['1'], huisnummer=row['2'], postcode=row['3'], polisnummer=row['4']) p.save() exit() When I run the script on its own, everything works perfectly. However, when I'm running it scheduled through Crontab, the following mail appears in /var/spool/mail: File "/home/ec2-user/project/manage.py", line 22, in <module> main() File "/home/ec2-user/project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/ec2-user/.local/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/ec2-user/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/ec2-user/.local/lib/python3.7/site-packages/django/db/models/base.py", line 122, in … -
How to use jinja2 with django mako template tutor openedx
I'm trying to build an openedx platform with comprehensive theming. The documentation has indicated that I need to follow the same path as the original file in my theme folder. The problem is that when I try to build a new image of the openedx with my new theme I get a jinja2 template exception regarding the logout.html file. knowing that openedx requires jinja2 to work properly I need to find a workaround to this error. my logout.html file : {% extends "main_django.html" %} {% load i18n %} {% load static %} {% load django_markup %} {% block title %}{% trans "Signed Out" as tmsg %}{{ tmsg | force_escape }} | {{ block.super }} {% endblock %} {% block body %} <link rel="stylesheet" href="{% static 'css/bootstrap/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/partials/lms/theme/logout.css' %}"> <div class="logout-wrapper"> {% if show_tpa_logout_link %} <h1>{% trans "You have signed out." as tmsg %}{{ tmsg | force_escape }}</h1> <p style="text-align: center; margin-bottom: 20px;"> {% blocktrans trimmed asvar sso_signout_msg %} {start_anchor}Click here{end_anchor} to delete your single signed on (SSO) session. {% endblocktrans %} {% interpolate_html sso_signout_msg start_anchor='<a href="'|add:tpa_logout_url|add:'">'|safe end_anchor='</a>'|safe %} </p> {% else %} {% if enterprise_target %} {% comment %} For enterprise SSO flow we intentionally … -
javascript for loop error uncaught type error on .length
I am currently doing a school assignment. The objective is to make a simple social network posting app using Django and JavaScript. JavaScript is used in order to dynamically load posts on the web page and replace HTML parts. I was following a a YouTube lesson https://youtu.be/f1R_bykXHGE to help me. Despite the fact that I have followed the tutorial on by one I am receiving the following Uncaught TypeError: Cannot read properties of undefined (reading 'length')at XMLHttpRequest.xhr.onload ((index):63:28). const postsElement = document.getElementById("posts") // get an html element // postsElement.innerHTML = 'Loading...' // set new html in that element // var el1 = "<h1>Hi there 1</h1>" // var el2 = "<h1>Hi there 2</h1>" // var el3 = "<h1>Hi there 3</h1>" // postsElement.innerHTML = el1 + el2 + el3 const xhr = new XMLHttpRequest() const method = 'GET' // "POST" const url = "/posts" const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.onload = function() { const serverResponse = xhr.response const listedItems = serverResponse.response // array var finalPostStr = "" var i; for (i=0;i<listedItems.length;i++) { console.log(i) console.log(listedItems[i]) } } xhr.send() </script> -
Create a model, List should return all the movies of him, Aggregate total movies he worked (django )
My task was **Create a actor model, List should return all the movies of him, Aggregate total movies he worked Create a genre model, List should return all the movies under the genre, Aggregate total movies Create a movie model, that have name, actors and genre fields. Here actors and genre should be a manytomany relationship ** I have done this models.py from django.db import models class Actor(models.Model): actors = models.CharField(max_length=100) def __str__(self): return self.actors class Genre(models.Model): genre = models.CharField(max_length=100) def __str__(self): return self.genre class Movie(models.Model): name = models.CharField(max_length=100) actors = models.ManyToManyField(Actor) genre = models.ManyToManyField(Genre) def __str__(self): return self.name serializer.py from rest_framework import serializers from .models import Movie,Genre,Actor class ActorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Actor fields = ['url','actors'] class GenreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Genre fields = ['genre'] class MovieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movie fields = ['url','name','actors','genre'] views.py from django.shortcuts import render from rest_framework import viewsets # Create your views here. from .serializers import MovieSerializer,ActorSerializer,GenreSerializer from .models import Movie,Actor,Genre from django.db.models import Count class movie(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer class actor(viewsets.ModelViewSet): queryset = Actor.objects.all() serializer_class = ActorSerializer class genre(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class=GenreSerializer urls.py from django.urls import include, path from rest_framework import routers from .views import * … -
Using external input for a Django rest framework serializer
I have a class with a US cent value. When I serialize it I want to be able to convert it to a dynamically specified other currency. So the class looks like this: class Evaluation(models.Model): sum_in_cents = models.IntegerField() def converted_sum_in_cents(currency_code): currency_code = currency_code.upper() CurrencyConverter().convert(self.sum_in_cents / 100, 'USD', currency_code) ... #other stuff And it has a standard serializer that currently ignores that function: class EvaluationSerializer(serializers.ModelSerializer): class Meta: model = Evaluation fields = '__all__' depth = 1 So how, when using the serializer, should I get the currency_code argument to the converted_sum_in_cents method? (it's passed as a query string in the view) I've tried looking at read_only fields, and to_representation but as far as I can understand they seem to cover only 0-argument function calls. I've also found this thread, which is my fallback plan, but both that thread's author and I are suspicious that if that were the right way of doing something that seems like it must come up a lot, DRF would have included a lot less hacky pathway to doing it. So am I just thinking about this wrong? -
DRF return Response(serializer.data) taking more then 30 seconds to response
This is my view, I have debugged it, and getting query data and serialization takes less time but when I am doing serializer.data it takes almost 30 seconds. I have around 1000 records, and the serializer is very much nested if request.GET.get('venue') and request.GET.get('day'): venue_menu = Q(venue__name=request.GET.get('venue').title()) venue_day = Q(days__name=request.GET.get('day').title()) venue_menu_list = VenueMenu.objects.filter(venue_menu & venue_day) serializer = VenueMenuSerializer(venue_menu_list, many=True) return Response(serializer.data) else: return Response(status.HTTP_404_NOT_FOUND) -
Post, in_memory images files to external API on POST Request
Here is the scenario of this post..... A user will post some images to REST API, I have to get those images and post them to an external API to get scores calculated from an AI Modal. I have found many solutions to post the stored images to an external API, But could not find anything related to in-memory objects, SO I am posting my Solution over here so that it will be easier for someone else next time import requests from rest_framework.exceptions import ValidationError def external_api(img): api_endpoint = 'YOUR_EXTERNAL_API' payload = {} files = [ ('img', (img.get("img").name, img.get('img').file, img.get("img").content_type)) ] headers = {} response = requests.request("POST", api_endpoint, headers=headers, data=payload, files=files) return response #Serializer class ScoreCardSerializer(serializers.ModelSerializer): score_data = serializers.JSONField(read_only=True, required=False) class Meta: model = ScoreCard exclude = ['card_display'] def create(self, validated_data): score_image = validated_data.pop('score_card_image') ai_response = [] for image in score_image: ai = external_api(image) if ai.status_code == 200: ai_response.append(ai.json()) else: raise ValidationError("Server is overloaded. Please try again in few minutes") specie = ScoreCard.objects.create(**validated_data) for image in score_image: Images.objects.create(score_card_id=specie.id, img=image['img']) specie.score_data = ai_response specie.save() return specie -
Postman - Forbidden (CSRF token missing or incorrect.)
Ive been having problems getting started with postman - I've used it before with Spring but its my first time with Django. I have a working website with all URLs working well. When I send a post request in postman to a page that has a csrftoken, I can see the token in the cookies section of the results, but I get the following error in the server output: Forbidden (CSRF token missing or incorrect.): /contact/ I have the token in the headers section I have tried quite a few different solutions from stack overflow such as adding: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... CSRF_COOKIE_SECURE=False#I am over the localhost with http REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), This is what the view looks like def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): ... sending email ... return redirect('contact') return HttpResponse(status=303) return render( request, 'app/contact.html', { 'title':'Contact Us', 'year':datetime.now().year, 'form': form, } ) -
Postgresql long data
I saved on my database postgresql datas example of one column : Column A ---------- a;b;c;d;e;f;g;h;i;j;k;l;m I want to separate this data where there is ";" and different columns like : Column1 Column2 Column3 Column4 ------- ------- ------- ------- a b c d How i can do it please ? -
Serializing custom count field in DRF
I am trying to send a serialized custom field that has that count of all items in a category in a vessel; I am trying to understand why this line works: vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) but this doesnt : vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) serializer.py : class VesselInfoSerializer(serializers.ModelSerializer): vessel_component_count = serializers.IntegerField( source='vessel_components.count', read_only=True ) vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) class Meta: model = Vessel fields = '__all__' models.py class Category(models.Model): name = models.CharField(max_length=150, null=True, blank=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_inventory_category') def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=150, null=True, blank=True) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.CASCADE, related_name='category_items') def __str__(self): return self.name -
How to render context when we open template from S3buckets?
I'm trying to render context in template. But I'm unable to do that. I'm opening my template from bucket and reading. Now how to render context. render_param.update({'name': email.split("@")[0],'email': email}) # html_message = loader.render_to_string(obj.html_template.url, request_data) html_message = default_storage.open(obj.html_template.name, 'r') html_message= f""" {html_message.read()} """ message = EmailMultiAlternatives(subject, html_message, email_host.email, [email]) message.attach_alternative(html_message, 'text/html') messages.append(message) -
How to autopopulate a field in models.py
I have a class named Property with a field property_type, i wana autofill this field when i create one of the other models who have onetoone relationship with Property I want the when i create a Apartment in django admin for exp the property_type in Property should autofill with the "Apartment", when i create Villa in django admin it should autofill with "villa" class Property(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="agent_of_property") district_id = models.ForeignKey(District, on_delete=models.CASCADE) slug = models.SlugField(max_length=255, unique=True) property_type = models.CharField(choices=PROPERTY_TYPE, max_length=20) title = models.TextField(verbose_name="Titulli", help_text="Vendos titullin e njoftimit", max_length=500) description = models.TextField(verbose_name="Pershkrimi", help_text="Vendos pershkrimin",max_length=1000) address_line = models.CharField(verbose_name="Adresa", help_text="E nevojeshme",max_length=255) price = models.IntegerField() area = models.IntegerField() views = models.IntegerField(default=0) documents = models.CharField(verbose_name="Dokumentacioni", help_text="Dokumentat", max_length=255) status = models.BooleanField(default=True) activity = models.CharField(max_length=20, choices=ACTION_OPTION) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Prona" verbose_name_plural = "Pronat" def get_absolute_url(self): return reverse("pronat:property_detail", args=[self.slug]) def __str__(self): return self.title class Apartment(Property): property_id = models.OneToOneField(Property, on_delete=models.CASCADE, parent_link=True, primary_key=True) floor = models.IntegerField(default=0) room_num = models.IntegerField(default=0) bath_num = models.IntegerField(default=0) balcony_num = models.IntegerField(default=0) class Meta: verbose_name = "Apartament" verbose_name_plural = "Apartamentet" def save(self, *args, **kwargs): self.property_type = "Apartment" class Villa(Property): property_id = models.OneToOneField(Property, on_delete=models.CASCADE, parent_link=True, primary_key=True) living_room = models.IntegerField(default=1) floors = models.IntegerField(default=1) room_num = models.IntegerField(default=1) … -
django admin panel is locked after pushing in github repository
i was working on project in react and django and i push it into the github repository. When i pushed it into the github i got an email saying " your django secret key is leaked" . After that all my django database are not working and when i try to login to django admin panel it says "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." I have created other superuser and tried to login but again it doesnot work. I can't find what the problem is maybe somethig went wrong after i pushed the project into the github.please help me to find the problem -
How can I create a react flow page in current django project?
In current I have a django project, it runs typically with html templates. Now I want to add react-flow pages to current project. Example: using standat url: http://127.0.0.1:8000/ops/main/ it is a normal html page with bootstrap navigation. and I want to add new page as http://127.0.0.1:8000/ops/react/xyz_flow to show react flow. and it shouldn't affect the other pages. -
How to Get Count OR Single dot on notification icon when notification comes in Django
I have created notifications API using django-notifications. and notifications successfully send using nofiy.send. But Now, I wish to add count OR dot on this Notification icon. for this 3 icons I have created separate icon.html file and calling it in every html page. and notifications getting on another notifications.html file Here is the icon.html {% if request.session.is_staff %} <div class="col"> <a href="{% url 'my-account' %}"> <h4> <span class="fas fa-user-tie"></span></h4> </a> </div> <div class="col"> <a href="{% url 'notifications' %}"> <h4><span class="fas fa-bell"></span></h4> </a> </div> <div class="col"> <div class="dropdown p-10"> <a id="dropdownMenuButton1" style="cursor: pointer;" data-bs-toggle="dropdown" aria-expanded="false"> <h4><span class="fa fa-envelope"></span></h4> </a> <ul class="dropdown-menu m-10" aria-labelledby="dropdownMenuButton1" style="margin:2px !important"> <li> <a class="dropdown-item" href="{% url 'email-logs' %}" style="padding: 5px !important;"> &nbsp;&nbsp;Email Logs </a> </li> <li> <a class="dropdown-item " href="{% url 'sms-logs' %}" style="padding: 5px !important;"> &nbsp;&nbsp;SMS Logs </a> </li> </ul> </div> </div> {% else %} <div class="col" align="right"> <a href="{% url 'my-account' %}"> <h4> <span class="fas fa-user-tie"></span></h4> </a> </div> <div class="col" align="right" style="padding-right:30px !important"> <a href="{% url 'notifications' %}"> <h4><span class="fas fa-bell"></span></h4> </a> </div> {% endif %} Notifications are getting on notifications.html. here is notifications.html {% for notification in notifications %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body p-2"> <div class="row device"> <div class="col-1"> <h3 … -
Trying to save time input into mysql database using django
i am trying to save data from HTML input into MySql database using Django. Other forms that i created work. My conclusion is that it doesn't work because of time input. I have it converted into datettime python type which should make it work but it still doesn't save. Would you please check my code and see what can be possible the reason for it not saving? views.py file: def employee_view(request): table = employeeModel.objects.all() context = {"table": table} if request.method == "POST": postCopy = request.POST.copy() # to make it mutable postCopy['barberStartTime'] = datetime.strptime('15/05/22 ' + postCopy['barberStartTime'], '%d/%m/%y %H:%M').time() postCopy['barberEndTime'] = datetime.strptime('15/05/22 ' + postCopy['barberEndTime'], '%d/%m/%y %H:%M').time() request.POST = postCopy form = employeeForm(request.POST or NONE) if form.is_valid(): form.save() return render(request, 'accounts/employee.html', context) return render(request, 'accounts/employee.html', context) python employeeModel: class employeeModel(models.Model): barberName = models.CharField(max_length=50) barber_workplace = models.ForeignKey(workplacesModel, on_delete=models.CASCADE) barberStartTime = models.TimeField() barberEndTime = models.TimeField() class barbers: db_table = "home_employeemodel" python employeeForm: class employeeForm(forms.ModelForm): barberStartTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S')) barberEndTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S')) class Meta: model = employeeModel fields = ["barberName", "barber_workplace", "barberStartTime", "barberEndTime"] html input form: (it is part of a table - reason for tr/td tags): <tr> <form method="POST">{% csrf_token %} <td class="id-td" scope="row">---</td> <td class="barberName-td"><input type="text" name="barberName" placeholder="Meno"/></td> <td class="barberWorkplace-td"><input type="number" name="barberWorkplace" placeholder="Mesto"/></td> … -
Error ElasticBeanstalk 100.0 % of the requests are erroring with HTTP 4xx
I created a SSL Certificate and put it in Elasticbeanstalk LoadBalancer Note: Even although I add my SSL Certificate when I enter my domain there's no file in the site, it is like my aplication is not being linked to my domain Note: in Certificate Manager my Certificate status is "ok" When I deploy my application I get: 100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. EB Logs Resume: 172.31.38.25 - - [16/May/2022:07:18:45 +0000] "GET / HTTP/1.1" 400 58062 "-" "ELB-HealthChecker/2.0" "-" 172.31.25.200 - - [16/May/2022:07:18:52 +0000] "GET / HTTP/1.1" 400 58064 "-" "ELB-HealthChecker/2.0" "-" 172.31.38.25 - - [16/May/2022:07:19:00 +0000] "GET / HTTP/1.1" 400 58062 "-" "ELB-HealthChecker/2.0" "-" 172.31.25.200 - - [16/May/2022:07:19:07 +0000] "GET / HTTP/1.1" 400 58064 "-" "ELB-HealthChecker/2.0" "-" -
can't access ojects from dict field in mongoengine as i wants to compare and fetch data from dict filed
def recorded_meal(request ): try : schema = { "meal_plan_id": {'type': 'string', 'required': True, 'empty': False}, "id": {'type': 'string', 'required': True, 'empty': False} } v = Validator() # validate the request if not v.validate(request.data, schema): return Response({'error': v.errors}, status=status.HTTP_400_BAD_REQUEST) meal_plan_id = request.data['meal_plan_id'] id = request.data['id'] consumed_meal = MealPlan.objects(id=meal_plan_id).first() if consumed_meal: clr1 = MealPlan.recipes consumed_meal1 = clr1(id = id ).first() if consumed_meal1: serializer = serializers.MealsPlanInfoSerializer(consumed_meal1, many=False) response = serializer.data print(response) return Response({'data': response}, status=status.HTTP_200_OK) else: return Response({'error': Messages.INVALID_MEAL_ID}, status=status.HTTP_200_OK) except Exception as exception: Logger.objects.create( error=str({'error': 'Something went wrong at Learn', 'response': str(exception)}), path=str('v1/user/learn/detail') ) return Response({'error': str(exception)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) COLLECTION of meal_plan { "_id": { "$oid": "6281e3f868715b78ac782ccd" }, "type": "standard", "round": 1, "week": 1, "day": 1, "recipes": { "breakfast": { "serves": 1, "id": "6281e4c868715b78ac782cce", "image": "Screen-shot-2012-11-30-at-10.08.27-PM11-250x250.png", "title": "Asparagus Egg Bake", "calories": 88 }, "snack": { "title": "Pea and Avocado Dip with Pita Crisps", "calories": 88, "id": "6281e4ed68715b78ac782ccf", "image": "Pea_Avo_Dip_Pita_Crisps_009_MC_LR-250x250.jpg", "serves": 1 }, "lunch": { "serves": 1, "id": "6281e50668715b78ac782cd0", "image": "Zucchini-and-Feta-Slice1-250x250.jpg", "title": "Everything but the Bagel Chicken", "calories": 88 }, "vegan": { "title": "Cleansing Grapefruit & Mint Salad", "calories": 148, "id": "6281e52d68715b78ac782cd1", "image": "Cleansing-Grapefruit-and-Mint-Salad-LR-8999-250x250.jpg", "serves": 1 }, "dinner": { "serves": 1, "id": "6281e53e68715b78ac782cd2", "image": "Screen-Shot-2014-05-30-at-1.42.47-pm-250x250.png", "title": "Roasted Red Bell Pepper and Shrimp", "calories": 88 …