Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST throwing [Errno 54] Connection reset by peer and Bad Request
I am using Django REST API for my server in combination with Djoser library for authentication. The client part is written with Vue.js, and I use Axios for API requests. Now I am trying to make the server and client parts interact. I have started with authentication. My server is up on 127.0.0.1:8000. When I use Postman to request an authentication token based on username and password, I send a POST request and get a response: Then, I am trying to reproduce such a request using Vue and Axios. I have defined a component named Login and written the following there: <script> import axios from 'axios' export default { name: "Login", data() { return { login: '', password: '' } }, methods: { setLogin() { axios({ method: 'post', url: 'http://127.0.0.1:8000/auth/token/create/', body: {username: this.login, password: this.password} }) .then(function (response) { sessionStorage.setItem("auth_token", response.data.attributes.auth_token) }) .catch(function (error) { console.log(error); }); } } } And the template consists of just 2 inputs (for login and password) with v-model=login and v-model=password and a button with @click="setLogin". I have imported this component in App.js and display it here. Now when I am trying to authorize, I have several issues: 1) The page is reloaded so quickly … -
Access Consumer from View to push api-received data to User via WebSocket (Django-Channelsv2.2 & DRF)
I found myself struggling to find a way to push data to Consumer (Django Channels v.2.2) from View (APIView Django-rest-framework) or distributed task (Celery/RabbitMQ directly) I'd really appreciate any code sample that would allow me to access the consumer from View as the trigger itself is the input device, not web, so I can make API call from it, so I need the connector. Django Channels v.2.2, DjangoChannelsRestFramework, mostly all the cases described here: https://channels.readthedocs.io/en/latest/community.html as well as correlating questions @stackoverflow consumers.py class BasicConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ "type": "websocket.accept" }) # await self.send({ # "type": "websocket.send", # "text": "Hello world" # }) async def websocket_receive(self, event): print('receive', event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') print(msg) user = self.scope['user'] if user.is_authenticated: username = user.username myResponse = { 'message': msg, 'username': username } await self.send({ "type": "websocket.send", "text": json.dumps(myResponse) }) async def websocket_disconnect(self, event): print('disconnect', event) @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] views.py class BasicView(APIView): def post(self, request): serializer = BasicViewSerializer(data=request.data) if serializer.is_valid(): triggerConsumer(serializer.validated_data) -
How to integrate accountkit in a Python Django project?
I'm entirely new in Python or any kind of back-end development. I've created a simple project using Django & Django REST framework to feed data in a React Native application. I want to integrate Facebook Accountkit for passwordless login, didn't found any documentation or tutorial on how to do that on Django. Can anyone suggest me any example project or code snippet regarding this topic? -
Saving data form in django without editable property for admin-django
I want to save the data of a form that user submit. But I don't wanna the admin be able to edit those data at all. I tried the readonly_field stuffs, but that didn't work. my models.py: class User(models.Model): first_name = models.CharField(max_length=100) country = CountryField() my admin.py: from django.contrib import admin from .models import User admin.site.register(User) class MyAdmin(admin.ModelAdmin): readonly_fields=('first_name', 'country') -
Django Aggregation - Trying to return two values
I am trying to get the username and text of their most recent post using an aggregation function. I am trying the code below, but I don't get distinct values for the user name. conversations = Chat.objects.values('user__username','body').annotate(Max('dateofpost')) With the above it gives me all posts by that user, but what I am trying to get is the user name with the body text of the post that is the most recent one posted. Can anyone help? I have been reading online, but can't find an explanation of what to do in this situation. I can see posts on calling the aggregate / values method again, but can't get this to work. -
How change form_field name in django template?
I tried to get list of checkbox values from template. But I need to change name of form_field in loop like html-input I use forms.ModelForm -> forms.BooleanField(initial=False, required=False) forms.py is_used = forms.BooleanField(initial=False, required=False) template.html {% for object in objects %} {% bootstrap_label form.is_used %} // input type="checkbox" name="{{ object.id }} ##I need something like that {% endfor %} I haven't a list in a POST, I have only is_used=[0:on, 1:on] if i mark the first and the last too. -
how to perform django orm on Django Cassandra engine models
I have django cassandra engine and I create my model as it saied here: enter link description here here it explain I can use raw query inorder to work with my db:enter link description here does it means that I cannot use django orm (ex:model.objecs.all()) for this kinds of model? or there is some solution for it? -
I cannot add song to specific album using CreateView
I am following buckys django tutorial, he explained how to add albums but not song, i want to try adding songs to specific album but it is not working. I have added a SongCreate view to my views.py, i also created a song_form.html template for inputting song details.I have also tried the form_valid method, but it doesnt just work. My views.py class AlbumCreate(CreateView): model=Albums fields=['alb_title','alb_genre','alb_logo','alb_artist'] class SongCreate(CreateView): model = Song fields = ['song_title', 'song_format'] def form_valid(self, form): album = get_object_or_404(Albums, pk=self.kwargs['pk']) form.instance.album = album return super(SongCreate, self).form_valid(form) #My urls.py app_name ='music' urlpatterns = [ path('',views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('album/add/', views.AlbumCreate.as_view(), name='album-add'), path('album/<int:pk>/songadd/', views.SongCreate.as_view(), name='song-add'), path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album- update'), path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'), ] #My song_form.html template {% extends 'music/base.html' %} {% block title %}Add New Song{% endblock %} {% block body %} <div class="container-fluid"> <h4>Add the details of the Song in the given fields.</h4> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class='form-horizontal' action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn- success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} When add song is clicked it directs me to a form to fill … -
add new attribut from other model to user model
i have structure model with id and name_structure and i want when i add user i affect them in one structure like username john password 1234 structure electric departement but i don't know how can i do this work in Django so please help me ? this models.py in immob appfrom django.db import models # Create your models here. class structure(models.Model): structure_code=models.CharField(max_length=1) structure_desig=models.CharField(max_length=350) class service(models.Model): structure_id=models.ForeignKey (structure,on_delete=models.CASCADE,default=0) service_desig=models.CharField(max_length=350) class immob(models.Model): immo_code=models.CharField(max_length=7) immo_desig=models.CharField(max_length=150) immo_qte=models.FloatField(default=1) immo_datemes=models.DateTimeField() immo_cptimmob=models.CharField(max_length=10) immo_dureevie=models.IntegerField(default=7) immo_numaut=models.CharField(max_length=4) immo_origine=models.CharField(max_length=1) immo_fournisseur=models.CharField(max_length=150) immo_nufact=models.CharField(max_length=20) immo_datefact=models.DateTimeField() immo_valht=models.DecimalField(max_digits=18,decimal_places=2) immo_monaie=models.CharField(max_length=3) immo_tauxcvt=models.DecimalField(max_digits=18,decimal_places=2) immo_tauxctrval=models.DecimalField (max_digits=18,decimal_places=2) immo_frais=models.DecimalField(max_digits=18,decimal_places=2) immo_coutacq=models.DecimalField(max_digits=18,decimal_places=2) immo_refcmde=models.CharField(max_length=35) immo_datecmde=models.DateField() immo_journee=models.CharField(max_length=10) immo_cptanal=models.CharField(max_length=9) immo_local=models.CharField(max_length=45) immo_mode_amort=models.CharField(max_length=1) immo_code_r=models.CharField(max_length=2) immo_val_amort=models.DecimalField (max_digits=18,decimal_places=2) immo_status=models.CharField(max_length=1) immo_code_bar=models.CharField(max_length=25) service_id=models.ForeignKey (service,on_delete=models.CASCADE,default=0) and this model of compte app (account) # Create your models here. from immob.models import structure from django.db import models from django.contrib.auth.models import User class utilisateur(models.Model): user=models.OneToOneField('auth.User', on_delete=models.CASCADE) structure=models.ForeignKey(structure,on_delete=models.CASCADE) -
How to sort Django QuerySet output by date?
I have data like this: <QuerySet [(datetime.datetime(2019, 6, 14, 20, 4, 58, 104805, tzinfo=<UTC>), UUID('b15be3c1-3f70-4ccb-af08-dba385f883a1')), (datetime.datetime(2019, 6, 12, 18, 42, 38, 675120, tzinfo=<UTC>), UUID('f2ea2ad0-f228-43d7-823a-c824a041feb2')), (datetime.datetime(2019, 6, 12, 17, 46, 38, 479890, tzinfo=<UTC>), UUID('16c66e9b-0cbf-4b6d-b848-78cf771f522c')), (datetime.datetime(2019, 6, 21, 20, 17, 15, 785171, tzinfo=<UTC>), UUID('a169afcf-267b-4212-97e5-6221595ab107')), (datetime.datetime(2019, 6, 15, 7, 33, 34, 136331, tzinfo=<UTC>), UUID('9aac6b06-6622-4587-9956-5b517aaa11e8')), (datetime.datetime(2019, 6, 18, 16, 11, 49, 134458, tzinfo=<UTC>), UUID('00271b56-9ff7-4f9d-b9c0-2592ca9436d2')), (datetime.datetime(2019, 6, 21, 21, 3, 53, 528261, tzinfo=<UTC>), UUID('df0d8905-5377-4b8d-99d9-eba644273eaa')), (datetime.datetime(2019, 6, 21, 21, 4, 6, 256957, tzinfo=<UTC>), UUID('c339d797-f37d-48ff-94a6-e6d1510e23cc')), (datetime.datetime(2019, 6, 18, 17, 10, 18, 388505, tzinfo=<UTC>), UUID('00271b56-9ff7-4f9d-b9c0-2592ca9436d2'))]> In the QuerySet i've multiple datetime instance with UUID, I created this data using 2 different model and both model have different datetime field name, so i think we can't use CHAIN. Here I want to sort according to datetime Many Thanks in advance -
breadcrumb_url - Reverse for '' not found. '' is not a valid view function or pattern name
I'm trying to do breadcrumbs by this example https://www.djangosnippets.org/snippets/1289/ but have error Reverse for '' not found. '' is not a valid view function or pattern name.I did everything just like in this example. But I'm doing something wrong. Error in this line {% breadcrumb_url 'Home' product_list %} urls.py app_name = 'shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^show/(?P<slug>[-\w]+)$', views.product_show, name='product_show'), url(r'^(?P<category>[-\w]+)$', views.product_list, name='lst_by_ctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)$', views.product_list, name='lst_by_subctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)/(?P<kind>[-\w]+)$', views.product_list, name='lst_by_knds'), ] base.html {% load breadcrumbs %} <!DOCTYPE html> <html> <head> <title>Shop</title> <meta charset="utf-8"> </head> <body> {% block breadcrumbs %} {% breadcrumb_url 'Home' product_list %} {% endblock %} <div class="container"> {% block content %} {% endblock %} </div> </body> </html> breadcrumbs.py from django import template from django.template import loader, Node, Variable from django.utils.encoding import smart_str, smart_text from django.template.defaulttags import url from django.template import VariableDoesNotExist register = template.Library() @register.tag def breadcrumb(parser, token): """ Renders the breadcrumb. Examples: {% breadcrumb "Title of breadcrumb" url_var %} {% breadcrumb context_var url_var %} {% breadcrumb "Just the title" %} {% breadcrumb just_context_var %} Parameters: -First parameter is the title of the crumb, -Second (optional) parameter is the url variable to link to, produced by url tag, i.e.: {% url person_detail object.id as person_url %} then: {% … -
Error 404 not found raises 500 when Debug set to False
I recently tried to implement a custom view for my 404 and 500 errors on my website. It works well when debug is set to True, i.e. both the custom views work well when called. But as soon as set my Debug to False only the error 500 will be raised I tried already to call them by creating a url, both of the handler404 and handler500 custom view works well. This is the view where it should raise an error 404 when badly called: def arret(request, id): view = 'search/arret.html' arret = get_object_or_404(Arret, id=id) Here you can find my 404 custom view: def arret(request, id): def handler404(request, template_name="colorlib-error-404-19/index.html"): response = render_to_response("colorlib-error-404-19/index.html") response.status_code = 404 return response it raises an error 500 when trying to find a non existing Arret. this is what is written in the terminal ``bash System check identified no issues (0 silenced). June 22, 2019 - 08:55:31 Django version 2.0, using settings 'nora.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435 -
Python unsupported operand type(s) where everything is FloatField
one of my functions return the following error: unsupported operand type(s) for -: 'str' and 'float' this is the sippet im doing my math on: increased = decoded_balance["InGet"] - user.acc_cash_temp if decoded_balance["Unfulfilled"] == '0' and increased > 0: user.receiver.create(amount=increased, sender=system, type='usd') user.acc_cash_temp = decoded_balance["InGet"] user.acc_cash_balance += increased user.save() Where do i miss the field types? All mentioned fields like acc_cash_temp or acc_cash_balance are FloatField thanks and regards -
How to add label ID in Django Model Form
I am using Django modelform for label. However, I don't know how to add label ID and I find nothings on Internet. UserForm class UserForm(ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}), 'last_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Last Name', 'class': 'form-control input-md'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control input-md'}), } labels = { 'first_name': "Họ", 'last_name': "Tên", 'email': "Email", } First name label label style="margin-left: -48px; margin-right: 48px;" class="col-md-4 control-label" for="">First Name -
How to get dictionary items through javascript
I need to alert the dictionary items on page load.But so far no alert is getting displayed.Please help. data2 = {"iname": "name", "imodel": "dtls2"} return render(request, "home.html", data2) // inside home.html <script> for (var key in data2) { alert(data[key]); } </script> -
How to add custom HTML elements and images to a blog in Django?
I am trying to create a blog in Django. Most of the tutorials and examples available shows just retrieving some content from the database and displaying it dynamically on the predefined HTML structure. After looking at some solution I found something called flatpages in Django which provide the facility to write HTML. But its recommended to use it for About Us and Contact Us kind of pages. Should I use this? I want to do it as I can write my own HTML data for each blog and add some images so that the structure of HTML should not be similar in each blog. For example, In the case of WordPress, it allows the user to completely write each part of the blog except the heading part and the structure of HTML is not constant always. I want such functionality. Please help. -
Object not iterable in Django Rest API foreign key serializers
I am new in DRF! Trying to serialize my models even with foreign key. I want to the end-point should display data in foreign key related data. but i got an error and that is TypeError: 'Author' object is not iterable These are my serializer classes from rest_framework import serializers from . models import Author, Article, Category class AuthorSerializers(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class CategorySerializers(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(many=True) category = serializers.StringRelatedField(many=True) class Meta: model = Article fields = '__all__' and these are my models from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) detail = models.TextField() def __str__(self): return self.name.username class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and these are my views: class ArticleListCreateGet(ListAPIView, CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleSingle(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'pk' # This is delete/update method class ArticleDeleteUpdate(DestroyAPIView, UpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'pk' and these are my url path('api/v1/article', views.ArticleListCreateGet.as_view(), name='article'), path('api/v1/article/<int:pk>/detail', views.ArticleSingle.as_view(), name='article-single'), path('api/v1/article/<int:pk>', views.ArticleDeleteUpdate.as_view(), name='article-delete-update'), -
How to integrate django backend with react frontend?
I am working on a website which has its back-end developed in django and front-end developed in React.I have got the build folder from the react app. How should I proceed to integrate my back-end with react? -
Celery is not executing tasks concurrently
I'm new to celery, please let me know in comments if more information is required. I have around 3000 tasks queued in redis and i want to execute these tasks concurrently over multiple threads, after a bit of research i ended up using eventlet for thread pooling and set concurrency to 500, like so celery worker -A <app_name> -P eventlet -c 500 but when i checked celery flower many free threads are available which the celery is not using Any idea on how to make use of those free threads and make tasks faster? also if possible please suggest a good read for working with celery -
Django: Names are not showing in drop-down list
I need to show a list of countries for users to select from the ship's country field. But it's showing Country object(1), Country object(2)... instead of showing names of countries I've created classes for Ship and Country with the Ship class having a foreignkey of country. class Ship(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) callsign = models.CharField(max_length=50) last_updated = models.DateTimeField(auto_now=True, editable=False) weight = models.DecimalField(max_digits=20, decimal_places=4) # RelationShip Fields shipflag = models.ForeignKey( 'manifest.Country', on_delete=models.SET_NULL, related_name="Ships", null=True ) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('manifest_Ship_detail', args=(self.slug,)) def get_update_url(self): return reverse('manifest_Ship_update', args=(self.slug,)) class Country(models.Model): # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) code = models.CharField(max_length=5) # RelationShip Fields continent = models.ForeignKey( 'manifest.Continent', on_delete=models.CASCADE, related_name="Countrys", ) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('manifest_Country_detail', args=(self.slug,)) def get_update_url(self): return reverse('manifest_Country_update', args=(self.slug,)) In the 'create new ship' form at the country dropdown combo I expect to see a list of countries like United States, Mexico, Canada... but instead am seing countries as objects like this object(1), Country object(2)... -
Build dict through for loop without repetition
My code is currently very repetitive with grouped_events.setdefault('VAR', []).append(event) and event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get('VAR'). Do you see any better way in writing this? Currently, my best idea would be to write a function above where I insert the strings such as 'archived' etc. # Events by status grouped_events = {} for event in events: if event.status == EventStatus.ARCHIVED: grouped_events.setdefault('archived', []).append(event) elif event.status == EventStatus.DRAFT: grouped_events.setdefault('draft', []).append(event) elif event.is_over: grouped_events.setdefault('past', []).append(event) else: grouped_events.setdefault('live', []).append(event) event_data_by_organizer[organizer.pk][ 'events_archived' ] = grouped_events.get('archived') event_data_by_organizer[organizer.pk]['events_draft'] = grouped_events.get( 'draft' ) event_data_by_organizer[organizer.pk]['events_past'] = grouped_events.get( 'past' ) event_data_by_organizer[organizer.pk]['events_live'] = grouped_events.get( 'live' ) -
Is there a way to add ManyToMany filed inside current form (not in popup page) in django admin?
I have 2 models in django. the first one is Tag and second one is Article that is related to Tag models via ManyToMany fields. class Tag(models.Model): title = models.CharField(max_length=60, blank=False) class Article(models.Model): title = models.CharField(max_length=160) content = models.TextField() tags = models.ManyToManyField(Tag) When I want to and one or more tag(s) for article, a popup appears to add tag. I want to add this inside the current form. Is it possible? -
Add Extra fields in serializer from one to one relation models
In this project, I have two models Student and Parent related to each other through one to one field. In Parent serializer, I want to add Students attributes like age. I am thinking of using SerializerMethodField for both cases is their any better way to do it? I am not getting the queries on how to get the object attributes and little explanation would be great. Here what I have done till now. Models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) batch = models.ForeignKey(Batch, on_delete=models.CASCADE, null=True, related_name='students') email = models.EmailField(null=True) phone_number = models.CharField(max_length=10, null=True) dob = models.DateField(blank=True, null=True, help_text="Enter in the following format : YYYY-MM-DD") address = models.TextField(max_length=150, null=True) age = models.IntegerField(blank=True) image = models.ImageField(upload_to='profile_pictures', default='student_image.png', blank=True) @property def remarks(self): return self.remark_set.all() @property def marks(self): return self.marks_set.all() def __str__(self): return self.user.firstName + ' ' + self.user.lastName class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) child = models.ForeignKey(Student, on_delete=models.CASCADE) email = models.EmailField(null=True) phone_number = models.CharField(max_length=10, null=True) address = models.TextField(max_length=150, null=True) image = models.ImageField(upload_to='profile_pictures', default='student_image.png', blank=True) def __str__(self): return self.user.firstName + ' ' + self.user.lastName Serilaizer.py class ParentSerializer(serializers.HyperlinkedModelSerializer): student_age = serializers.SerializerMethodField() student_batch = serializers.SerializerMethodField() parent_name = serializers.SerializerMethodField() class Meta: model = Parent fields = "__all__" def get_student_age(self, obj): return Parent.objects.get(child__age = … -
Django annotate group by date return object
I'm using Django's annotate from the aggregate doc. My goal is to group a model by date and return all objects associated with each date in this form: [{ 'date': 'datetime.datetime(2019, 6, 22, 11, 35)' 'instances': [<Model: (1)>, <Model: (2)> ] }, { 'date': 'datetime.datetime(2019, 6, 21, 11, 35)' 'instances': [<Model: (3)>, <Model: (6)> ] },] I tried this query: Flight.objects.values('origin_scheduled_dep').annotate(Count('origin_scheduled_dep')).order_by('origin_scheduled_dep') But that's returning the values I specified: <QuerySet [{'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 11, 35), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 15, 40), 'origin_scheduled_dep__count': 1}, {'origin_scheduled_dep': datetime.datetime(2019, 6, 22, 22, 0), 'origin_scheduled_dep__count': 2}]> Thanks for any help, always :) -
How can i send matplot graph as a graph to django template but not as a image
I wanted to send matplot graph as a graph to my django template not as a image to template. How can i achieve this? This is my sample code which is successfully generate graph and send as a image but i want to send as a graph only so that if in my template someone hover at the data point, it should display annotation but saving as a image will not work so sending as a graph to template. def graph(request): register_matplotlib_converters() dates_in_string = ['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-04', '2010-01-21'] dates_datetime = [] m = pd.date_range('2015-07-03', '2015-07-20') print(m) for d in dates_in_string: dates_datetime.append(datetime.datetime.strptime(d, '%Y-%m-%d')) dates_float = matplotlib.dates.date2num(dates_datetime) list1 = [0,0,1,4,5,6,3,44,4,6,3,4,5,6,7,8,9,4] plt.grid(True) plt.plot_date(m, list1, linestyle='-', tz=None, xdate=True, ydate=False, label="chat-clicks") plt.title("Chat click Analysis") plt.ylabel("Chat clicks") plt.xlabel("Day") plt.legend(loc='upper left') # for i,j in zip(m,list1): # plt.annotate(str(j),xy=(i,j)) mplcursors.cursor(hover=True) plt.savefig("graph.png") # plt.show() figfile = BytesIO() plt.savefig(figfile, format='png', dpi=300) figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()).decode('utf-8').replace('\n', '') figfile.close() result = figdata_png return render(request,'graph.html', {"result":result})