Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app on Azure getting images from static files but not Bootstrap, Jquery or CSS files
Got a Django app deployed on Azure with this structure: wwwroot |---Myproject |---manage.py |---oryx-manifest.toml |---hostingstart.html |---static //Same static folder and same files from myapp ├── myapp │ ├── migrations │ ├── __pycache__ │ ├── static │ │ │---bootstrap-3.3.7-dist │ │ │ │--css │ │ │ │ │--bootstrap.min.css │ │ │ │ js │ │ │ │ │--bootstrap.min.js │ │ │---Datatables │ │ │ │--jQuery-3.3.1 │ │ │ │ │--jquery-3.3.1.js │ │ │ │ │datatables.js │ │ │ │ │datatables.css | | |---Images | | | |--myimage.png | | | |--myimage2.png │ └── templates Thing is, when I call statics on my template this way: <script src="{% static 'Datatables/jQuery-3.3.1/jquery-3.3.1.js' %}"></script> <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}"> <script type="text/javascript" charset="utf8" src="{% static 'Datatables/datatables.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'Datatables/datatables.css' %}"> <img src="{% static 'Images/myimage.png' %}" align="center"/><br> Images render perfectly, but CDN datatable and css styles not, and browser console throw me this errors: bootstrap.min.js:6 Uncaught Error: Bootstrap's JavaScript requires jQuery at bootstrap.min.js:6 And : myappwapp.azurewebsites.net/:1 Refused to apply style from 'https://myapp.azurewebsites.net/static/Datatables/datatables.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Makes no sense, order of calling … -
matching query does not exist. DoesNotExist at /blog/postComment
I am trying to add the feature of commenting and replying to it in my blog. But it is constantly throwing me the error of "BlogComment matching query does not exist." def postComment(request): if request.method == "POST": comment = request.POST.get('comment') user = request.user postSno = request.POST.get('postSno') post = Post.objects.get(sno=postSno) parentSno = request.POST.get('parentSno') if parentSno == "": comment = BlogComment(comment=comment, user=user, post=post) comment.save() messages.success(request, "Your comment has been posted successfully") else: parent = BlogComment.objects.get(sno=parentSno) comment = BlogComment(comment=comment, user=user, post=post, parent=parent) comment.save() messages.success(request, "Your reply has been posted successfully") -
Django template - how to show the value of a list at specified index
I have list - list_name[] and list_age[] list1[] contains the name of persons, and list_age[] contains age of that persons from list_name[] I have to write in template like this: 1st div should contain name=list_name[0] and age=list_age[0] 2nd div should contain name=list_name[1] and age=list_age[1] and so on -
Array to string with Django and MySQL
I need to design SQL query in html on Django I have an array in my table like : list = ['aa', 'bb', 'cc'] When I call this array in my page : <p>{{ list }}</p> I have : ['aa', 'bb', 'cc'] What do I do if I want : a b c I tried with .split(',') but I've already '[]' I tried with for item in list but I've : [ a a , b b , c c , ] Could you help me please ? -
Implementing "Last Viewed" functionality in Django
Am still a newbie trying to to implement "Last Viewed" functionality for my web app. I want this function to return the 10 latest objects a user viewed. And this should be user specific. Problem is that I don't know how to go about it. Any help will be appreciated. Below is my model.py code class Link(Stamping): name = models.CharField(max_length=256, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) url = models.CharField(max_length=256, default=None) type = models.CharField(choices=Link_Type, max_length=256, default=None) receivables = models.PositiveIntegerField(default=None) #How the user wants to distribute the watched_max on each link object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", related_name="child_links", null=True, blank=True, on_delete=models.CASCADE, default=None) watched = models.ForeignKey(Watched, null=True, blank=True, on_delete=models.CASCADE, default=None) watched_num = models.PositiveIntegerField(default=None, null=True, blank=True) watched_max = models.PositiveIntegerField(default=None, null=True, blank=True) ... ... -
matplotlib python list comprehensive?
I want to do a simple chart to show the total of all appointments profit per day. the result shows something like that which is definitely not right. I know that the issue is in my views.py list comprehensive but not sure how to fix it.. any help is appreciated models.py class Service(models.Model): service_name = models.CharField(max_length=50) service_price = models.DecimalField(max_digits=8, decimal_places=2) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) def __str__(self): return self.service_name class Appointment(models.Model): appointment_date = models.DateField(null=True) appointment_time = models.TimeField(null=True) patient = models.ForeignKey('Patient', on_delete=models.CASCADE) reseptionist = models.ForeignKey('Reseptionist', on_delete=models.SET_NULL, blank=True, null=True) service = models.ForeignKey('Service', on_delete=models.CASCADE) physician = models.ForeignKey('Physician', on_delete=models.CASCADE) plots.py import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import base64 from io import BytesIO def get_graph(): buffer = BytesIO() plt.savefig(buffer, format="png") buffer.seek(0) img = buffer.getvalue() g = base64.b64encode(img) g = g.decode("utf-8") buffer.close() return g # create a plot function for different matplotlib plots def line_plot(x, y): plt.figure(figsize=(4,4)) # you can set size plt.plot(x,y) return get_graph() views.py from .plots import line_plot def index(request): revenue = [x.service.service_price for x in prices] month = [x.appointment_date for x in prices ] c = pie_plot(revenue,month) context = {'chart': c } return render(request, 'index.html', context) -
How to create pages / URLs combining Product Category and Attribute Values? [Django]
So, I have create a Django app with product categories (URLs: domain.com/vk/[category-name]). The product categories display all the products assign to that category. Now, products also have attribute values, which have attributes (keys) as foreign keys. For example, "Grey" is an attribute value where "Color" is the key. How do I create pages that combine the categories and attributes in the categories? For example, I want an URLs like this: domain.com/vk/[category-name]/[grey]/[nike]. Or in generalized: domain.com/vk/[category-name]/[color]/[brand]. The attributes must be hierarichal, meaning that if two attributes are selected at once, they have a set order (for example: color/brand and never brand/color). Here's some code pieces (redundant code left out): # models.py class Product(models.Model): title = models.CharField(max_length=255) class ProductAttributes(models.Model): name = models.CharField(max_length=255) class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) # views.py class ProductCategoryListView(ListView): template_name = "products/product_categories.html" # Default fetch template location: <blog>/<modelname>_list.html #queryset = Product.objects.filter(categories_id = ) # e.g. id=1 def get_queryset(self): self.category = get_object_or_404(ProductCategory, slug=self.kwargs["slug"]) #id=self.kwargs["id"] filtered_products = Product.objects.filter(categories=self.category) # categories_id=self.category.id #for return filtered_products def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Get Attributes of all products in the product category products = Product.objects.filter( categories=self.category, productattributesvalue__attribute__isnull=False ).values( 'title', 'productattributesvalue__attribute__name', … -
request with complex dict DRF
I want to filter ListAPIview endpoint, which is serialized by some nested serializers. class FilterView(generics.ListAPIView): serializer_class = tariff_serializer.TariffSerializer queryset = Tariff.objects.all() filter_backends = (DjangoFilterBackend, ) filterset_fields = '__all__' example json: { "A": "Т1", "B": 1, "C": { "A": "ЭТ2", "B": 3, "C": 1, "D": false }, "D": { "A": "ЭУ1-1", "B": 1, "C": "2021-06-25T07:35:48.490848+03:00", "D": "2021-06-25T07:35:48.490861+03:00", "E": { "A": "У1-1", "B": 1, "C": true, "D": false, "E": "2021-06-25T07:19:15+03:00", "F": "2021-06-25T07:19:17+03:00", "G": "2021-06-25T07:19:37.955155+03:00", "H": "2021-06-25T07:19:37.955168+03:00", "I": { "A": "ЛУ1", "B": 1, "C": { "A": "ЛБ1", "B": 1 } } } } Have no problems filterin on top "A" and "B" keys. But when i am trying to request params like that: http://127.0.0.1:8000/api/filter?С__А=ЭТ2 that does not work. http://127.0.0.1:8000/api/filter - urlpattern, ?С__А=ЭТ2 - query Help, please. -
Django Queryset mock objects and count
I am looking for a way to mock both the Django queryset result and the count result in the same test. Please find below a code snippet to give an overview of what I try to do. This is not the real code, just a simplified version that does nothing interestin. # METHOD def method_to_mock(car_ids): cars = Car.objects.filter(id__in=car_ids).order_by("creation_date") if cars.count() != len(car_ids): missing_cars = set(car_ids) - set(cars.values_list("id", flat=True)) logger.error(f"Failed to retrieve cars {missing_cars}.") for car in cars: print(car.brand) # TESTING mock_filter = mocker.patch("Car.objects") mock_filter.filter.return_value.order_by.return_value = [mocker.Mock(), mocker.Mock()] mock_filter.filter.return_value.order_by.return_value.count.return_value = 2 method_to_mock([0, 1, 2]) This does not work as the list of mocks do not have a count method. I don't want to return a Mock instead of the list of Mock as I still want to be able to loop through the mocks. Could you please help on that ? Thanks ! -
How to fix Attribute error even though it is imported
While I was adding my dislike button I have encountered another problem An attribute error. I hope someone can help me fix it. It says Post object has no attribute even though it does. Traceback: AttributeError at /article/27 'Post' object has no attribute 'total_dislikes' Request Method: GET Request URL: http://127.0.0.1:8000/article/27 Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'total_dislikes' Exception Location: C:\simpleblog\ablog\myblog\views.py, line 67, in get_context_data Python Executable: C:\Users\Selvi\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\\simpleblog\\ablog', 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Selvi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] views.py(where the traceback occured) from .models import Post, Category def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) def DislikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) disliked = False if post.dislikes.filter(id=request.user.id).exists(): post.dislikes.remove(request.user) disliked = False else: post.dislikes.add(request.user) disliked = True return HttpResponseRedirect(reverse('article-detail', args=[str(pk)])) class ArticleDetailView(DetailView): model = Post template_name = 'article_details.html' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) thing = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = thing.total_likes() total_dislikes = thing.total_dislikes() disliked = False if thing.dislikes.filter(id=self.request.user.id).exists(): disliked = True liked = False if thing.likes.filter(id=self.request.user.id).exists(): liked = True context["cat_menu"] = cat_menu context["total_likes"] = total_likes context["liked"] = liked context["total_dislikes"] = total_dislikes … -
Django: Acess denied to XMLHttp request from react because of CORS policy
I am using django as backend and using react in the fronted and I recieve a problem when I try to access data from django server. When I open devtools I recieve the error: Access to XMLHttpRequest at 'http://localhost:8000/wel' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-vmainp*+c^_!0*f50a09f+)txe6wjt!#pge7%$@ak(=i*a4in*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny' ], 'CORS_ORIGIN_ALLOW_ALL' : True } ROOT_URLCONF = 'middleware.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'middleware.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Django - How to load javascript variable from another file to template
How can I load some variable from another js document inside a template, and then modify this variable inside a script tag in my template? For example: js file let myObject = {color: red} Django template {% extends 'app/general/base.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% load static %} {% block content %} <h1 id="color"></h1> <script> document.getElementById('color').innerHTML = myObject.color //I need some way of loading myObject here, and be able to retrieve and edit data from it </script> {% endblock %} -
Problem hile uploading to server django rest api
So I'm trying to upload a rest api made with django and the frontend with react, the problem is the authentication isn't working when I access my website with the domain, but when I access it with the IP it works just fine, the backend was running with the Ip address and the port so: 'IP:8080'. I'm using HTTP only cookies, but the cookies aren't set when I log in, I read in another stack overflow question that this is because the domain isn't the same as the Ip, my question is, how can I run the django backend with someting like domain.com:8080 or a subdomain so that it detects that they are the same page and the authentication cookie is set? -
Django filter queryset of a models that are related with a foreign key to other model?
I have a simple question. I have two models(Waiter and Manager) and they both contains same foreign key to restaurant as: class Managers(BaseUser): restaurant = models.ForeignKey(Restaurants, on_delete=models.CASCADE) class Waiters(BaseUser): restaurant = models.ForeignKey(Restaurants, on_delete=models.CASCADE) And restaurant model: class Restaurants(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=250) location = models.CharField(max_length=200) rating = models.DecimalField(null=True, decimal_places=2, max_digits=5) So I need to get all waiters that restaurant=managers__restaurant_id. I think in SQL would be: select * From Waiters w Left outer join Managers m On w.restaurant_id = m.restaurant_id Note* I'm able to query that like below: manager = Managers.objects.filter(id=request.usr.id) queryset=Waiters.objects.filter(restaurant=manager.restaurant_id) But is there any way that i could do it in one query. -
Add a django model method result as a field in an ORM query
I create a djngo model with two methods for do some stuff like thisone: class Scaling(models.Model): id = models.AutoField(primary_key=True) description = models.TextField(default='', verbose_name="Description", null=True, blank=True) input_low = models.FloatField() input_high = models.FloatField() output_low = models.FloatField() output_high = models.FloatField() limit_input = models.BooleanField() def __str__(self): if self.description: return self.description else: return str(self.id) + '_[' + str(self.input_low) + ':' + \ str(self.input_high) + '] -> [' + str(self.output_low) + ':' \ + str(self.output_low) + ']' def scale_value(self, input_value): input_value = float(input_value) if self.limit_input: input_value = max(min(input_value, self.input_high), self.input_low) norm_value = (input_value - self.input_low) / (self.input_high - self.input_low) return norm_value * (self.output_high - self.output_low) + self.output_low def scale_output_value(self, input_value): input_value = float(input_value) norm_value = (input_value - self.output_low) / (self.output_high - self.output_low) return norm_value * (self.input_high - self.input_low) + self.input_low Ok so now i would use my instance methods calculation in a complex django query as normal field as, for example: var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), id_res__proj_code=pr_code, var_id__is_quarterly=False ).select_related( "id_res", "var_id", "scaling_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", <scale_output_value(scaling instance_id)> ) how can i use model method return value as a column in a queryset? So many thanks in advance Manuel -
Heroku deployment: ModuleNotFoundError: No module named 'django'
After deploying a test site to heroku, it shows an Application Error: Heroku Log: 2021-06-25T13:20:42.143490+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-06-25T13:20:42.143491+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-06-25T13:20:42.143492+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-06-25T13:20:42.143492+00:00 app[web.1]: self.callable = self.load() 2021-06-25T13:20:42.143492+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-06-25T13:20:42.143493+00:00 app[web.1]: return self.load_wsgiapp() 2021-06-25T13:20:42.143493+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-06-25T13:20:42.143494+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-06-25T13:20:42.143494+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app 2021-06-25T13:20:42.143494+00:00 app[web.1]: mod = importlib.import_module(module) 2021-06-25T13:20:42.143495+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-06-25T13:20:42.143495+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-25T13:20:42.143496+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-06-25T13:20:42.143496+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-06-25T13:20:42.143496+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2021-06-25T13:20:42.143497+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2021-06-25T13:20:42.143497+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 848, in exec_module 2021-06-25T13:20:42.143498+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-06-25T13:20:42.143498+00:00 app[web.1]: File "/app/config/wsgi.py", line 12, in <module> 2021-06-25T13:20:42.143498+00:00 app[web.1]: from django.core.wsgi import get_wsgi_application 2021-06-25T13:20:42.143499+00:00 app[web.1]: ModuleNotFoundError: No module named 'django' 2021-06-25T13:20:42.144378+00:00 app[web.1]: [2021-06-25 13:20:42 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-06-25T13:20:42.184157+00:00 app[web.1]: [2021-06-25 13:20:42 +0000] [9] [INFO] Booting worker with pid: 9 2021-06-25T13:20:42.220213+00:00 app[web.1]: [2021-06-25 13:20:42 +0000] [9] [ERROR] Exception in worker process … -
python datetime does not update on ubuntu
I am having the following code on ubuntu as part of a django applicaiton that is deployed using gunicorn. now = datetime.datetime.now() year = now.year month = now.month day = now.day start = now.replace(hour=14,minute=0,second=0,microsecond=0) end = now.replace(hour=16,minute=0,second=0,microsecond=0) day1 = datetime.datetime(year, month, day) day1 = day1.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) if day1.weekday() != 0: # Make day1 == Weekday 0 == Monday day1 = day1 - timedelta(days=day1.weekday()) day2 = day1 + timedelta(days=1) day3 = day1 + timedelta(days=2) day4 = day1 + timedelta(days=3) day5 = day1 + timedelta(days=4) day6 = day1 + timedelta(days=5) day7 = day1 + timedelta(days=6) day8 = day1 + timedelta(days=7) day9 = day1 + timedelta(days=8) day10 = day1 + timedelta(days=9) Meaning that on Monday automatically day1 should be reset to the next week, e.g. from Mo, 21th June to Mo, 28th June. But it is not happening and I always have to restart my server/gunicorn process... any ideas on how to fix this? Thank you. -
how to find the best web framework for data driven web app
As a data scientist, I want to have a 'complete' web developing solution for datascience apps. I do not want to deal with html/css/js. The solution must be complete, not just for prototyping. there are multiple options. Streamlit , but we can not have multiple pages web app with it, also just works with some ports which is not good for 'real' web app. plotly dash app, it's good, but if you want to have user authentication, you have to pay for enterprise solution. PyWebIO, good solution but still immature. it may become paid solution. voila, just one pager dashboards. can anyone please guide me any possible solutions to be able to make and deploy a web app as a regular web app for a non front end person? -
_UnixSelectorEventLoop' object has no attribute '_ssock
I am running an async method inside an interval schedule method and sending data to websocket after every second. It works fine for a while but after sometime below error appear in celery worker terminal. I using python 3.8.5 and djnago 3.1.7. Can anyone help me resolving this issue. Screen shot of error [2021-06-25 17:54:38,033: WARNING/ForkPoolWorker-6] 24 [2021-06-25 17:54:38,033: WARNING/ForkPoolWorker-6] Exception ignored in: [2021-06-25 17:54:38,033: WARNING/ForkPoolWorker-6] <function BaseEventLoop.del at 0x7eff8a9e8700> [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] Traceback (most recent call last): [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] File "/usr/lib/python3.8/asyncio/base_events.py", line 656, in del [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] File "/usr/lib/python3.8/asyncio/unix_events.py", line 58, in close [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] File "/usr/lib/python3.8/asyncio/selector_events.py", line 92, in close [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] File "/usr/lib/python3.8/asyncio/selector_events.py", line 99, in _close_self_pipe [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] AttributeError [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] : [2021-06-25 17:54:38,034: WARNING/ForkPoolWorker-6] '_UnixSelectorEventLoop' object has no attribute '_ssock' -
django-elasticsearch-dsl not syncing for Nested Filed
I've created a django-elasticsearch document(PostDocument) against some models(post, comment, ReactForComment). Everything is working fine. However, after updating ReactForComment model the PostDocument is not getting update. My assumption is, I need to work on def get_instances_from_related(self, related_instance): or prepare_field but can't figure out the way. models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') tags = TaggableManager() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_comments') name = models.CharField(max_length=80) body = models.TextField() email = models.EmailField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ['created'] def __str__(self): return f'Comment by {self.name} on {self.post}' class ReactForComment(models.Model): comment = models.ManyToManyField(Comment, on_delete=models.CASCADE, related_name='react_comments') like = models.IntegerField(null=True, blank=True) happy = models.IntegerField(null=True, blank=True) sad = models.IntegerField(null=True, blank=True) neutral = models.IntegerField(null=True, blank=True) def __str__(self): return f'React on {self.comment}' Document.py @registry.register_document class PostDocument(Document): post_comments = fields.NestedField(properties={ 'id': fields.IntegerField(), 'react_comments': fields.NestedField(properties={ 'id': fields.IntegerField(), 'like': fields.IntegerField(), 'happy': fields.IntegerField(), 'sad': fields.IntegerField(), 'neutral': fields.IntegerField() }) }) class Index: name = 'post' settings = {'number_of_shards': 1, 'number_of_replicas': 1} class Django: model = Post fields = [ … -
Logging - Add extra dict in logging without monkey patching method
I have a task, logs should be sent to the console with extra data: I did this: 1.settings.py logging.Logger = make_record LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s %(message)s %(_extra)s", }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'root': { 'handlers': ['console'], 'level': env('CONSOLE_LOGGING_LEVEL', default='WARNING'), }, 'loggers': { 'keyring.backend': { 'handlers': ['console'], 'level': 'CRITICAL', }, 'elasticapm': { 'handlers': ['console'], 'level': 'CRITICAL', }, 'project.api.client': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'project.utils': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, } } 2.utils.py import logging original_record = logging.Logger.makeRecord def make_record(self, name, level, fn, lno, msg, args, exc_info, func=None,extra=None, sinfo=None): record = original_record(self, name, level, fn, lno, msg, args, exc_info, func, extra, sinfo) record._extra = extra return record This works fine, but how do I override this without 'monkey patching'? I tried to override Logger class and use this class(setLoggerClass) but it didn't work. Any advise? -
Django multiprocessing multiple APIs in separate Pools
My problem seems a bit complex as compared to all other similar solutions I have searched for here. I have three different functions developed in my views.py as three different APIs. Suppose I have 16 GB and 8 cores machine available for it. I want to create three separate pools for each API in such a way that Pool-1 (for API-1) is assigned 4 cores (and 8 GB if that is even possible), Pool-2 is assigned 2 cores (and 4 GB) and Pool-3 is assigned remaining 2 cores (and remaining 4 GB). Now suppose user A makes a request for API-1 (which goes in Pool-1). As soon as the request is made, I dont want to wait for it to finish but only store the process id. Now if user B makes a request say after few hours for API-1 but all 4 cores in Pool-1 are already running, it will wait for any one to finish and basically goes into queue-1 (for Pool-1) even though cores for Pool-2 and Pool-3 are available. So three separate pools managing three different APIs here in same machine. Below is a rough code of views.py of what I am trying to achieve. from … -
Pre-filter query dynamically with user input in django
i'd like to pre-filter a query with user input, that input being a date range. The reason for this is that the query unfiltered just overloads the database. # models.py class Image(models.Model): id = models.BigAutoField(db_column='image_id', primary_key=True) image_date = models.DateTimeField() area = models.FloatField(blank=True, null=True) I've investigated using django-filters package but it applies the filter after the query that gets all objects. Is there a way to do this? -
Django Folium.Map Markers take too long to display
I've created a map with Folium in which users can add their own markers by writing the coordinates of them in a Form. As soon as the user submits the form, the marker gets created in the database correctly. The problem comes when displaying that object (Folium.Marker) in the map itself. When i was in development i had to restart the server the new markers to be displayed. A few days ago i deployed my aplication in Heroku and if i want the markers to be shown i have to restart dynos or else they'll be displayed in no less than an hour. Views.py class mapListView(ListView): model = park template_name = "map/map.html" #Creating the map m = folium.Map(min_zoom = 2, max_bounds = True) parks = park.objects.all() for i in parks: title_ = i.title latitude_ = i.latitude longitude_ = i.longitude commentary_ = i.commentary author_ = i.author html = folium.Html('<div style="width:100px; word-wrap: break-word; text align:center;">' '<h4 style="text-transform:uppercase;">' + str(title_) + '</h4>' '<p>Coordinates: ' + str(latitude_) + ', ' + str(longitude_) + '</p>' '<p>' + str(commentary_) + '</p>' '<p>Uploaded by: ' + str(author_) + '</p>' '</div>', script = True) popup = folium.Popup(html) #Creating markers folium.Marker([latitude_ , longitude_], tooltip = "Click here", popup = … -
502 Bad Gateway nginx Server
I am following satssehgal tutorial to host a website on a cloud server. I am unfortunately getting a 502 Bad Gateway. Here is my nginx/error.log 2021/06/25 12:18:58 [crit] 2494#2494: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:07 [crit] 2494#2494: *3 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:08 [crit] 2519#2519: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:19:10 [crit] 2519#2519: *1 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET / HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/", host: "139.162.255.54" 2021/06/25 12:20:58 [crit] 2519#2519: *5 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/admin", host: "139.162.255.54" 2021/06/25 12:21:03 [crit] 2519#2519: *5 connect() to unix:/home/seast/blog/blog.sock failed (13: Permission denied) while connecting to upstream, client: 85.68.32.122, server: 139.162.255.54, request: "GET /polls HTTP/1.1", upstream: "http://unix:/home/seast/blog/blog.sock:/polls", host: "139.162.255.54" 2021/06/25 12:26:04 [crit] 2519#2519: *9 connect() to …