Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with Serializing list in Django framework and Vue JS
I am want to serialize the list during update, example making patch call to update below user profile with "cuisine" { "user": { "pk": 2, "username": "rayees", "email": "rayees.xxxx@yahoo.co.in", "first_name": "Rayees", "last_name": "xxxx", "user_type": "Chef" }, "first_name": "Rayees", "last_name": "xxx", "bio": "TEST BIO", "chef_cost": "10.00", "serve_type": "Non-Veg", "cuisine": [ "South Indian", "North Indian" ] } Here is my serializer class, i think "serializers.SerializerMethodField()" is read only one and "cuisine" not getting updated during patch operation , If want to serialize both get and patch, what should i do here class ChefProfileDetails(serializers.ModelSerializer): chef_date = AvailabilityDetails(many=True, read_only=True) first_name = serializers.CharField(source='user.first_name', read_only=True) last_name = serializers.CharField(source='user.last_name', read_only=True) cities = CitySerializer(many=True, read_only=True) cuisine = serializers.SerializerMethodField() user = UserDetailsSerializer(read_only=True) class Meta: model = Chef fields = ('user', 'first_name', 'last_name', 'bio', 'chef_cost', 'serve_type', 'cuisine', 'chef_date', 'cities') def get_cuisine(self, obj): cuisine_list = [] for i in obj.cuisine.all(): cuisine_list.append(i.cuisine) return cuisine_list -
How to show the path of file uploaded by fielfield in django instead of the local path
I want to show the S3 url of a file i uploaded via filefield in django instead of the local path in my django admin dashboard. -
Setting different permission classes for POST and GET while using djangorestframework's default router
I was just watching some online tutorial on how to use Django Rest Framework to create a basic REST API using their default router. Link to Docs but then because he used a model viewset he had to add permission_classes to them which means all different types of requests whether its post or get or others it'll all take the same permission. I was wondering if there's a way to give them different permission_classes depending on the type of request. -
Django: Setting unique_together on fields of a model together with a field condition
I'm working on a Django/Python API project and I need one of my models to have a unique_together combination along with a given condition on another field of the model. Ex: user | date |from_time | to_time | status ==================================================== 1 | 2020/01/01 |10 am | 12 pm | Active 1 | 2020/01/01 |10 am | 12 pm | Inactive 1 | 2020/01/01 |9 am | 12 pm | Inactive 1 | 2020/01/01 |12 pm | 3 pm | Active ---------------------------------------------------- 2 | 2020/01/01 |9 am | 3 pm | Active 2 | 2020/01/01 |10 am | 3 pm | Inactive unique_together = [['user', 'date', 'from_time'], ['user', 'date', 'to_time']] This unique combination only allows to save only one record that validates this combination. Adding "status" field to this unique combination will allow adding overlapping times with the same status. So in my application I need to have only one record following the above unique_together combination when its status is "Active" and multiple if it's "Inactive" as shown in the example data set above. Removing the above unique_together combination to UniqueConstraint also fails producing an error in the console upon migrating. constraints = [ models.UniqueConstraint(fields=['user', 'date', 'from_time'], condition=Q(status='Active'), name='uc_user_date_from_active'), models.UniqueConstraint(fields=['user', 'date', … -
AttributeError at /employee/ 'function' object has no attribute 'delete'
I'm new in python and django, wanted to add a function to delete an employee, along with urls and html, the delete button came out just fine, but it didn't do anything, is there anything I did wrong, I've been researching but couldn't find the solution, please advice, thank you, here's the code: views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from django.contrib.auth.decorators import login_required from django.forms import modelformset_factory from .models import Employee from .forms import EmployeeForm def index(request): '''The home page for employee_record.''' return render(request, 'employee_records/base.html') @login_required def employees(request): '''Shows all employees''' employees = Employee.objects.filter(owner=request.user).order_by('full_name') context = {'employees': employees} return render(request, 'employee_records/employees.html', context) @login_required def employee(request, employee_id): '''Show a single employee''' employee = Employee.objects.get(id=employee_id) # Make sure the employee belongs to the current user. if employee.owner != request.user: raise Http404 EmployeeFormSet = modelformset_factory(Employee, fields=('full_name', 'address', 'city', 'state', 'zip', 'email', 'hire_date'), extra=0) if request.method == 'POST': form = EmployeeFormSet(request.POST) employees = form.save(commit=False) for employee in employees: employee.save() return HttpResponseRedirect(reverse('employee_records:employees')) form = EmployeeFormSet(queryset=Employee.objects.filter(id=employee_id)) context = {'employee': employee, 'form' : form} return render(request, 'employee_records/employee.html', context) @login_required def delete_employee(request): employee employee.delete() return redirect('employees') urls.py '''Defines URL patterns for employee_records.''' from django.urls import path from . import … -
What is "import ..." python syntax supposed to mean?
What does "import …" mean in Python? I see it in Django files but no explanation in Python 3.8 documentation. Not one comment about what the "..." is supposed to mean. -
Anchor tags enclosed in li tags not clickable?
So I have a search bar with an inventory in it. The search bar consists of an unordered list with list items that have anchors inside. Each anchor has an href to a page specific to that listed item. The problem I'm having (I believe) is that the mouse-click-down event on the anchor makes it disappear so the mouse-click-up event which should trigger the redirect to the href is never triggered because the list items have already disappeared by then. I found this post: Anchor tag not working inside List Item It seemed to reference a similar issue and I thought I could just import jquery into the head section of my html file with <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> I then thought I could just put <script> $("a").mousedown(function(ev) { ev.preventDefault(); } </script> inside the head tag but it doesn't work, does anyone have any insights? -
Best CI and deployment tool for Django?
I'm fairly inexperienced when it comes to DevOps. I've tried using travis and circleci for CI and deployment but apparently their os do not come preinstalled with GDAL which is a dependency for GeoDjango. Are there any cloud based CI platforms that can easily integrate GeoDjango? Pythonanywhere allowed me to host the application but don't provide ability to run long running processes such as celery and no CI tools. -
I can't displaying error messages on Django Authentication forms
I am having issues trying to displaying error messages on different authentication forms On password reset form: What I am trying to achieve is to display error message like "Email not in our database" when a user enters unregistered email. on password set form: I am trying to display "New Passwords and Confirm Passwords not matching" and any other messages pertaining to the form Below are my codes on forms.py from django.contrib.auth.forms import PasswordResetForm class PasswordReset(PasswordResetForm): email = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Email'})) class SetPassword(SetPasswordForm): new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control form-control-lg', 'placeholder':'New Password'})) new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Confirm Password'})) on urls.py urlpatterns = [ path( 'reset-password/', auth_views.PasswordResetView.as_view(template_name='backend/reset-password.html', email_template_name='backend/password-reset-email.html', form_class=PasswordReset), name='password_reset' ), path( 'password-reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='backend/password-confirm-form.html', form_class=SetPassword), name='password_reset_confirm' ), ] on reset-password.html <form class="pt-3" method="post"> {% if form.errors %} <div class="alert alert-danger">{{ form.errors }}</div> {% endif %} <div class="form-group"> {{ form.email }} </div> <input type='submit' value='Reset Password'> </form> on password-confirm-form.html <form method="post"> {% if form.errors %} <div class="alert alert-danger">{{ form.errors }}</div> {% endif %} <div class="form-group"> {{ form.new_password1 }} </div> <div class="form-group"> {{ form.new_password2 }} </div> <input type="submit" value="Change Password"> </form> -
Django delete all M2M related objects on main object delete
class Project(models.Model): name = models.CharField(max_length=100) project_results_m2m = models.ManyToManyField(Project_Results,blank=True) def delete_all(self): pass ### TO BE ADDED FROM ANSWERS signal @receiver(post_delete,sender=Project) def delete_project_signal(sender,instance,created=False,**kwargs): if created is False: instance.delete_all() p = Project.objects.get(id=1) p.delete() Once above delete() triggered on Project object 1 then the signal would execute delete_all function. Now I would like to delete all objects of Project_Results related to project_results_m2m for Project object 1. How do I achieve it in a safe manner while deleting, either with signals or without signals? -
Coding problem C# Code -- pictures.Box1.Image = Image.FromFile(@"c:\Pictures\ohms1.jpg");
I have a multiple choice test questions & answers script. It has a random generator of questions and comes with radio button for answering the exam test. I am trying to add some pictures on enter code here:{Form 1,I made to go alone with the questions and possible answers.Most of the questions are straight forward true and false statements. The one problem I have is posting a image in picture box and give it a question with radio buttons for choice of answers or more less the right one. I am stuck on this problem and why it will not work, go to the list of random pictures and show them and the questions {private void Form1_Load(object sender,EventArgs e) enter code here Random rnd = new Random(); int randomNumber = rnd.Next(1,4); switch(randomNumber) { case 1: pictureBox1.Image = Image.FromFile(@"c:\Pictures\ohms1.jpg");} break; case 2: pictureBox1.Image = Image.FromFile(@"c:\Pictures\Aideen O'Brien2.jpg"); break; case 3: pictureBox1.Image = Image.FromFile(@"c:\Pictures\circuit board picture3.jpg"); break; case 4: pictureBox1.Image = Image.FromFile(@"c:\Pictures\circuit board picture4.jpg"); break; } } } -
How to use distinct() method without applying values()?
I hope the title is enough to understand what i mean is. this is my current code in views.py students = grade.objects.filter(Teacher=m.id).annotate(total_avg=Avg('Average')).prefetch_related('Subjects').order_by('Students_Enrollment_Records').distinct() this is the result: as you can see the 2 ROSE L TRiNIDAD exist, and it didnt compute the final ratings, but when i use the values() students=grade.objects.values('Students_Enrollment_Records').filter(Teacher=m.id).annotate(total_avg=Avg('Average')).prefetch_related('Students_Enrollment_Records').order_by('Students_Enrollment_Records').distinct() the result is the distinct() method is applied and it computes the final ratings, but as you can see the name of the teacher, subject and the students didnt display this is my html {% for student in students %} <tr> <td>{{student.Teacher}}</td> <td>{{student.Subjects}}</td> <td>{{student.Students_Enrollment_Records}}</td> <td>{{student.total_avg}}</td> </tr> {% endfor %} my models.py class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True) class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) class EmployeeUser(models.Model): Image = models.ImageField(upload_to='images', null=True, blank=True) Employee_Number = models.CharField(max_length=500, null=True) Username = models.CharField(max_length=500, null=True) Password = models.CharField(max_length=500, null=True) . . I post this question 2 times but i didnt get the right answer, AND TAKE NOTE THIS IS DIFFERENT QUESTION BUT SAME RESULT, How to use filtering data while using distinct method … -
CreateView Model Objects to a template
So I am trying to pass a list of objects into my template. I want my profile.html to reflect the information in the model. I found some documentation on ListView but nothing on CreateView. The only thing that is passing through to the template is {{ user.username }}. Any suggestions would be greatly appreciated. profile.html {% extends 'base.html' %} {% block title %}User Profile{% endblock %} {% block content %} {% if user.is_authenticated %} <p>User: {{ user.username }} logged in.</p> <p><a href="{% url 'homepage' %}">homepage</a></p> <p><a href="{% url 'logout' %}">logout</a></p> {% else %} <a href="{% url 'login' %}">login</a> | <a href="{% url 'signup' %}">signup</a> {% endif %} {% endblock %} models.py class Volunteer(CustomUser): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) about_me = models.TextField(default='') class Meta: db_table = "volunteer" forms.py class VolunteerSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = Volunteer fields = ("username", "email", "first_name", "last_name",) @transaction.atomic def save(self): user = super(VolunteerSignUpForm, self).save(commit=False) user.is_volunteer = True user.save() return user views.py class VolunteerSignUp(CreateView): form_class = VolunteerSignUpForm success_url = reverse_lazy('login') template_name = 'volunteer_signup.html' -
Enforcing proper usage of python Enum
So I'm working with a large Django codebase that uses python Enums throughout, e.g.: from enum import Enum class Status(Enum): active = 'active' # ... later assert some_django_model_instance.status == Status.active.value # so far so good ...but of course the ".value" part gets forgotten and left off all the time. It would be hard to ditch Enums altogether by now, although they have been more problematic than useful. Is there a way to auto-check for lines like these: assert some_django_model_instance.status == Status.active # someone forgot ".value" here! with, say, mypy or pylint or perhaps adding some code/asserts to the base Enum? The problem is, Status.active doesn't really call any code, it just returns a class, and of course that class is never equal to some_django_model_instance.status, which is a string. -
Django Privacy Policy & Cookie Policy GDPR Compliance With Versioning and User Acceptance Logging
I want to create something similar to this -> https://github.com/cyface/django-termsandconditions Where instead of handling the terms and conditions, it handles versioning and editing of the privacy policy / cookie policy in the database and stores the user's acceptance to the policy and their IP address and username when they accept the policy. Each page on the site cannot be accessed until the user accepts the policy when they are logged in. When an existing policy is updated, users will need to accept the new one. The database will log all policy version acceptances by the user. I need the acceptance of the policy to be GDPR compliant. It would be ideal to have the terms and conditions, privacy policy, and cookie policy all separate from each other and agreed to separately. If not, hopefully combining the privacy policy and cookie policy and into one acceptance should be acceptable for GDPR. Maybe creating a banner at the bottom of the page where users get to accept both the privacy policy / cookie policy would be the way to go. I tried to see if anything else existed out there for this type of thing and I found these: 1) https://pypi.org/project/django-privacy-mgmt/ (Could … -
How to get updated current date in django forms.DateInput value
How can I keep updated a current date in form field? I've tried to set date at views.py and forms.py, but in that case it saves date in cache only once (when I update index.wsgi) and then it's don't update date on every page reloads. Daily restart of the app is not an option. I can't believe javascript is the only way. I'm just stuck on it, help me, please. How it looks like now: I have a form: class AddRecordForm(forms.ModelForm): class Meta: model = Journal fields = ['date'] widgets = { 'date': forms.DateInput(attrs={'type': 'date', 'class': 'form_input', 'value': date.today().strftime("%Y-%m-%d")}), From this model: class Journal(models.Model): date = models.DateTimeField() And resulting html: <input type="date" name="date" class="form_input" value="2020-01-17" required="" id="id_date"> Looks good, but if I go to the page tomorrow it will still be 2020-01-17. But it should be 2020-01-18 and so on. Date in form updates only after app reload (touch index.wsgi). -
Disabling pagination won't work with Django rest framework
I created an API endpoint for my project, in order to retrieve JSON data from Jquery. Here is how i created it: My view: class tstList(generics.ListCreateAPIView): pagination_class = None queryset = tst.objects.all() serializer_class = tstSerializer filter_backends = [DjangoFilterBackend] My serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('Amount', 'Perc') def create(self, validated_data): return tst.objects.create(**validated_data) To retrieve the data from Jquery, i'm connecting to the following url: http://127.0.0.1:8000/tst Here is my problem: i've noticed that i'm able to get some Json records but not other records, i've investigated further and i realized that i'm only able to get the records located in the first page of my API list, but i won't be able to get records from the following 13 pages. I tried to disable pagination by setting pagination_class = None, but i will still get the same problem. Can anyone help me out on this? -
I use two interconnected ChainedForeignKey fields, but they don't. why?
my problem: I have three models. 'il'(province), 'ilce'(district) and 'mahalle'(neighborhood). I filter with smart-select. works smoothly in the entry of information. When I looked at the database, I saw that "mahalle(neighborhood)" data was recorded. but the mahalle(neighborhood) widget sounds empty. my models: class il(models.Model): adi = models.CharField(max_length=20) class ilce(models.Model): ill = models.ForeignKey(il, on_delete=models.CASCADE) adi = models.CharField(max_length=35) class mahalle(models.Model): ilcee = models.ForeignKey(ilce, on_delete=models.CASCADE) adi = models.CharField(max_length=50) class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) ....... kurum_il = models.ForeignKey('il', on_delete=models.SET_NULL, null=True, blank=False) kurum_ilce = ChainedForeignKey('ilce', chained_field="kurum_il", chained_model_field="ill", show_all=False, sort=False, null=True, blank=False) kurum_mahalle = ChainedForeignKey('mahalle', chained_field="kurum_ilce", chained_model_field='ilcee', show_all=False, sort=False, null=True, blank=False) Does not appear on the Admin page even though I enter and save neighborhood information related screenshot -
Django Query Many relation "includes"
I have the following models: class Contact(models.Model): email_list = models.ForeignKey(EmailList, related_name='contacts') customer = models.ForeignKey('Customer') class EmailList(models.Model): customers = models.ManyToManyField('Customer', related_name='lists', through='Contact') class Customer(models.Model): email = models.EmailField(max_length=255, unique=True) Now I want to query all customers that belong to a certain set of EmailLists by the EmailList id. I thought I was gonna be able to query this with something: all_customers.filter(lists__id__contains=[email_list_1.pk, email_list_2.pk]) that is weird looking I accept and returns an empty Queryset, but what surprised is that it works when querying for only 1 EmailList like: all_customers.filter(lists__id__contains=email_list_1.pk) So my next step was to query with and AND operator: customers.filter(Q(lists__id__contains=el1.pk) & Q(lists__id__contains=el2.pk)) but that returns and empty QuerySet. I would like to find a way to be able to query lists__id__contains passing an iterable of ids, or at least find a way to concatenate subqueries -
ValueError at /search(url)/ Field 'id' expected a number but got 'Junior'
Im trying to make a query in my app that returns my model so I can use it in my html template but I got that error. The query is made with the data of a form filled by the user. This is my Model that Im trying to query: class Ration(models.Model): ration_name = models.CharField(max_length=255) ration_desc = models.TextField() ration_age = models.ManyToManyField(Age) ration_image = models.CharField(max_length=2083) ration_atrib = models.ManyToManyField(Attributes) ration_type = models.ManyToManyField(Type) ration_port = models.ManyToManyField(Port) ration_classification = models.ManyToManyField(Classification) ration_price = models.FloatField() def __str__(self): return self.ration_name The form: <form method="post" class="form-signin" action="{% url 'search' %}"> {% csrf_token %} <select class="form-control" id="ration_age" name="ration_age"> <option value="Junior">Junior</option> <option value="Adulto">Adulto</option> <option value="Senior">Senior</option> </select> <select class="form-control" id="ration_atrib" name="ration_atrib"> {% for atribs in atribs %} <option value={{ atribs.attributes_name }}>{{ atribs.attributes_name}}</option> {% endfor %} </select> <select class="form-control" id="ration_type" name="ration_type"> <option value="Cão">Cão</option> <option value="Gato">Gato</option> </select> <select class="form-control" id="ration_port" name="ration_port"> <option value="Pequeno">Pequeno</option> <option value="Médio">Médio</option> <option value="Grande">Grande</option> </select> <select class="form-control" id="ration_classification" name="ration_classification"> <option value="Económica">Económica</option> <option value="Standart">Standart</option> <option value="Premium">Premium</option> </select> <button class="btn btn-lg btn-primary btn-block" type="submit">Pesquisar</button> </form> And my view that makes the query: search(request): if request.method == 'POST': ration_age = request.POST['ration_age'] ration_atrib = request.POST['ration_atrib'] ration_type = request.POST['ration_type'] ration_port = request.POST['ration_port'] ration_classification = request.POST['ration_classification'] aux = Ration.objects.all().filter(ration_age=ration_age, ration_atrib=ration_atrib, ration_type=ration_type, ration_port=ration_port, ration_classification=ration_classification) #aux = Ration.objects.all().filter(ration_age=age).filter(ration_atrib=atrib).filter(ration_type=type).filter(ration_port=port).filter(ration_classification=classification) … -
Factory Boy date provider is returning string
So, I've been working in some app using the factory_boy package to generate some random data and I'm suffering with the date provider :( class MyModel(models.Model): date = models.DateField() class MyModelFactory(factory.DjangoModelFactory): date = factory.Faker('date') class Meta: model = MyModel my_model = MyModelFactory() my_model.date # '2010-05-20' Someone know how can I make the faker return a real date object? -
Use atomic update in Django ManyRelatedManage
I'm working on an application that includes tables with many-to-many relationships. A simplified version is described here in the django documentation. A junction table relates the two models. Each record in the junction table has a deleted flag (and a few other pieces of information) that need to be updated whenever the record is updated or deleted. For example, if the record is deleted, the deleted flag is set. That is handled for other models (in this example Pizza and Toppings) by inheriting from a model that overrides the "save" and "delete" methods. The junction table also inherits from the model that overrides "save" and "delete", but the ManyRelatedManager uses bulk updating, so the "save" and "delete" methods are not called. Several of the ManyRelatedManager functions have a "bulk" parameter that I'm hoping can be set to False to disable bulk updates. Is there a way to use the ManyRelatedManager so that bulk updating is set to False? Thanks. -
Django rest framework datetimefield won't validate empty string
I've developed a web hook to receive transactions from my bank. I use Django-rest-framework to validate the data before saving it to my database. However my bank passes a blank string for the field 'settled' and Django-rest-framework doesn't seem to be able to validate a form with blank values in a datetime field. null is ok, but an empty string is not. What to do? JSON passed by my bank: { "type": "transaction.created", "data": { "account_id": "acc_00008gju41AHyfLUzBUk8A", "amount": -350, "created": "2015-09-04T14:28:40Z", "currency": "GBP", "description": "Ozone Coffee Roasters", "id": "tx_00008zjky19HyFLAzlUk7t", "category": "eating_out", "is_load": false, "settled": "", "merchant": { "address": { "address": "98 Southgate Road", "city": "London", "country": "GB", "latitude": 51.54151, "longitude": -0.08482400000002599, "postcode": "N1 3JD", "region": "Greater London" }, "created": "2015-08-22T12:20:18Z", "group_id": "grp_00008zIcpbBOaAr7TTP3sv", "id": "merch_00008zIcpbAKe8shBxXUtl", "logo": "https://pbs.twimg.com/profile_images/527043602623389696/68_SgUWJ.jpeg", "emoji": "🍞", "name": "The De Beauvoir Deli Co.", "category": "eating_out" } } } class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) logo = serializers.URLField(max_length=250, required=False) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) is_load = serializers.BooleanField() settled = serializers.DateTimeField(required=False, allow_null=True) merchant = MerchantSerializer() class TransactionSerializer(serializers.Serializer): type = serializers.CharField(required=True, max_length=50) data = DataSerializer() -
pandas- grouping and aggregating consecutive rows with same value in column
I have a pandas DataFrame from a long list of datetime ranges pulled from a database, each range with a label. The dates are ordered such that the start date of one row, is the end date of the row before. A workable example is here: import pandas as pd bins = [{'start': '2020-01-12 00:00:00', 'end': '2020-01-13 00:00:00', 'label': 't3'}, {'start': '2020-01-13 00:00:00', 'end': '2020-01-13 07:00:00', 'label': 't2'}, {'start': '2020-01-13 07:00:00', 'end': '2020-01-13 15:30:00', 'label': 't1'}, {'start': '2020-01-13 15:30:00', 'end': '2020-01-14 00:00:00', 'label': 't2'}, {'start': '2020-01-14 00:00:00', 'end': '2020-01-14 07:00:00', 'label': 't2'}, {'start': '2020-01-14 07:00:00', 'end': '2020-01-14 15:30:00', 'label': 't1'}, {'start': '2020-01-14 15:30:00', 'end': '2020-01-15 00:00:00', 'label': 't2'}, {'start': '2020-01-15 00:00:00', 'end': '2020-01-15 07:00:00', 'label': 't2'}, {'start': '2020-01-15 07:00:00', 'end': '2020-01-15 15:30:00', 'label': 't1'}, {'start': '2020-01-15 15:30:00', 'end': '2020-01-16 00:00:00', 'label': 't2'}, {'start': '2020-01-16 00:00:00', 'end': '2020-01-16 07:00:00', 'label': 't2'}, {'start': '2020-01-16 07:00:00', 'end': '2020-01-16 15:30:00', 'label': 't1'}, {'start': '2020-01-16 15:30:00', 'end': '2020-01-17 00:00:00', 'label': 't2'}, {'start': '2020-01-17 00:00:00', 'end': '2020-01-17 07:00:00', 'label': 't2'}, {'start': '2020-01-17 07:00:00', 'end': '2020-01-17 15:30:00', 'label': 't1'}, {'start': '2020-01-17 15:30:00', 'end': '2020-01-18 00:00:00', 'label': 't2'}, {'start': '2020-01-18 00:00:00', 'end': '2020-01-19 00:00:00', 'label': 't2'}] bins_df = pd.DataFrame(bins) Notice that some labels are repeated consecutively, for example, … -
How to store Global variable in Django view
In Django views, is it possible to store a numeric data in a global / session variable (say, sent through an Ajax call) in a view and make use of it in another view? The scenario I am trying to implement will be something like: View view1 gets some variable data sent thru' Ajax call: def view1(request): my_global_value = request.GET.get("data1", '') # Storing Global data Then, the stored variable is used in another view, view2: def view2(request): my_int_value = my_global_value # Using the global variable Thanks.