Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send result of function from Django Server to React Native App?
I am study React Native and Django Development and I create an app which recognize a text from image. I realized POST method from React Native to Django Server but I don't understand how to send the result of recognition back to React. How I can resolve this problem? Django Server: views.py: from .serializers import PostSerializer from .models import Ocr from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status # Create your views here. from django.http.response import JsonResponse # Create your views here. # import pytesseract to convert text in image to string import pytesseract # import summarize to summarize the ocred text from .forms import ImageUpload import os # import Image from PIL to read image from PIL import Image from django.conf import settings # Create your views here. class PostView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): posts = Ocr.objects.all() serializer = PostSerializer(posts, many=True) print(serializer.data) return Response(serializer.data) def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.data) if posts_serializer.is_valid(): text = "" message = "" posts_serializer.save() try: posts_serializer.save() image = request.FILES['image'] image = image.name path = settings.MEDIA_ROOT pathz = path + "/images/" + image text = pytesseract.image_to_string(Image.open(pathz), lang='rus+eng') os.remove(pathz) except … -
How do I best restrict by user and by data model using Django?
I'm using django-guardian and I encountered some issues with the default mixins. And I want to know if there's a better way to do this. Problem: If I want to limit access at both the model and object levels, using these two mixins (PermissionRequiredMixin, PermissionListMixin) is not a very easy task. Because the permissions_required attribute is overridden. To get around this I had to create a new attr "object_permission" and do the following: Model Looks like: # Create your models here. from django.db import models from localflavor.br import models as localModels from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Customer(models.Model): user: User = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Company(models.Model): user: User = models.OneToOneField(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='comapnies') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Project(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='projects') class Meta: permissions = (('read_project', 'Read Project'),) def __str__(self): return self.name class House(models.Model): rooms = models.IntegerField() postal_code = localModels.BRPostalCodeField() project = models.ForeignKey(Project, on_delete=models.CASCADE) Here I needed to create a new attribute ("object_permission") to limit object-level access in the View: class ProjectsListView(PermissionRequiredMixin, PermissionListMixin, ListView): template_name = 'home/projects.html' model = models.Project permission_required = ["homepage.view_project"] object_permission = ["read_project"] redirect_field_name = 'next' login_url = 'login/' get_objects_for_user_extra_kwargs = … -
How to add Reactjs code to django app on docker-compose with nginx-proxy acme-companion
I am trying to setup a complete django react webapp via docker-compose on AWS. I went through a tutorial to create a django backend with database and ssl via nginx-proxy and letsencrypt acme-companion. Everything works so far, but I struggle to add reactjs code as the frontend. I created a frontend folder with react-code and a Dockerfile to create the static files: # Dockerfile frontend FROM node:15.13-alpine as build WORKDIR /frontend # add `/app/node_modules/.bin` to $PATH ENV PATH /frontend/node_modules/.bin:$PATH # install app dependencies COPY package.json ./ COPY package-lock.json ./ RUN npm ci --silent COPY . ./ RUN npm run build # The second stage # Copy React static files FROM nginx:stable-alpine COPY --from=build /frontend/build /usr/share/nginx/html I tried to change the default file in nginx/vhost.d/default to access static frontend files as default and the django-backend-app via /api: # nginx/vhost.d/default server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { try_files $uri @proxy_api; } location /admin { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend:8000; } location /django_static/ { autoindex on; alias /app/backend/server/django_static/; } } Here is … -
TestCase fails but api works fine
Im still learning django but i found a issue i couln't find anything about on the internet. Im was busy with writing my tests for my CBV's but im now running in this weird issue specs: Python 3.10 django 4.0.4 drf 3.13.1 I have a model with 2 foreignkey fields you can see it below. My issue that is when i run the code and test with the drf-yasg swagger it runs without any issues but my test keeps failing. specifically the test_get_good() The traceback says: AttributeError: 'ArticleLocation' object has no attribute 'article_name' but the swagger page does everything without issues and with postman i also did not get the error at all. Could somebody explain to me where it goes wrong as im not seeing it. class Slotting(ICSBaseMixin): # database fields article = models.OneToOneField( "ics_stock.Article", on_delete=models.SET_NULL, related_name="slotting", null=True ) article_location = models.OneToOneField( "ics_stock.ArticleLocation", on_delete=models.SET_NULL, null=True, related_name="slotting" ) def __str__(self): return str(self.record_id) class Meta: db_table = "ICS_Stock_Slotting" verbose_name = "Slotting" verbose_name_plural = "Slottings" # noqa and my serializers are: from rest_framework import serializers from ics_stock.models.slotting import Slotting from ics_stock.models.article import Article from ics_stock.models.article_location import ArticleLocation class SlottingOutputSerializer(serializers.ModelSerializer): class Meta: model = Slotting fields = "__all__" class SlottingArticleOutputSerializer(serializers.ModelSerializer): class Meta: model … -
Running a python script needing typed arguments in the terminal within Django
I am trying to build a website and a component would be a python script that would run internally and needs typed arguments in the terminal to run and produce results. How can I run this script with pre-written arguments within Django? -
Django dumpdata: "Unable to serialize database" error due to a BitFlagField var
I've been trying to create a fixture of a table, but it's always been failing with the following message: CommandError: Unable to serialize database: __str__ returned non-string (type method). The stacktrace was equally unhelpful, pointing to one of the Django files as the culprit. After some fiddling about, I've managed to pinpoint the culprit in the models.py: class UserExtra(model.Models): (...) blocked = BitFlagField( flags=( 'manual', 'system', 'tries', 'expired', 'inactivity', 'nosys_nobypass' ), db_column='ind_block' ) The class is only a list of vars and lacks any sort of function. If I remove that var and run the dumpdata command, it works. How do I serialize this field? -
Django SelectMultiple field with filter
what should I write here to filter participants by event ID 'participants' : forms.SelectMultiple( choices=Participant.objects.filter('event_id'), ), in parentheses was event = event_id but event_id I don't know how to initialize tried it like that def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['participants'] = Participant(queryset=Participant.objects.all()), -
issue Dockerise Django Cuda application using docker compose
I am trying to dockerize a Django Cuda application that runs on Nginx and Gunicorn.Problem is when I go to do prediction .. I get an error cuda drivers not found My DockerFile: FROM nvidia/cuda FROM python:3.6.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./requirements.txt /app/requirements.txt RUN python -m pip install --upgrade pip RUN pip install cmake RUN pip install opencv-python==4.2.0.32 # RUN pip install pywin32==227 RUN pip install -r requirements.txt COPY . /app RUN python manage.py collectstatic --noinput RUN pip install gunicorn RUN mkdir -p /home/app/staticfiles/ Ngnix DockerFile FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Ngnix config file upstream project_settings { server web:8000; } server { listen 80; client_max_body_size 0; location / { proxy_pass http://project_settings; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/staticfiles/; } } Main Docker compose file services: nginx: build: ./nginx ports: - 1300:80 volumes: - static_volume:/home/app/staticfiles/ depends_on: - web web: build: . command: gunicorn project_settings.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/staticfiles/ image: sampleapp1121asa expose: - 8000 deploy: resources: reservations: devices: - capabilities: [ gpu ] volumes: static_volume: Things are not working with docker compose, when I try to build the dockerfile seperately and then run using docker run … -
Django CreateView: How/Where to inject additional form field, prior to Model.Clean() call?
I have created the following Django model: class CoachGalleryImage(models.Model): image = models.ImageField( null=False, blank=None, validators=[validate_gallery_img_dimensions] ) coach = models.ForeignKey(Coach, on_delete=models.CASCADE, null=False) created_on = models.DateField(default=timezone.now) def clean(self): if CoachGalleryImage.objects.filter(coach=self.coach).count() > 3: raise ValidationError("You have reached your gallery image upload limit") Note the additional validation provided in the 'clean()' method. I have a CreateView, that allows a user to upload a gallery image, based on the model above. The user will provide the 'image' field, and the 'coach' field will be assigned programmatically. class CoachGalleryUploadView(CreateView): template_name = "coach_gallery_upload.html" model = CoachGalleryImage fields = ["image"] def form_valid(self, form): form.instance.coach = self.request.user.coach return super().form_valid(form) When the user posts the form, the following error occurs: CoachGalleryImage has no coach. /coach/models.py, line 120, in clean if CoachGalleryImage.objects.filter(coach=self.coach).count() > 3: The issue seems to be that although I am appending the 'coach' field to the form instance, in the CreateView's form_valid(), the Coach Model .clean() method is being called before this has taken place. Since the .coach field doesn't exist when the model .clean() is called, it's causing the custom validation rule to throw an exception. I know that I could move the custom validation logic up to the CreateView, however I would like to keep it … -
Django: set dynamic array in urlpatterns from urls.py
I have this function that I want to use in order to delete some records from a database. It takes as input an array of ints. function deleteScript(idList){ $.ajax({ url: '/delete', type: 'get', data: { ids: idList }, success: function(response) { alert('success') } }) console.log('ajax sent') } How can I set the django dynamic url so that no matter the list, the request would always call the same method? urls.py urlpatterns = [ path('', views.get_data), path('delete/<list:ids>', views.delete) ] -
JsonResponse Error when getting users list on Createview - Django
I'm trying to get all the users who has the group 'decoration' into a form field. I'm using JsonResponse to get the list in realtime when the user start to type. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['...'] def get_form(self, form_class=None): form = super().get_form(form_class) if 'term' in self.request.GET: qs = User.objects.filter(groups__name='decoration', username__icontains=self.request.GET.get('term')) titles = list() for product in qs: titles.append(product.username) form.fields['culture'] = titles return JsonResponse(form, safe=False) return form If I make a print of this, the code is working, is bringing me the correct user but I'm getting the following error 'TypeError: Object of type PostForm is not JSON serializable'. Titles is actually a list, I couldn't figure it out why is giving me that error. -
How to get IntegerField from ForegienKey for objects model
I have a profile, and in this profile I want to display bookmarks for all messages (this is my IntegerField). In other words, how many people have bookmarked a particular author's posts. models.py class Post(models.Model): slug = models.SlugField(unique=True) title = models.CharField(max_length=255, db_index=True) author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, db_index=True ) bookmarkscount = models.IntegerField(null=True, blank=True, default=0) class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) This is my try in template but it does not work <p>Bookmark</p> <p>{{posts.bookmarkscount}}</p> But work only if I use "for" {% for post in posts %} <p>{{ post.bookmarkscount}}</p> {% endfor %} views.py class ProfileDetailView(DetailView): model = Profile template_name = "users/profile/profile.html" def get_context_data(self, **kwargs): try: context["posts"] = Post.objects.filter( author=self.object.user.is_authenticated ) except Post.DoesNotExist: context["posts"] = None -
After changing data with signal i need to render it with new value
I made time limit by one hour to order. If user doesn't get his order in time order's status changed to not delivered. I have a signal that works after order created and calls a function with one hour delay, and changes status to not delivered. And i want to know how to make user aware of this. I have a template which shows status of order model, but doesn't show changes after signal. How can i show that new status to user? My models.py class Order(models.Model): NOT_DELIVERED = 'не доставлено' DELIVERING = 'в пути' DELIVERED = 'доставлено' STATUS_CHOICES = ( (NOT_DELIVERED, 'не доставлено'), (DELIVERING, 'в пути'), (DELIVERED, 'доставлено') ) full_name = models.CharField(max_length=150) email = models.EmailField() street = models.CharField(max_length=50) building = models.CharField(max_length=50) flat = models.CharField(max_length=50, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) status = models.CharField(choices=STATUS_CHOICES, default=DELIVERING, max_length=20) class Meta: ordering = ['-created'] verbose_name_plural = 'orders' def __str__(self): return f'Order {self.id}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) def status_deactivate(self): if self.status != self.DELIVERED: self.status = self.NOT_DELIVERED self.save() print(self.status) else: print('user got his order') My signals.py @receiver(post_save, sender=Order) def set_status(sender, instance, created, **kwargs): if created: timer = Timer(datetime.timedelta(hours=1).total_seconds(), instance.status_deactivate) timer.start() Thanks in advance for your help :) -
merge two django querysets without changing the order
I need to do two different filtering to the queryset. qs1 = qs.filter(name=value) qs2 = qs.filter(equipment_set__name=value) Then I need to connect them without changing the order, just like they were created. qs_result = <QuerySet [<qs1 >, <qs2>,] -
refresh web in django
I have a question, how do I refresh the page where I am currently in django? I am new with all this, add a favorite button, but I am doing a redirect to a page, it is wrong, since I only need the page where I am currently to be refreshed, could someone help me? -
How to use multiple Stripe API keys in Djstripe webhook, is it even possible?
I'm having a hard time trying to wrap my mind around this issue - is it possible to somehow use more than just one Stripe API key in Djstripe webhook handler? If so, how? I have two client apps, both using Stripe. Expectedly, there are two sets of Stripe API keys, each set for a client app. There are no issues with making the payment intents and charging, app is sending enough info, and the keys are explicitly defined (e.g. stripe.api_key = STRIPE_SECRET_KEY) so those part of the code can juggle between API keys succesfully. The hard problem I have encountered is, Stripe webhook handler does not have info to do the juggling - it fails with an error saying: stripe.error.InvalidRequestError: Request <req_id>: No such payment_intent: <payment_intent_id> Sure enough, if I use only one set of API keys, it'll do as expected, but I'd need them both. My idea is to use two webhook endpoints, but I'm not sure how to define additional webhook endpoint in my config/urls.py file. Currently, I'm using this: urlpatterns = [ ... path("stripe/", include("djstripe.urls", namespace="djstripe")), ... In the webhook.py file, I'm using @webhooks decorator: @webhooks.handler('payment_intent.succeeded') def payment_intent_succeeded(event, **kwargs): # code goes here... Since there are … -
How can I pass an id as an argument to delete or patch an user?
I'm trying to set endpoints to PATCH or DELETE users according to a permission but my current code only allows me to apply those changes to the account I'm logged to. Is there a way for me to pass an id or an email as an argument in the body of a request to modify other accounts without using the ID in the URL? Thank you. serializers.py class UserModifySerializer(serializers.ModelSerializer): class Meta: model = User exclude = ['id', 'user_role'] class UserSerializer(serializers.ModelSerializer): organization = OrganizationSerializer(read_only=True) class Meta: model = User fields = ['id', 'email', 'first_name', 'last_name', 'organization', 'user_role', 'language'] models.py class UserViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): swagger_schema = None serializer_class = UserSerializer @action(detail=False, methods=['patch'], permission_classes = [IsAuthenticated], url_path='modify-user') def update_user(self, request): user = User.objects.get(id=self.request.user.id) if user.user_role in [Roles.ORGANIZATION_USER, Roles.ORGANIZATION_ADMIN, Roles.WEBSITE_ADMIN]: serializer = UserModifySerializer(user, data=request.data, partial=True) if serializer.is_valid(): serializer.save(**serializer.validated_data) return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_401_UNAUTHORIZED) @action(detail=False, methods=['delete'], permission_classes = [IsWebsiteAdmin, IsOrganizationAdmin]) def delete_member(self, request): user = User.objects.get(id=self.request.user.id) if user.user_role in [Roles.ORGANIZATION_ADMIN, Roles.WEBSITE_ADMIN]: members = User.objects.filter(organization=self.request.user.organization)\ .filter(id=id).delete() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_401_UNAUTHORIZED) -
Django jquery function doesn't work for new append elements
I created page where my posts showing after scroll down, they have like function which works well on the first 3 elements (from page=1), but for those posts that show up with pagination function of likes doesn't work. Even the console.log('click') doesn't cause any log in console. list.html {% block content %} <div id="image-list"> {% include "content/list_ajax.html" %} </div> {% endblock %} {% block domready %} $(window).scroll(function(){ var margin = $(document).height() - $(window).height() var postion = $(document).scrollTop() if (0.9*margin < postion && block_request==false) { page += 1 block_request=true $.get( '?page=' + page, function(data){ if (page > max_page) { empty_page = true} else{ $('#image-list').append(data); block_request=false} } ) } }) $('button.like').click(function(){ console.log('click') $.post( ... {% endblock %} list-ajax.html {% for post in posts %} <div class='w3-container w3-card w3-white w3-margin-bottom'> <p> {{post.text}} </p> <button id='id-{{post.id}}' class="like" data-id="{{post.id}}" data-action="{% if request.user in post.users_like.all %}un{%endif%}like"> {% if request.user in post.users_like.all %}Unlike{% else %}Like{%endif%} </button> <p> <span id='id-{{post.id}}' class=like>{{post.users_like.count}}</span> likes </p> </div> {% endfor %} base.html (...) $(document).ready(function(){ {% block domready %} {% endblock %} views.py def list(request): ... posts = paginator.page(page) #if request.is_ajax(): if request.headers.get('x-requested-with') == 'XMLHttpRequest': return render(request, 'content/list_ajax.html', {'posts':posts}) return render(request, 'content/list.html', { 'posts':posts}) ``` -
automate dynamic update file
** I want to monitor a folder to add any new file that is being dumped in there to be added to my model . The purpose is to automize upload procedure when a csv file is added to a folder added to the model and delete the file to be ready for next file(whenever arrives) from django.db import models class FilesAdmin(models.Model): adminupload=models.FileField(upload_to='media') title=models.CharField(max_length=50) def __str__(self): return self.title -
502 Bad Gateway AWS Python
I started learning how to host Django web application on AWS Elastic Beanstalk lately and I've been getting a 502 Bad Gateway Error. The health of the application environment is severe. I really need help on how I can go about this, thanks in advance. Here are all the files included in the project The code in the AWS Elastic Beanstalk configuration files. django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: anapp/wsgi.py anapp-dev.env.yml ApplicationName: anapp DateUpdated: 2022-05-02 13:54:58+00:00 EnvironmentName: anapp-dev PlatformArn: arn:aws:elasticbeanstalk:af-south-1::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.13 settings: AWSEBAutoScalingScaleDownPolicy.aws:autoscaling:trigger: LowerBreachScaleIncrement: '-1' AWSEBAutoScalingScaleUpPolicy.aws:autoscaling:trigger: UpperBreachScaleIncrement: '1' AWSEBCloudwatchAlarmHigh.aws:autoscaling:trigger: UpperThreshold: '6000000' AWSEBCloudwatchAlarmLow.aws:autoscaling:trigger: BreachDuration: '5' EvaluationPeriods: '1' LowerThreshold: '2000000' MeasureName: NetworkOut Period: '5' Statistic: Average Unit: Bytes AWSEBLoadBalancerSecurityGroup.aws:ec2:vpc: VPCId: null AWSEBV2LoadBalancer.aws:elbv2:loadbalancer: AccessLogsS3Bucket: null AccessLogsS3Enabled: 'false' AccessLogsS3Prefix: null IdleTimeout: null SecurityGroups: sg-00f20b4b23bdaabab AWSEBV2LoadBalancerListener.aws:elbv2:listener:default: DefaultProcess: default ListenerEnabled: 'true' Protocol: HTTP Rules: null SSLCertificateArns: null SSLPolicy: null aws:autoscaling:asg: Availability Zones: Any Cooldown: '360' Custom Availability Zones: '' EnableCapacityRebalancing: 'false' MaxSize: '4' MinSize: '1' aws:autoscaling:launchconfiguration: BlockDeviceMappings: null DisableIMDSv1: 'false' EC2KeyName: shopit IamInstanceProfile: aws-elasticbeanstalk-ec2-role ImageId: ami-0391473f9da0308f8 InstanceType: t3.micro MonitoringInterval: 5 minute RootVolumeIOPS: null RootVolumeSize: null RootVolumeThroughput: null RootVolumeType: null SSHSourceRestriction: tcp,22,22,0.0.0.0/0 SecurityGroups: awseb-e-tucpjbzz2m-stack-AWSEBSecurityGroup-1KE9LLVZQDHGE aws:autoscaling:updatepolicy:rollingupdate: MaxBatchSize: '1' MinInstancesInService: '1' PauseTime: null RollingUpdateEnabled: 'true' RollingUpdateType: Health Timeout: PT30M aws:ec2:instances: EnableSpot: 'false' InstanceTypes: t3.micro, t3.small … -
Hey I want to make a website where someone can buy a subscription and use the tools I want to use WordPress but my tool in in python what should I do
can someone suggest something currently I have this website called Premium Free Tools I want to make a new online tool website with WordPress because it has external plugins which are easy and I easily add a subscription function to use but my tool is in python can someone suggest something -
Django Forms - How would I implement a form that dynamically changes its fields depending on model objects in the database?
I have 3 models : from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Certification(models.Model): def __str__(self): return f'{self.name}' name = models.CharField(max_length=30) shortName = models.CharField(max_length=10) score = models.IntegerField(null=True, blank=True) class ActiveCertification(models.Model): def __str__(self): return f'{self.user} | {self.sensor}' user = models.ForeignKey(User, on_delete=models.CASCADE) certification = models.ForeignKey(Certification, on_delete=models.CASCADE) value = models.BooleanField() In my database, there are a few different Certification objects, but there is bound to be more in the future. My ActiveCertification model is used to identify which user has which certification. Now, the problem I am facing is that I wish that each user could fill out which certifications they have in a form. I basically need the form to look like this : Certification 1 [ ] Certification 2 [ ] Certification 3 [ ] Certification 4 [ ] ect... [ Submit ] ([ ] representing a checkbox) Basically, I need that when user A uses this form, he checks the certifications he has, and that upon submitting, the ActiveCertification table would fill/update the userA/certification pairs. At first, I started doing a form like this : from django import forms class ActiveCertificationForm(forms.Form): certification1 = forms.BooleanField(required=False) certification2 = forms.BooleanField(required=False) certification3 = forms.BooleanField(required=False) certification4 = forms.BooleanField(required=False) But quickly realized … -
Django Channels - Callback on receiving ping (0x9) message
I am running a Golang application that sends a standard ping (0x9) message at some interval and my Django backend responds to it just how it is described HERE. And I want to track if the Golang client is online by executing a callback on my Django backend. How to run a callback when a ping message is received with Django channels? -
How to download files using xlsxwriter in django views.py
def download_fild(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() merge_format = workbook.add_format({'align': 'center', 'valign': 'vcenter'}) supportings = Supporting.objects \ .annotate(date_str=Cast(TruncDate('date'), CharField())) \ .values_list('ldate_str', 'date_str', 'study_name', 'student_register_number', 'student__name', 'student__no', 'date_str', 'kinds', 'teahcer', 'comment') supportings = pd.DataFrame.from_records(supportings) supportings = supportings.rename(columns={0: 'Day', 1: 'Date', 2: 'Study name', 3: 'Register Number', 4: 'Name', 5: 'No', 6: 'Time', 7: 'Kinds', 8: 'Teacher', 9: 'Comment'}) for supporting in supportings['Day'].unique(): # find indices and add one to account for header u = supportings.loc[supportings['Day'] == supporting].index.values + 1 if len(u) < 2: pass # do not merge cells if there is only one supporting days else: # merge cells using the first and last indices worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Day'], merge_format) workbook.close() output.seek(0) supportings.set_index(supportings.columns[:-1].tolist()).to_excel('success.xlsx') Q. If I run the code up to this point in jupyter notebook, the function works normally and I checked the download file in the folder. However, since the return value must be entered in django's views.py, the code below must be added. However, if I add the code below, the file download is possible, but the last code "supportings.set_index(supportings.columns[:-1].tolist()).to_excel('success.xlsx')" does not apply, so the file data is missing when I open it. What could be the cause? filename = 'Register.xlsx' … -
display events from django database to fullcalendar
I am on a django project in which I want to display events from the django database to fullcalendar. The problem I'm having is similar to this one FullCalendar not displaying events but I'm not using php and I'm having trouble visualizing what I'm missing (I guess it's the Ajax request given the answer provided). Currently it is as if my context was not processed. I don't want to add events from JS to the database, just display them by retrieving them from the database. Additions to the database will be done later with django and python via a form. Thanking you in advance for your clarifications. My calendar view code: class ScheduleCalendarView(LoginRequiredMixin, View): def get(self, request): all_events = Planning.objects.all() event_arr = [] for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.reason start_date = datetime.strptime(str(i.appointment_date_start.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.strptime(str(i.appointment_hour_stop.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) data = JsonResponse((event_arr), safe=False) datatest = json.dumps(event_arr) #return HttpResponse(json.dumps(event_arr)) print(data, type(data)) print(datatest, type(datatest)) #return HttpResponse(json.dumps(event_arr)) context = { "appointment": datatest } return render(request, "schedule/fullcalendar.html", context) My template html with Fullcalendar: {% extends 'base_admin.html' %} {% load static %} {% block head_shedule_content %} {% load static %} <link href='https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css' rel='stylesheet'> <link href="{% static …