Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Error when trying to see my site in PythonAnywhere
I've put my site in PythonAnywhere, but when I try to see it through the browser, it's generated an error. It has something to do with the secret key. In the project (created in pycharm), the secret key is stored in a .env file, and in PythonAnywhere, the secret key is stored in an environment variable in the .profile file. Here's the log error: PythonAnywhere_log_error How could I solve this problem? -
Python Django ORM select custom DB for raw query by session variable
Given the following raw query, inside a view: @login_required(login_url='/login/') def view(request): result = CustomObject.objects.raw("SELECT a, b, c FROM table WHERE d = %(param)s", { 'param': 123 }) ... return render(request, 'templates/template.html', { 'a': 'b' }) I use a router to route the query to a DB (use case is read only). class MyDBRouter(object): @staticmethod def db_for_read(model, **hints): if model == CustomObject: return 'customdb' return None @staticmethod def db_for_write(model, **hints): return None I have the available databases configured: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'customdb': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxx.yyy.zzz:1234/DB', 'USER': 'user', 'PASSWORD': 'pass', } } Problem: During login, the User can specify which database he wants to execute the commands on. Depending on the session, I have to use different databases to connect to, therefore I have to specify manually for each request which DB it goes to. Question: How can I access my session variables from a static method of a router? If using routers is not advised in this specific case, what other options do I have for this problem? -
Django long running asynchronous view blocking other requests
I need help I have been trying to solve a problem for a long time now I want my django project to send some data which it would obtain from another url but the data would be sent in batches. However all have done seems to be blocking other request or operation which I want to do. I have tried to make it an async function but it keeps on blocking other request view.py async def asyncTest(): print('inside asyncTest sleep') await asyncio.sleep(20)#purpose of this is ensure that other request can recieve response print('inside asyncTest wakeup') ..do some other operations @sync_to_async def send_invitation(request): if request.method == 'POST': loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return HttpResponse(json.dumps({"result":"msg_type"}), loop.run_until_complete(loop.create_task( asyncTest())), content_type ="application/json", status=status.HTTP_200_OK) when it gets to asynctest where the sleep is, i try to open another view, the server does not respond. Please can I do to make my program respond asynchronously to other request. -
Django jquery: new elements lost functionality after scroll pagination
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 {% extends "base.html" %} {% block content %} <div id="image-list"> {% include "content/list_ajax.html" %} </div> {% endblock %} {% block domready %} var page = 1; var empty_page = false; var block_request = false; var max_page = {{posts.paginator.num_pages}}; $(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(){ var id_but = $(this).data('id') console.log('click') $.post( '{% url "content:post_like" %}', data = { id : $(this).data('id'), action : $(this).data('action') }, function(){ var button_id = 'button#id-'+ id_but var span_id = 'span#id-'+ id_but var previous_action = $(button_id).data('action') var previous_likes = parseInt($(span_id ).text()) $(button_id).data('action', previous_action == 'unlike' ? 'like' : 'unlike'); $(button_id).text(previous_action == 'unlike' ? 'Like' : 'Unlike'); $(span_id).text(previous_action == 'unlike' ? previous_likes-1 : previous_likes+1)} ) }) {% endblock %} list-ajax.html {% for post … -
Do I need a clean install of Python to start working with virtual environments?
I've been using Python on my system for about a year as a new programmer. Until recently, the topic of virtual environments hasn't come up until got to the end point of the Django course on codecademy. I'm now expected to make a Django project on my own system. I have been just installing packages to Python without making virtual environments in the past as I wasn't aware that it was recommended to create an environment for each project. Should I have a clean install of Python before I start using virtual environments? If so, is there a pip command to uninstall all non-python native packages and essentially reset the install? -
How to push data on git hub I having Permission issue Of my same Account
hello I m new In Coding I made a project I want to push my project on git hub every thing is goes well but if I want to push my data in git repo then I m having this kind of error $ git push -u origin main remote: Permission to manojgupta143/python-.git denied to manojgupta143. fatal: unable to access 'https://github.com/manojgupta143/python-.git/': The requested URL returned error: 403 in my git bash terminal please some buddy can help -
How to separate data by date and its value count of its time interval
I created function in django. where I am fetching data from api by time interval. which have parameters datetime and value. the data is getting like this: { "Parameter_1": { "2021-11-16 14:29:00": 319.56, "2021-11-16 15:16:00": 319.56, "2021-11-16 15:17:00": 319.56, "2021-11-17 00:00:00": 335.48, "2021-11-17 00:01:00": 335.48, "2021-11-17 00:02:00": 335.48, "2021-11-18 00:00:00": 355.45, "2021-11-18 00:01:00": 355.45, "2021-11-18 00:03:00": 355.45, }, "Parameter_2": { "2021-11-16 14:29:00": 319.56, "2021-11-16 15:16:00": 319.56, "2021-11-16 15:17:00": 319.56, "2021-11-17 00:00:00": 335.48, "2021-11-17 00:01:00": 335.48, "2021-11-17 00:02:00": 335.48, "2021-11-18 00:00:00": 355.45, "2021-11-18 00:01:00": 355.45, "2021-11-18 00:03:00": 355.45, } When I am fetching data by time interval of 1 min. the data is getting with date and value but I wish to separate date and value by per date. here, I am separating date and value, I am getting dates by time interval of 1440. and values from time interval 1 I wish to count data of one date and get data like this and count value. { "Parameter_1": { "2021-11-16: 319.56,319.56,319.56, "2021-11-17": 335.48,335.48,335.48, "2021-11-18": 355.45,355.45,355.45, }, "Parameter_2": { "2021-11-16": 319.56,319.56, 319.56, "2021-11-17": 335.48,335.48,335.48, "2021-11-18": 355.45,355.45,355.45, } This is code I does: data = [] for parameter in parameters: for key, values in data_response.items(): for key1, value in values.items(): date = …