Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Varying cloudinary images in a django template
I'm trying to vary images based on a variable - id in the Django template. <img href="'https://res.cloudinary.com/.../image/'|add:{{ object.id }}|add:'.png'" class="mx-auto" width="100px" alt="No Image"/> object.id is passed into the template from a Queryset object (i.e. object). Page load, but image does not show up and goes to alt="No Image". -
django form queryset choices
this is my model class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_variation") name = models.CharField(max_length=50) this is my form: class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label=_('Quantity'),widget=forms.NumberInput(attrs={'class': 'form-control text-center'})) variation_select = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['variation_select'].queryset = Variation.objects.filter(i want to filter there by foreign key, product_id=product_id) any suggestion? -
How can I capture a picture from webcam and store it in a ImageField or FileField in Django?
I am trying to capture a photo from a webcam and store it in a FileField or ImageField. But I am not getting how to get the captured image data on request. Please check my HTML template, javascript code, and views.py. Can anyone suggest a way to get this image data captured using javascript, on submitting the form in HTML? class UserDetails(models.Model): User_name = models.CharField(max_length= 300) User_phone = models.BigIntegerField() User_address = models.TextField() User_pic = models.FileField(upload_to='documents/%Y/%m/%d') My HTML form {% extends 'base.html' %} {% load static %} {% block content %} <form method="POST" action="/usersave/" enctype="multipart/form-data"> {% csrf_token %} .... <div class="card-body"> <div class="row"> <div class="col-md-4 ml-auto mr-auto"> <div class="form-group"> <video id="video" autoplay ></video> <canvas id="canvas"></canvas> </div> <button id="startbutton1" class="btn btn-outline-secondary btn-sm">Take Photo</button> <script src="{% static "assets/js/capture.js" %}"></script> </div> ..... <div class="img pull-center" > <img id ="photo" name="photo" alt="The screen capture will appear in this box."> </form> </div> </div> </div> Views.py def usersave(request): if request.method== 'POST': User_name = request.POST["Username"] User_phone = request.POST["Userphone"] User_address = request.POST["Useraddress"] pic = request.FILES["photo"] User_info= UserDetails(User_name=User_name, User_phone=User_phone, User_address=User_address, User_pic= pic) User_info.save() return render(request, 'some.html') Using this capture.js file I am able to take photo and populate the HTML file in img tag (function() { var width = 320; … -
Django - Passing exceptions in large try block without skipping whole block?
I have a view in django which gathers a lot of data depending on user input. Sometimes, not all of the data will be available for the specific query. I currently have large try blocks, but it is less than ideal as it will skip the whole block and not show any data. Is there any way to continue past the errors without having to do a ton of individual try blocks? Here is a much shorter example to show what I currently have. try: year1 = income[0]['date'] year2 = income[1]['date'] year3 = income[2]['date'] year4 = income[3]['date'] year5 = income[4]['date'] except Exception as e: pass This will pass the whole block if year5 is unavailable. One solution would be to put each year in it's own try block, but that would add 100s of lines of code if not thousands. It would be great if there was a simple way to maintain the data that is successfully collected, and pass the ones that throw an exception (or give them a default value). Thanks! -
Adding data to a Django model associated with a user field
I am creating an application that contains the model UserDetail. In this model, there are 3 fields, a field for donations, points, and a field for the user who is associated with these points. I show these fields in the dashboard.html file, and everything works. My problem is that I manually have to go into /admin and give a user in the database a points and donations field. I want my program to automatically populate the user, donations, and points data to the database when their account is completed, giving the points and donation field a value of 0 and associating it with the user. Below is my code for both the dashboard.html view, which allows the data to be shown on the dashboard page, my UserDetail model, and the view for when the account is created. Thank you to everyone who helps! Model: class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) Dashboard view: @login_required(login_url='/login/') def dashboard(request): user = request.user # assuming there is exactly one # this will break if there are multiple or if there are zero # You can (And should) add your … -
Django: How to add query params to queryset as is done in Pagination?
Our site is DRF backend, with Vue frontend. It incorporates extensive filter options, so any endpoint could have many query parameters - like example.com?name__icontains=bob&...etc. We have a situation on one view where we need to return a sum of one column. Instead of creating a separate endpoint for the frontend to hit, we want to add it to the results of the original view. Like so... { "pagination": { ...pagination stuff... }, "results": [ { "id": 1, "task": "DMSD-50", ...other fields..., "duration": 204 }, { "id": 2, "task": "DMSD-53", ...other fields..., "duration": 121 }, ...more rows... ], "totals": { "duration": 955 } } My first attempt was to add this to the get() method of the view: def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) queryset = self.get_queryset() totals = queryset.aggregate(total_duration=Sum('duration')) response['totals'] = { 'duration': totals['total_duration'] or 0 } return response ...which worked when I did the full (unfiltered) list. But when I added filters in the URL, the total was always the same. That made me realize that get_queryset() doesn't add query parameters from the URL. I then realized that the pagination class must be incorporating query parameters, so my second solution was to add this code … -
Error while performing Cloud Build and connecting to Cloud PostgreSQL
I am trying to automate the process of building a Django app on Google Cloud Build. This app has to communicate with a PostgreSQL DB hosted on Cloud SQL and there're three stages I would like to complete: Building the image with a Dockerfile Pushing the image to Artifact Registry Running Django migrations python manage.py migrate by connecting to Cloud PostgreSQL through Cloud SQL Proxy I have successfully made the first two stages work with these configuration files: cloudbuild.yaml steps: # Build the container image - id: "build image" name: "gcr.io/cloud-builders/docker" args: ["build", "-t", "${_IMAGE_TAG}", "."] # Push the container image to Artifact Registry - id: "push image" name: "gcr.io/cloud-builders/docker" args: ["push", "${_IMAGE_TAG}"] # Apply Django migrations - id: "apply migrations" # https://github.com/GoogleCloudPlatform/ruby-docker/tree/master/app-engine-exec-wrapper name: "gcr.io/google-appengine/exec-wrapper" # Args: image tag, Cloud SQL instance, environment variables, command args: ["-i", "${_IMAGE_TAG}", "-s", "${PROJECT_ID}:${_DB_REGION}:${_DB_INSTANCE_NAME}=tcp:127.0.0.1:3306", "-e", "DJANGO_SECRET_ID=${_DJANGO_SECRET_ID}", "--", "python", "manage.py", "migrate"] # Substitutions (more substitutions within the trigger on Google Cloud Build) substitutions: _IMAGE_TAG: ${_REPOSITORY_REGION}-docker.pkg.dev/${PROJECT_ID}/${_REPOSITORY}/${_IMAGE_NAME}:${COMMIT_SHA} # Display the image in the build results # https://cloud.google.com/build/docs/building/build-containers#store-images images: - '${_IMAGE_TAG}' Dockerfile FROM python:3.7-slim # Add new /app directory to the base image ENV APP_HOME /app WORKDIR $APP_HOME # Removes output stream buffering, allowing for more efficient logging … -
How to define range in "for" at Django template
Django ListView returns object_list, and in Template I want to take the data only once using "for". So I wrote this code. {% for item in object_list(range(1)) %} But this code does not work. Here is the error code. Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '(range(1))' from 'object_list(range(1))' I know my for code is something wrong, please teach me how to write properly. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you.