Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply a for statement to simplify repeated code in Django queryset
The filter is applied according to team_parameter(request.GET.get('team)) and it has very repetitive code. At the end of the if statement, no filter is applied only if team_parameter is 'ALL'. I think a for statement is necessary to minimize this code, but I did not know how to apply it, so I asked a question. Please let me know which loops are needed to simplify the code below. Help. [views.py] team_parameter = request.GET.get('team') if team_parameter == 'A' and not team_parameter: monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='A')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'B': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='B')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'C': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='C')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), … -
how to work with foreign key field in django
Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) views.py def add_payout_uber_daily_data(request): if request.method == 'POST': form = UberPerformanceDataForm(request.POST, request.FILES, request=request) if form.is_valid(): date = form.cleaned_data['date'] excel_file = request.FILES['file'] df = pd.read_excel(excel_file) is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum() error_list = [] if is_na > 0: error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload') context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, } return render(request, 'add_payout_uber_daily_data.html', context=context) date_match = True for d in df['Date']: if str(d.strftime("%Y-%m-%d")) != str(date): date_match … -
Django authentication with phone number and OTP
In my Django app, I have to authenticate with phone number and OTP on every login. I don't want to store passwords in the user table. How can i customize the Django user model and authentication backend for this?. please help me to figure this out. -
Wagtail and allauth - allauth is inheriting site name from django not wagtail
I am using allauth with wagtail. I have name my site 'mysite' in the wagtail admin, but when sign up emails refer to 'example.com' My settings.py has apps in the following order [ ... 'django.contrib.auth', 'django.contrib.sites', "allauth", "allauth.account", "allauth.socialaccount", "allauth.account", "allauth.socialaccount", 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', ] It sounds as though this might be related to the conflict between django and wagtail described here https://github.com/wagtail/wagtail/issues/2840. However it looks as though that issue has been closed and I am using recent version (Django==3.2.11, django-allauth==0.47.0, wagtail==2.15.1) -
Update django model database with ForeignKey by using serializer
I have created a django model which includes a foreign key to a user as follows: from authentication.models import User from django.db import models class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) My serializers.py file is as follows: class EventSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Event fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request'] What I need to do is to go to a url and with a POST request to upload the data to the database, but without specifically specifying the user. My views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user = request.user instance.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) As I study I thought that by using commit=False in save would solve the problem, but I am getting the following error: 'commit' is not a valid keyword argument to the 'save()' method. If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. You can also pass additional keyword arguments to … -
Login logic in React via Django Rest
I implemented Django rest_auth to use it as authentication backend for my app. This works find when testing via Postman. However, if I now send a login POST request from the client (React) it returns Success: {password: Array(1)}password: Array(1)0: "This field is required."length: 1[[Prototype]]: Array(0)[[Prototype]]: Object When I log the transmitted formData in the submitHandler I get {username: 'admin', password: 'sonne123'} password: "sonne123" username: "admin" which to me looks fine. I'm not sure how to debug this and where the bug might be. import {Fragment, useState, useReducer} from "react"; import {Link} from "react-router-dom"; // Initiate Form reduced const formReducer = (state, event) => { return { ...state, [event.name]: event.value } }; const Login = () => { const [formData, setFormData] = useReducer(formReducer, {}); const [logging, setLogging] = useState(false); const submitHandler = event => { console.log(formData) event.preventDefault(); setLogging(true); } fetch('http://127.0.0.1:8000/api/user/auth/login/', { method: 'POST', body: JSON.stringify({formData}), headers: {'Content-Type': 'application/json'}, }) .then(res => res.json()) .then(result => { console.log('Success:', result); }) const changeHandler = event => { setFormData({ name: event.target.name, value: event.target.value, }); }; return ( <Fragment> <form onSubmit={submitHandler}> <div className="text-lg text-sx-purple-dark text-center mb-4">Login to your Salaryx Account</div> <div> <div className="relative top-3 left-4 pl-2 pr-2 text-sx-purple-dark-soft bg-sx-white-plain w-max">Username*</div> <input type="text" className="w-full mb-4 h-auto text-sm … -
how do i store django media on remote unix server
I have two app servers 10.22.33.54 and 10.22.33.56 and I am trying to integrate media on another server IP 10.22.30.40 I created a media directory so what are the method I can use in Django to manage media files? -
Django DeleteView strange behavior
So I have a problem with a Django class-based Delete View. Actually, the delete view works just fine as it deletes the chosen entry, but the problem occurs when I want to redirect to the DetailView URL of the page where all entries are. DeleteView As you can see in the code above, I am using reverse lazy with a pk of the page before. But after I confirm to delete it seems like Django is trying to get to the same delete URL once again and I am always getting the same error. Error It seems like it's trying to get to the URL of the entry that was just deleted so obviously there is none found. I can't understand what am I doing wrong? Please help. urls.py -
Can't seem to know why this error is occuring
The same code on above is working but not on this line -
VS code not opening from terminal with code . command in windows 11
When I try to open with "code ." command from the windows terminal, it is throwing an error. code : The term 'code' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + code . + ~~~~ + CategoryInfo : ObjectNotFound: (code:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException It was opening fine before. No idea what happened. I tried reinstalling and the issue still remains -
Django how to get the value of other fields in annotate Max?
I want to get the value of other fields('status') in annotate Max or Min,how can I do it? DB user time status name_a 2022-01-03 11:23:40.000000 3 name_a 2022-01-03 17:56:41.000000 4 name_a 2022-01-03 22:24:28.000000 1 # data_1 = Attendance.objects.filter(user__in=user_list) data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time")).annotate(e_time=Max("time")) #print {'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28)} i want to get: {'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28), 's_status': '3', 'e_status': '1' } I tried adding filter but I didn't succeed data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time"), e_time=Max("time")).annotate(s_status=F("status"),filter=Q(time=Min("time"))).annotate(e_status=F("status"),filter=Q(time=Max("time"))) -
Do I need multiple custom permission classes for different object types?
Now for a example I have a course model with community has the foreign key. In my custom permission class has_object_permission I would check if UserCommunity.objects.filter(user=request.user, community=obj.community,role="admin").exists() Grant access Now I have various different models, for example a course post which has a foreign key to the Course and I can thus access the community from this course key. Do I need to create multiple custom permission classes for these different objects? Is there a better way. I've named my first permission class as IsCommunityAdminOrCreator, now all I can imagine happening is IsCommunityAdminOrCreatorCoursePost IsCommunityAdminOrCreatorCourseChallenge And so on... -
How customize permissions in django (not in DRF)?
How customize permissions for updating and deleting objects just for creator (author) in view.py (CRUD classes)? I know classes LoginRequiredMixin and PermissionRequiredMixin, but I cant customize them to make permission just for creator (author) to change exact object. I know how customize permission in DRF using class IsAdminOrReadOnly, for example: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return bool(obj.user == request.user or request.user.is_staff) The question is: How customize permissions in django (not in DRF)? Thank you in advance. I hope you could give me piece of advice, link to the article, or documentation, or example of code to solve this problem. I've read Custom users and permissions, but I haven't got how to solve my exact task. -
cannot connect to mysql database ubuntu 20.4 (VPS) "ModuleNotFoundError: No module named 'MySQLdb'"
I am working on the setup of my first unmanaged vps(ubuntu 20.4) and following the document to connect my django site to mysql server "https://www.digitalocean.com/community/tutorials/how-to-create-a-django-app-and-connect-it-to-a-database" able to setup python/django/virtualenv mysql server - tested from mysql workbench on my local machine-Ok apache2 working ok. able to see the welcome screen with sqlite3. now moving to mysql. i tried both the way('ENGINE': 'django.db.backends.mysql' and option file '/etc/mysql/my.cnf' to connect to mysql server from django project. None of the alternatives working. activated virtualenv, installed mysqldb using a) sudo apt install libmysqlclient-dev default-libmysqlclient-dev b) pip install wheel c) pip install mysqlclient while trying to migrate following error encountered. tried with all the option available on stakoverflow, i found none of them working. Error: " (envFusion) worker@server:~/fusion/fusionerp$ python manage.py makemigrations Traceback (most recent call last): File "/home/worker/fusion/envFusion/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 15, in import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: . . File "/home/worker/fusion/envFusion/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 17, in raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? " -
Potential Django/Celery/amqp threading issues
I'm currently working with a system which provides a Django backend to serve up a rest API. In addition to this we provide updates to a RabbitMQ instance using celery upon change to records within the Django app. uwsgi is used to host multiple (5) instances of the Django backend, and also has an attach-daemon setting which launches 5 celery worker instances, ie: attach-daemon = %(home)/bin/celery --app=djangoProject.worker.app worker -c 5 -l INFO We have recently added some functionality which increases the rate of updates in some circumstances and have discovered we are not generally getting UnexpectedFrame errors from within the amgqp library: amqp.exceptions.UnexpectedFrame: Received 0x00 while expecting 0xce We suspect this is some form of threading type issue, but looking for any advice to overcome the problem. Looking for any advice on how to over come this sort of issue, or to at least further diagnose where the fault lies. -
Django Static Assets Not Found (404) in Docker Container
I've recently configured my Django project with Docker. When I run my container, my Django app running but is missing (404) all of the static assets: GET http://localhost:8000/static/theme/css/sb-admin-2.min.css net::ERR_ABORTED 404 (Not Found) The assets load without issue outside of the Docker container. My Django project is configured to use WhiteNoise. I know that many people say it's not worth the trouble, and just migrate static assets to S3. I'll resort to that if I must, but I'd really like to try and get this to work for my local environment configuration. Here's the relevant configuration: project structure: - cs-webapp - cs - settings.py - urls.py - wsgi.py - staticfiles/ ... - webapp - migrations/ - models/ - views/ ... Dockerfile docker-compose.yml manage.py ... settings.py BASE_DIR = Path(__file__).resolve().parent.parent print("!!!!!! BASE_DIR IS " + str(BASE_DIR)) # this prints '/app' STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' docker-compose.yml version: '3' services: app: build: context: . ports: - "8000:8000" volumes: - /app command: > sh -c "sleep 10; python manage.py collectstatic --noinput && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - .env - db.env depends_on: - db rabbitmq: ... celery-worker: ... celery-beat: ... db: ... Dockerfile FROM python:3.7-alpine … -
Heroku Internal Server Error on Django Application with ModuleNotFoundError: No module named '_tkinter' in logs
I am currently trying to deploy a django project via Heroku, but the app is displaying an Internal Server Error. Checked the logs by running heroku logs -tail <app-name> which I am assuming that the following error is causing the errror: ModuleNotFoundError: No module named '_tkinter' I've tried a different stackoverflow solution, but did not have any luck with it. Here are the following steps: pipenv install matplotlib Added the following in my models.py (even tried in settings.py) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt Heroku Logs 2022-04-06T01:50:43.361025+00:00 app[web.1]: File "/app/config/urls.py", line 26, in <module> 2022-04-06T01:50:43.361025+00:00 app[web.1]: path('', include('users.urls')), 2022-04-06T01:50:43.361025+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/conf.py", line 38, in include 2022-04-06T01:50:43.361025+00:00 app[web.1]: urlconf_module = import_module(urlconf_module) 2022-04-06T01:50:43.361026+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2022-04-06T01:50:43.361028+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-04-06T01:50:43.361028+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2022-04-06T01:50:43.361028+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1027, in _find_and_load 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 688, in _load_unlocked 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 883, in exec_module 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2022-04-06T01:50:43.361030+00:00 app[web.1]: File "/app/users/urls.py", line 2, in <module> 2022-04-06T01:50:43.361030+00:00 app[web.1]: from . import views 2022-04-06T01:50:43.361030+00:00 app[web.1]: File "/app/users/views.py", line 9, … -
How to simplify redundant code in Django queryset
I want to graph the number of client registrations per month/employee for this year. The code below is used to get the desired queryset, but there are many overlapping parts in annotations, so I want to minimize this code. Also, there is a hassle of having to change the year every time the year changes, so I hope this problem will also be resolved. (* For reference, the x-axis is "month" and the y-axis is "the employee name" (uploader_id__first_name )) [views.py] monthly_enroll = Feedback.objects\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') -
External API Calls making django view slow
I am working with django.I have a problem pretty much like this question: Render slow loading results. However I am unable to resolve this. Problem is that I am making nearly 10-15 external api calls which is making rendering of template way too slow. I can't reduce that because that extenal API is my only source of data. What i want to do is to load template and then fetch the data from the extenal api. I think this is the best approach as users will have something to do while data is being fetched. Also i couldn't find a proper guide to implement this mechanism. Any help will be appreciated. -
File Inside Python Module Not Included (Django, Py2 to Py3 Conversion)
I am migrating a Django project from 2 to 3 and am running into an import(?) error. One of the apps/modules contains an __init__.py, admin.py, forms.py, models.py, urls.py, and view.py, but when the module is imported only admin, forms, and models are a part of it. A dir of the module looks like this: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'admin', 'forms', 'models'] If I try something like from . import views, I get a SyntaxError. -
How can I connect to docker db from local django?
How can I connect to docker db from local django? version: '3' services: redis-1: container_name: redis1 build: ./docker/redis environment: X_REDIS_PORT: 7001 networks: redisnet: ipv4_address: 10.0.0.11 ports: - 7001:7001 redis-2: container_name: redis2 build: ./docker/redis environment: X_REDIS_PORT: 7002 networks: redisnet: ipv4_address: 10.0.0.12 ports: - 7002:7002 redis-3: container_name: redis3 build: ./docker/redis environment: X_REDIS_PORT: 7003 networks: redisnet: ipv4_address: 10.0.0.13 ports: - 7003:7003 redis-4: container_name: redis4 build: ./docker/redis environment: X_REDIS_PORT: 7004 networks: redisnet: ipv4_address: 10.0.0.14 ports: - 7004:7004 redis-5: container_name: redis5 build: ./docker/redis environment: X_REDIS_PORT: 7005 networks: redisnet: ipv4_address: 10.0.0.15 ports: - 7005:7005 redis-6: container_name: redis6 build: ./docker/redis environment: X_REDIS_PORT: 7006 networks: redisnet: ipv4_address: 10.0.0.16 ports: - 7006:7006 redis-cluster: container_name: redis-cluster image: redis:latest command: redis-cli -p 7001 --cluster create 10.0.0.11:7001 10.0.0.12:7002 10.0.0.13:7003 10.0.0.14:7004 10.0.0.15:7005 10.0.0.16:7006 --cluster-replicas 1 --cluster-yes depends_on: - redis-1 - redis-2 - redis-3 - redis-4 - redis-5 - redis-6 networks: redisnet: ipv4_address: 10.0.0.2 predixy: container_name: predixy build: ./docker/predixy depends_on: - redis-1 - redis-2 - redis-3 - redis-4 - redis-5 - redis-6 ports: - 7617:7617 volumes: - ./docker/predixy/conf:/etc/predixy/conf networks: redisnet: ipv4_address: 10.0.0.3 networks: redisnet: driver: bridge ipam: driver: default config: - subnet: 10.0.0.0/16 This is my docker-compose.yml file and I would like to connect the predixy (cluster proxy) floated on port 7617 with django … -
IntegrityError at /forum/post/15/comment/new/: NOT NULL constraint failed: forum_comment.name_id
I'm trying to implement a commenting feature for my blog style project, but I'm getting the following error: IntegrityError at /forum/post/15/comment/new/ NOT NULL constraint failed: forum_comment.name_id I suspect that the error has something to do with the comment author because I was reading similar posts where that was the problem, however I wasn't able to fully comprehend or adapt their problem onto mine because of the way I have setup my comments. Here's how my project setup looks: models.py: class Post(models.Model): titulo = models.CharField(max_length=150) contenido = MarkdownxField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def formatted(self): return markdownify(self.contenido) def __str__(self): return self.titulo def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = MarkdownxField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return '%s - %s' % (self.post.titulo, self.name) views.py: class CommentCreateView(CreateView): model = Comment form_class = CommentForm #fields = ['body'] template_name = "forum/comment_form.html" class Meta: ordering=['-time'] def form_valid(self, form): form.instance.post = Post.objects.get(pk=int(self.kwargs['pk'])) return super().form_valid(form) def get_success_url(self): return reverse_lazy('') forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body': MarkdownxField() } urls.py: path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name='comment-create'), Any kind of help would be greatly appreciated, thanks in advance... -
React Native File Upload not working using Axios
I am trying to upload a file to the server and the server APIs are written using django. The file upload is working perfectly from Postman but when i try to upload from mobile app (React Native) using axios the backend is not able to read it. Following is the Frontend Snippet: let accessToken = await AsyncStorage.getItem('accessToken') let formData = new FormData() formData.append('doc_type', this.state.selectedDoc.id) formData.append('document', this.state.selectedFiles) // <- This is the fetched file in array format . [{filname:'abc', size:12344,.....}] formData.append('description', this.state.description.value) formData.append('data', JSON.stringify(this.state.selectedDoc.fields)) let url = `${AppConstants.url}api/${AppConstants.apiVersion}/upload_doc` var config = { method: 'post', url: url, data: formData, headers: { 'Authorization': `Bearer ${accessToken}`, } } axios(config) .then((resp) => { resolve(resp) }) .catch((err) => { reject(err) }); And the backend-end if else statement is as follows: if(request.FILES.getlist("document")): files = request.FILES.getlist("document") .... .... .... else: return response.JsonResponse({ 'success' : False, 'message' : 'Please Upload a file' }, status = status.HTTP_200_OK) The above else block is executed even though the UI is sending a valid file. Request you to please share a solution. -
Annotate GIS Intersection in Nested Subquery
I am trying to execute a complex Django query involving a nested subquery. Starting with the Stick model, I want to annotate the ownership_pct from the StickOwnership model (which is straightforward given the FK relationship). Next, I also want to annotate the ownership_pct from the BoxOwnership model such that the associated Box has the maximum overlap with the Stick. For reference, here are the models: Stick: lateral_line_string = models.LineStringField() Box: polygon = models.MultiPolygonField() BoxOwnership: box = auto_prefetch.ForeignKey("Box") owner = auto_prefetch.ForeignKey("Owner") ownership_pct = DecimalField StickOwnership: stick= auto_prefetch.ForeignKey("Stick") owner = auto_prefetch.ForeignKey("Owner") ownership_pct = DecimalField Here is what I have written so far: sticks = Sticks.objects.all() # starting queryset is arbitrary owner_in_question = Owner.objects.first() # owner is arbitrary stick_ownership_subquery = StickOwnership.objects.filter(stick=OuterRef('pk'),owner=owner_in_question).only('ownership_pct') box_subquery = box.objects.filter(polygon__intersects=OuterRef(OuterRef('lateral_line_string'))).annotate(length=Length(Intersection(OuterRef(OuterRef('lateral_line_string')), F('polygon')))).order_by('-length').only('pk') box_ownership_subquery = BoxOwnership.objects.filter(box=Subquery(box_subquery.first().pk), owner=owner_in_question).only('ownership_pct') sticks = sticks.annotate(stick_ownership=Subquery(stick_ownership_subquery.values('ownership_pct'))).annotate(box_ownership=Subquery(box_ownership_subquery.values('ownership_pct'))) The box_subquery is throwing this error: Traceback (most recent call last): File "venv/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3251, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-8-0b4d9b715187>", line 1, in <module> box_subquery = Box.objects.filter(polygon__intersects=OuterRef(OuterRef('lateral_line_string'))).annotate(length=Length(Intersection(OuterRef(OuterRef('lateral_line_string')), F('polygon')))) File "venv/lib/python3.10/site-packages/django/db/models/query.py", line 1225, in annotate return self._annotate(args, kwargs, select=True) File "venv/lib/python3.10/site-packages/django/db/models/query.py", line 1273, in _annotate clone.query.add_annotation( File "venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1074, in add_annotation annotation = annotation.resolve_expression( File "venv/lib/python3.10/site-packages/django/contrib/gis/db/models/functions.py", line 71, in resolve_expression res = super().resolve_expression(*args, **kwargs) File "venv/lib/python3.10/site-packages/django/db/models/expressions.py", line 762, in … -
ValueError: Cannot assign "15": "Comment.post" must be a "Post" instance
I'm trying to setup a comment system for my posts in a project that I've been working on for the past couple of months, and I'm getting the following error when trying to use the post_id (the number or pk) to identify the post that the comment is being made on: ValueError at /forum/post/15/comment/new/ Cannot assign "15": "Comment.post" must be a "Post" instance. This is how I have setup the comments: models.py: class Post(models.Model): titulo = models.CharField(max_length=150) contenido = MarkdownxField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def formatted(self): return markdownify(self.contenido) def __str__(self): return self.titulo def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = MarkdownxField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return '%s - %s' % (self.post.titulo, self.name) views.py: class CommentCreateView(CreateView): model = Comment form_class = CommentForm #fields = ['body'] template_name = "forum/comment_form.html" def get_post_id(request, post_id): post=Post.objects.get(id=post_id) class Meta: ordering=['-time'] def form_valid(self, form): form.instance.post = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return reverse_lazy('') forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body': MarkdownxField() } urls.py: path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name='comment-create'), Any help is greatly appreciated. Thanks in advance.