Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get JSON data on console
Trying to console.log the data before rendering it on page but I keep getting 404 not found or not attributeName 'Porfile' don't have username as an attribute. I'm a noob when it comes to JSON, I've only started messing around with it recently, please help it's for an assignment JS: $.ajax({ type: 'GET', url: 'my-profile-json/', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); Urls: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( post_view_json, profile_test_view, MyProfileView, MyProfileData, ) urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("test", profile_test_view, name="test"), path("my/", MyProfileView.as_view(), name="my-profile-view"), path("my-profile-json/", MyProfileData.as_view(), name="my-profile-json"), # endpoints path("posts-json/", post_view_json, name="posts-view-json") ] Views from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render from django.urls import reverse from django.core import serializers from .models import User, Post, Profile from django.views.generic import TemplateView, View class MyProfileData(View): def get(self, *args, **kwargs): profile = Profile.objects.get(user=self.request.user) qs = profile.get_proposals_for_following() profiles_to_follow_list = [] for user in qs: p = Profile.objects.get(user__username=user.username) profile_item = { 'id': p.id, 'user': p.username, 'avatar': p.avatar.url, } profiles_to_follow_list.append(profile_item) return JsonResponse({'pf_data': profiles_to_follow_list}) class … -
Django Pandas Dataframe with display with neasted list
i still newbie on django, i would like this ask the table how to create pandas with pivot table with neasted list. data_list = [{'id': '1', 'date':2022-1-10 'car': 'toyota', 'car_material': {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}}] pivot = pd.DataFrame(data_list) OutPut | id | date | car | car_material | |----|-----------|--------|--------------------------------------------------------------------------------| | 1 | 2022-1-10 | toyota | {'ST1230': {'name': 'Steel', 'qty': 13}, 'MT1239': {'name': 'PVC', 'qty': 8}}} | How to make it like this ? Final Result Output | id | date | car | car_material | name | qty | |----|-----------|--------|--------------|-------|-----| | 1 | 2022-1-10 | toyota | | | | | | | | ST1230 | stell | 13 | | | | | Mt1239 | PVC | 13 | -
Why is the django for loop not working, help would be appreciated
I passed my html templates that are in the templates directory to the functions to render, but they didn't. `def home(request): context = {"classes": classes} return render(request, 'home.html', context) def classes(request): context = {"classes": classes} return render(request, 'classes.html', context)` Here is one of the template files: `<!DOCTYPE html> {% for class_ in classes %} <div> <h3>Enter <a href='classes.html/'>{{class_.name}}</a></h3> </div> {% endfor %}` I know nothing is wrong with anything except the for loop, because I tried it without the loop and it worked. What did do wrong? -
Send message using Django Channels outside the Consumer Class WITHOUT channel layer
I have the problem described in this answer... Send message using Django Channels from outside Consumer class BUT this answer doesn't work in my case because, I don't want or need to use channel layers because my websocket is 1:1, ie limited to asynchronously notifying a single connected web client app of updates, not broadcasting to a channel layer. How can I send a message outside the Consumer class without using a channel layer? (The solution as described errors on [Consumer] has no attribute 'add_group'. class Monitor(WebsocketConsumer): def connect(self): self.accept() async_to_sync(self.add_group)('monitor_group') Am I confused? Is there no way around using channel_layers and a backing store like Redis even if one is only attempting to avoid long-polling for the status of a long-running backend task? -
Django template tags don't show HTML template correctly
I have an HTML template that I want code with django in back-end to develop my site. I have trouble with django template tags. when I use them, such as {% for %} the website template output is corrupted and don't show code of models.py and views.py. home_page.html: <section> <div class="gap100 no-top overlap-75"> <div class="container"> <div class="servic-category"> <div class="row merged"> <div class="col-lg-3"> {% for object in object_list %} <div class="category-box {{ forloop.first|yesno:"selected," }}"> <i class="fa fa-google-wallet"></i> <h2>{{ training_course.title }}</h2> <p>{{ training_course.title }}</p> <a href="#" class="main-btn" title="">ادامه مطلب</a> </div> {% endfor %} </div> </div> </div> </div> </div> </section><!-- services section --> views.py : from django.shortcuts import render from training_courses import TrainingCourses def home_page(request): training_courses = TrainingCourses.objects.all() context = { 'training_courses': training_courses } return render(request, 'home_page.html', context) models.py: from django.db import models # Create your models here. class TrainingCourses (models.Model): title=models.CharField(max_length=150, verbose_name= 'عنوان') description=models.TextField(verbose_name='توضیحات') link=models.URLField(max_length=100, verbose_name='آدرس') class Meta: verbose_name='برنامه آموزشی' verbose_name_plural='برنامه های آموزشی' def __str__(self): return self.title -
Django, DRF: How do I use pagination in raw SQL queries?
I'd like to use the following raw query in a ListAPIView in the Django REST Framework. I'm not sure how to use a raw SQL query instead of a queryset to support pagination. I've looked into it and didn't find much that made sense to me. If I want to use a query set, it would look like this How do I do this if I want to use raw SQL queries? class VideoListView(generics.ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer SELECT DISTINCT "t"."id", "t"."title", "t"."thumbnail_url", "t"."preview_url", "t"."embed_url", "t"."duration", "t"."views", "t"."is_public", "t"."published_at", "t"."created_at", "t"."updated_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "t"."id") LIMIT 1) AS "is_wl" FROM ( (SELECT "videos_video".* FROM "videos_video" WHERE ("videos_video"."is_public" AND "videos_video"."published_at" <= '2022-01-03 05:20:16.725884+00:00' AND "videos_video"."title" LIKE '%word') ORDER BY "videos_video"."published_at" DESC LIMIT 20) UNION (SELECT "videos_video".* FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT … -
Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver
I would like to running docker-compose. during running react and django application, docker-compose returns the following error: (base) dominik@Precision:~/PycharmProjects/humanet-docker$ ls api docker-compose.prod.yml docker-compose.yml front nginx (base) dominik@Precision:~/PycharmProjects/humanet-docker$ docker-compose ps Name Command State Ports ------------------------------------------------------------------------------------------------------------------------------------------------------ a7c8de30f648_humanet-docker_api_1 python manage.py runserver ... Exit 127 humanet-docker_db_1 docker-entrypoint.sh postgres Up 5432/tcp humanet-docker_front_1 docker-entrypoint.sh yarn ... Up 0.0.0.0:3000->3000/tcp,:::3000->3000/tcp humanet-docker_nginx_1 /docker-entrypoint.sh ngin ... Up 0.0.0.0:443->443/tcp,:::443->443/tcp, 0.0.0.0:80->80/tcp,:::80->80/tcp humanet-docker_pgadmin_1 /entrypoint.sh Up 443/tcp, 0.0.0.0:5050->80/tcp,:::5050->80/tcp (base) dominik@Precision:~/PycharmProjects/humanet-docker$ docker-compose up humanet-docker_pgadmin_1 is up-to-date humanet-docker_front_1 is up-to-date Starting a7c8de30f648_humanet-docker_api_1 ... humanet-docker_nginx_1 is up-to-date Starting a7c8de30f648_humanet-docker_api_1 ... error ERROR: for a7c8de30f648_humanet-docker_api_1 Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver 0.0.0.0:8000": executable file not found in $PATH: unknown ERROR: for api Cannot start service api: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "python manage.py runserver 0.0.0.0:8000": executable file not found in $PATH: unknown ERROR: Encountered errors while bringing up the project. (base) dominik@Precision:~/PycharmProjects/humanet-docker$ below docker-compose.yml file from my docker version: "3.3" services: front: build: ./front working_dir: /home/dominik/node env_file: ./front/.env.dist volumes: - ./front:/home/dominik/node - /private/etc/ssl:/etc/ssl ports: - 3000:3000 restart: always tty: true api: build: ./api working_dir: /home/dominik/python command: pip install -r requirements.txt && python manage.py runserver 0.0.0.0:8000 volumes: - ./api:/home/dominik/python - /private/etc/ssl:/etc/ssl ports: - … -
how to make django work on debian 11? – python error: KeyFile: 'django'
a few monthes ago, i installed mailman3 on clean installed debian 10 vm, with success – the server was working for long time and distributed hundreds of mails without any issues. The tutorial i implemented completely is that one announced by GNU Mailman itself. After regular debian system upgrade process from 10 to 11 (didn't ever added external package sources, so it was really easy) i tried starting mailman 3 again. Everything works, except the django web framework – that one controlled by qcluster.service. The problem seems to be within executing /opt/mailman/mm/bin/django-admin migrate; the output is as follows (journalctl -u qcluster.service contains the same lines): Traceback (most recent call last): File "/opt/mailman/mm/venv/lib/python3.9/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/mailman/mm/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/opt/mailman/mm/venv/lib/python3.9/site-packages/hyperkitty/templatetags/decorate.py", line 4, in … -
How can i install text editor in django frontend in my case django summernote
I need to install an editor in the frontend like the image below, I am using react and Django. Please help me it is really hard to find. -
Not able to access media file even if file exists when checked manually
I have a media file that Django isn't able to access, even if it definitely exists if I enter its URL in the browser. Info Language: Python [v.3.9.7] Platform: Django [v.3.2.8] Goal Being able to access the media file Description The thing is, people can upload books on my website. People upload images of these books in different sizes, so I want to be able to handle all of them, so I access the width and height of the image and then use that as the size of the image in the view (CSS). To do that, I've used a custom filter image_size that is going to do all the work of accessing the image and finding its size, which I send back to the view: @register.filter def image_size(img, host): img = host[0] + "://" + host[1] + img with Image.open(img) as image: width, height = image.size dct = { "width": width, "height": height } return dct Here, host[0] is the protocol (request.scheme) of the URL of the image and host[1] is the host name (request.get_host()). Here's my view: def all_books(request): if request.user.is_authenticated: context = { "books": Book.objects.all(), "request": request, "user_profile": UserProfileInfo.objects.get(user=request.user), "mail_sent": False, } else: context = { "books": … -
rendering forms into HMTL using django-easy-select2
I am using django-easy-select2 to handle the entering of data into several manytomanyfields within a model - titled Engagement. I am using bootstrap and crispy forms to render the Engagement form to HTML. The rendering is broadly working as expected/required. However, the size of form fields for manytomany data are initially very small and require data to the selected/entered, before they expand. Once data is entered the fields do expand. But, I would like these fields to initially render as the size set by bootstrap. For example, I've set bootstrap as col-6, but the initial render of the manytomany is only col-1 or even less. When data is entered that field will expand up to col-6 and no further, which good, but I would like the field to start at col-6, even with no data. Relevant code is below. engagements.view: class EngagementCreateView(CreateView): model = Engagement form_class = select2_modelform(Engagement, attrs={'width': 'auto'}) # this sets the widths of the field template_name = "engagements/engagement_create.html" def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) create engagement template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h4>{% if form.instance.pk %}Edit engagement{% else %}Create new engagement{% endif%}</h4> <div class="form-group"> <form method="post" novalidate> {% csrf_token %} … -
How to Loop through enum in Django?
I have a model in Django class Order(models.Model): class Gender(models.IntegerChoices): Male = (1,), _("Male") Female = (2,), _("Female") I want to send male and female in context context["genders"] = Order.Gender I use that in template like this {% for gender in genders %} <p>{{ gender }}</p> {% endfor %} I want to show male and female in front -
Cannot create list of objects in django rest framework
I am using ListSerializer for updating and creating list of objects, update() works fine but cannot create list of objects (bulk_create). models.py class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor') full_name = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=14, blank=True) class WorkExperiance(models.Model): tutor_work = models.ForeignKey(TutorUser, related_name='tutor_work', on_delete=models.CASCADE) organization = models.CharField(max_length=255, blank=True) start_year = models.IntegerField(null=True, blank=True) serializers.py class WorkExperianceListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): tutor_work_mapping = {tutor_work.id: tutor_work for tutor_work in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for tutor_work_id, data in data_mapping.items(): print(tutor_work_id) tutor_work = tutor_work_mapping.get(tutor_work_id, None) # print(tutor_work_id) if tutor_work is None: ret.append(self.child.create(data)) # print(ret) else: ret.append(self.child.update(tutor_work, data)) for tutor_work_id, tutor_work in tutor_work_mapping.items(): if tutor_work_id not in data_mapping: tutor_work.delete() class WorkExperianceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: list_serializer_class = WorkExperianceListSerializer model = WorkExperiance fields = [ 'id', 'organization', 'start_year', ] def update(self, instance, validated_data): instance.organization = validated_data.get('organization', instance.organization) instance.start_year = validated_data.get('start_year', instance.start_year) instance.save() return instance views.py class TutorWorkExperiance(APIView): def get_object(self, request): tutor = TutorUser.objects.get(tutor_user__id=request.user.id) tutor_work = WorkExperiance.objects.filter(tutor_work=tutor) return tutor_work def put(self, request): serializer = WorkExperianceSerializer(self.get_object(request), data = request.data, partial = True, many=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) return Response({"data": "Not valid"}) In my opinion the problem is here with ID, because WorkExperiance model foreign key with TutorUser model, and … -
Django Dynamic Nested Formsets
I have 3 models Clinic, Doctor, DoctorHours I want to create a dynamic form which will allow me to create those instances in one form something like this: ClinicForm add_doctor_button DoctorForm DoctorHoursForm DoctorHoursForm DoctorForm DoctorHoursForm DoctorHoursForm DoctorHoursForm Please help -
Cache for django restframwork API
I have cache settings in settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': 'django_cache', } } in view.py from django.views.decorators.cache import cache_page from rest_framework.response import Response @cache_page(60*15) @api_view(['POST', 'GET']) def get_route(request): res = {} # some calculation. return Response(res) post with this json { "ids_item":[4,1,2,3], "id":10 } At first access, cache file is made under django_cache directory, (OK it's cool and smooth.) However second access with same json, it calculates again and makes another cache file. I want to use cache when the json is the same. How can I make this?? -
How to add celery settings to django?
I would like to add the following celery setting modification to the django app worker_send_task_event = False task_ignore_result = True task_acks_late = True worker_prefetch_multiplier = 10 In my celery.py, I got import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') app = Celery('server') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() And my tasks.py @shared_task def some_task(): pass Celery is executed using the following command: celery -A server worker -Ofair — without-gossip — without-mingle — without-heartbeat I have added them directly to the Django settings.py but I am not sure if Celery actually picked those settings up. So I am wondering if there is another way to add them or someone has a similar experience? I am using celery==5.2.1 Django==3.2.5 -
Django how to append current logged in user to request.data
How do I append current logged in user to request.data when making post call to create a new chat. I tried append it to the request.data but its a querydict and immutable // models.py class ChatLog(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) participants = models.ManyToManyField(Profile, related_name='chatlogs') def __str__(self): return str(self.id) class Message(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) chat_log = models.ForeignKey(ChatLog, on_delete=models.CASCADE, related_name='messages') sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sentmessages') body = models.TextField() is_read = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class Meta: ordering = ['-created'] // views.py class ChatList(generics.ListCreateAPIView): serializer_class = ChatSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user.profile return user.chatlogs.all() def post(self, request, *args, **kwargs): serializer = ChatSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How do I get children from parent in a category?
How can I use a filter to get exactly those children who are related to a given parent? I'm use MPTT, but don't use recursetree, because he don't worked with images. Models.py class Category(MPTTModel): parent = TreeForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) image=models.ImageField(blank=True,upload_to='images/') Sample html: {% for category in categories %} <div> <div> <h1>{{ category.title }}</h1> </div> <div> <img src="{{ category.image.url }}"> </div> </div> <div> <ul> {% for subcategory in subcategories %} <li><a href="#">{{ subcategory }}</a></li> {% endfor %} </ul> </div> {% endfor %} views.py def index(request): categories = Category.objects.filter(parent__isnull=True) subcategories = Category.objects.filter(???) # how take self context={'categories': categories, 'subcategories': subcategories } return render(request,'index.html',context) -
Django : How do we automatically hide the parts of a form that requests information that we have already entered?
Saying that, I have two classes (service and product) which are linked with a foreign key. Each class contains a number of forms. I want that each information entered in the form of the product class is no longer requested in the form of the service class and if it has detected it I want to hide the fields which request it in the template! (to avoid repetition) Do you have a method for doing this pleaaaaaase? Product : model.py class Product : name = models.CharField(max_length=100, null=True) length = models.CharField(max_length=2, null=True) type = models.CharField(max_length=2, null=True) Service : model.py class Service : date_creation = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True, blank=True) -
load more buttons javascript
I need your help. How to get different button for all posts, now only first button works and it loads comments for all posts. First getting document.querySelector('#loadmore'); then set I set addEventListener and now how get specific elements for every post [...document.querySelectorAll()] My html code priciple is like this. <div class='post'> <div class='comments'> <div class='comment'> </div> </div> <button id="loadmore">load more</button> </div> -
TypeError when rendering page
I don't understand why it keeps saying that the int object is not iterable.. any help guys?? I'm trying to: 1) get the list of users that are following us 2) initialize an empty posts list and set qs equal to none 3) loop through the users list 3A) for each user that we are following - grab it's profile 3B) for every profile that we know have - grab the posts 3C) add the posts to the post list 4) grab our posts 5) if posts list isn't empty sort the posts by created date Error during template rendering In template C:\Users\Khaled\Desktop\social\project4\network\templates\network\profile_test.html, error at line 12 'int' object is not iterable 2 3 {% block title %} 4 Profiles 5 {% endblock title %} 6 7 {% block body %} 8 <p><b>My Posts: </b> {{profile.get_my_posts}}</p> 9 <p><b>My Posts number: </b> {{profile.get_num_posts}}</p> 10 <p><b>Following Profiles: </b> {{profile.get_following}}</p> 11 <p><b>Following Profiles List: </b> {{profile.get_following_users}}</p> 12 <p><b>My Posts and Posts of Following Users: </b> {{profile.get_all_posts}}</p> 13 {% endblock %} 14 def get_all_posts(self): users = [user for user in self.get_following()] posts = [0] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.post_set.all() posts.append(p_posts) my_posts = self.post_set.all() posts.append(my_posts) if len(posts) … -
Django crispy forms removes my initial values from a dynamic model form
I have a model for a 'page' that has a many-to-many relation through an intermediate model with something called 'elements'. I want to make the elements editable from the page edit form. Therefore I dynamically generate ModelChoiceFields. This works well (meaning all selects have the correct initial value), until I apply render_crispy_form to the form in the Jinja2 template. This sets the first value from the dropdown to all select elements, except to the 3rd, where it sets the fourth element as the initial value. The form definition looks like this: class CreatePageForm(ModelForm): class Meta: model = Page fields = [ 'name', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance') elements = Element.objects.all() if instance is not None: for page2element in kwargs.get('instance').pageelements_set.all(): fieldname = f"element_{page2element.position}" self.fields[fieldname] = ModelChoiceField(elements, initial=page2element.element) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Save')) -
maximum recursion depth exceeded while calling a Python object in Django 3.0
I have updated my code from Django 1.8 to Django 3.0 I guess here my issue is with get_context_data and calling get_context_data in gemethodt_form_kwargs Here is my views.py class JobShiftCreateView(CreateView): template_name = 'contract_worker/job_shift_form.django.html' form_class = JobShiftForm context_object_name = "job_shift" model = ShiftBooking def get_context_data(self, **kwargs): self.user_id = self.request.GET.get('user_id') tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%d/%m/%Y") self.due_date = self.request.GET.get('due_date', tomorrow) self.corporate_identity = self.request.GET.get('corporate_identity') date = datetime.datetime.strptime(self.due_date, '%d/%m/%Y').strftime('%Y-%m-%d') context = super(JobShiftCreateView, self).get_context_data(**kwargs) context['shift'] = WorkerAvailableShift.objects.filter(client=self.request.user.client, worker_id=self.user_id, date=date) context["is_create_view"] = True context["corporate_identity"] = self.corporate_identity context["due_date"] = self.due_date context["user_id"] = self.user_id return context def get_form_kwargs(self): kwargs = super(JobShiftCreateView, self).get_form_kwargs() context = self.get_context_data() print("CONTEXT IS",context) kwargs["client"] = self.request.user.client kwargs["is_update_view"] = False kwargs["corporate_identity"] = context['corporate_identity'] kwargs["due_date"] = context['due_date'] kwargs["user_id"] = context['user_id'] kwargs["request"] = self.request kwargs['new_shift_status'] = (('Pending', 'PENDING'),('Accepted', 'ACCEPT'),('Rejected', 'REJECT'),('NoShow', 'NoShow'), ('Cancelled', 'CANCELLED'),) return kwargs def get_work_time(self, shift): if shift.start_time > shift.end_time: dateTime3 = datetime.datetime.combine(datetime.date.today( ), shift.end_time)+datetime.timedelta(hours=24) - datetime.datetime.combine(datetime.date.today(), shift.start_time) else: dateTime3 = datetime.datetime.combine(datetime.date.today( ), shift.end_time) - datetime.datetime.combine(datetime.date.today(), shift.start_time) dateTimeDifferenceInHours = (float(dateTime3.seconds) / 3600) return dateTimeDifferenceInHours - shift.break_time def form_valid(self, form): addtional_days = form.cleaned_data['addtional_days'] booked_with = form.cleaned_data['booked_with'] or None print("BOOKED WITH",booked_with) date = form.cleaned_data['date'] location = form.cleaned_data['location'] week_start = date - datetime.timedelta(days=(date.weekday())) x = datetime.datetime.strftime(week_start, '%d-%m-%Y') week_start = datetime.datetime.strptime( x, '%d-%m-%Y').strftime('%d-%m-%Y') self.object = form.save(commit=False) # work_time = self.get_work_time(self.object) … -
How to create an asynchronous REST API in DJango?
I have a DJango application and am using djangorestframework for my API. Now the problem is I want to create a report which takes about 5 minutes to generate. So what is the best way to create an endpoint which when requested will give the user a status (in progress, completed) of the job and return the final file once its completed? I am confused between using Celery, RabbitMQ, Amazon SQS, Kafka, etc. -
Fetch API post data not receiving in Django view
What I am trying to do ? I am trying to send a post request with data to a Django view using fetch API like this: javascript: const data = { search_text: "", months: 6, property_type: "all" }; const headers = { 'Accept': 'application/json', 'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest' } fetch("some-url", { method: "POST", headers: headers, body: JSON.stringify(data) }) .then((response) => response.json()) .then((data) => console.log(data)); view: class MyView(View): def post(self, request, *args, **kwargs): print("request: ", request.POST) # do stuff with post data urls: re_path(r"^my_view/$", login_required(csrf_exempt(MyView.as_view())), name="my_view"), Problem When I try to access the post data in my Django view I get empty QueryDict and the output of the terminal is this: request: <QueryDict: {}> [06/Jan/2022 06:48:19] "POST /my_app/my_view/ HTTP/1.1" 200 114 Forbidden (CSRF token missing or incorrect.): /inbox/notifications/api/unread_list/ [06/Jan/2022 06:48:22] "{"search_text":"","months":"6","property_type":"all"}GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 403 12291 I have tried looking it up and nothing seems to work. We are using react and i know axios can also be used but it should work with fetch api why isn't it working please help.