-
Notifications
You must be signed in to change notification settings - Fork 0
/
Django 3 Source code - Python Web Framework.txt
1330 lines (1043 loc) · 75.6 KB
/
Django 3 Source code - Python Web Framework.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
www.youtube.com/watch?v=04L0BbAcCpQ
Django 3 Course - Python Web Framework (+ pandas, matplotlib, & more)
Learn Django, a Python web framework, in this full course. The course also covers pandas, matplotlib, JavaScript, ajax, xhtml2pdf, dropzone.js, and more!
You will learn about:
➜ django concepts (models, views, templates, signals and more!)
➜ pandas dataframes
➜ matplotlib and seaborn integration
➜ pdf integration
➜ javascript ajax integration
➜ dropzone js for csv files
➜ working with base64
➜ and more!
✏️ Course developed by Pyplane. Check out their channel: https://www.youtube.com/channel/UCQtHyVB4O4Nwy1ff5qQnyRw
💻 Source code and starter files: https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqbHE0WVBOZUpwNjFsT0FtcDkzZ1VybWxLdUEwUXxBQ3Jtc0tuOE8tS0VKcHJEUmpMakVwZDlveVNJbTF3dU5fZmRaNzV4a3NMUWhfV3N6LVRONmt4eW11NzAwUGNZU2o5eDhIZl8tdW5ycjlqTUlmQWltbDRTQ0M3VFBqeUplb09CVmFMSTMwUkNjVHpReVZjWkdmWQ&q=https%3A%2F%2Fblog.pyplane.com%2Fblog%2Fdjango-report-app%2F
⭐️ Coruse Contents ⭐️
⌨️ (0:00:00) intro
⌨️ (0:03:35) django project setup part 1
⌨️ (0:09:56) django project setup part 2
⌨️ (0:15:11) django project setup part 3
⌨️ (0:25:21) customer model
⌨️ (0:30:49) product model
⌨️ (0:36:30) profile model + post_save signal
⌨️ (0:48:14) sale model
⌨️ (1:12:05) m2m_changed signal
⌨️ (1:19:15) reports model
⌨️ (1:24:14) first view and template
⌨️ (1:33:25) working on the sales list
⌨️ (1:39:58) navigating to the detail page
⌨️ (1:49:27) creating the search form
⌨️ (1:58:15) get the data from the search form
⌨️ (2:01:08) first querysets and dataframes
⌨️ (2:17:05) display dataframes in the templates
⌨️ (2:24:04) dataframe for the positions
⌨️ (2:32:47) get the sales id for position objects
⌨️ (2:38:00) the apply function
⌨️ (2:49:01) merge dataframes
⌨️ (2:54:57) perform groupby
⌨️ (2:58:12) working on the charts part 1
⌨️ (3:02:58) working on the charts part 2
⌨️ (3:17:18) hello world from the console
⌨️ (3:21:29) adding the modal
⌨️ (3:29:04) add the report form to the modal
⌨️ (3:35:45) add the 'results by' field
⌨️ (3:50:02) no data available alert
⌨️ (3:53:51) add the chart to the modal
⌨️ (3:58:48) create report objects
⌨️ (4:28:46) adding alerts to the modal
⌨️ (4:33:27) report list and detail page
⌨️ (4:41:35) working on the report list
⌨️ (4:47:43) working on the report detail
⌨️ (4:51:33) first pdf
⌨️ (4:58:13) the report pdf
⌨️ (5:04:19) add dropzone + favicon
⌨️ (5:07:30) working on the dropzone js part 1
⌨️ (5:17:01) working on the dropzone js part 2
⌨️ (5:23:52) uploading csvs
⌨️ (5:35:45) first objects from file
⌨️ (5:49:27) improving the dropzone
⌨️ (5:56:15) dropzone js final touches
⌨️ (6:04:03) adding my profile
⌨️ (6:09:42) working on my profile
⌨️ (6:17:06) authentication
⌨️ (6:31:14) protecting the views
⌨️ (6:36:17) adding the navbar
⌨️ (6:49:03) the forgotten sale detail page
⌨️ (6:57:06) outro + next steps
🎉 Thanks to our Champion supporters:
👾 Otis Morgan
👾 DeezMaster
👾 Katia Moran
base.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- favicon -->
<link rel="shortcut icon" href="{% static 'favicon.ico' %}" />
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script>
<!-- Dropzone js -->
<link rel="stylesheet" href="{% static 'dropzone.css' %}">
<script src="{% static 'dropzone.js' %}" defer></script>
<!-- Custom js & css -->
<link rel="stylesheet" href="{% static 'style.css' %}">
{% block scripts %}
{% endblock scripts %}
<title>Report app | {% block title %}{% endblock title %}</title>
</head>
<body>
{% include 'navbar.html' %}
<div class="container mt-3 mb-3">
{% block content %}
{% endblock content %}
</div>
<!-- Bootstrap js -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js"></script>
</body>
</html>
pdf.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
</body>
</html>
navbar.html
{% load static %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href=""><img src="{% static 'logo.png' %}" class="logo-sm"></a>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Sales</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Add from file</a>
</li>
<li class="nav-item">
<a class="nav-link" href="">Reports</a>
</li>
</ul>
</div>
{% if request.user.is_authenticated %}
<div class="nav-item dropdown">
<div class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<img src="" class=""> {{request.user}}
</div>
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><a class="dropdown-item" href="">Profile</a></li>
<li><a class="dropdown-item" href="">Logout</a></li>
</ul>
</div>
{% endif %}
</div>
</nav>
Full source code
customers/models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=120)
logo = models.ImageField(upload_to='customers', default='no_picture.png')
def __str__(self):
return str(self.name)
customers/admin.py
from django.contrib import admin
from .models import Customer
admin.site.register(Customer)
products/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=120)
image = models.ImageField(upload_to='products', default='no_picture.png')
price = models.FloatField(help_text='in US dollars $')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.name}-{self.created.strftime('%d/%m/%Y')}"
products/admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
profiles.models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(default="no bio...")
avatar = models.ImageField(upload_to='avatars', default='no_picture.png')
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return f"Profile of {self.user.username}"
profiles/admin.py
from django.contrib import admin
from .models import Profile
admin.site.register(Profile)
profiles/signals.py
from .models import Profile
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def post_save_create_profile(sender, instance, created, **kwargs):
print(sender)
print(instance)
print(created)
if created:
Profile.objects.create(user=instance)
profiles/views.py
from django.shortcuts import render
from .models import Profile
from .forms import ProfileForm
from django.contrib.auth.decorators import login_required
@login_required
def my_profile_view(request):
profile = Profile.objects.get(user=request.user)
form = ProfileForm(request.POST or None, request.FILES or None, instance=profile)
confirm = False
if form.is_valid():
form.save()
confirm = True
context = {
'profile': profile,
'form': form,
'confirm': confirm,
}
return render(request, 'profiles/main.html', context)
profiles/urls.py
from django.urls import path
from .views import my_profile_view
app_name = 'profiles'
urlpatterns = [
path('', my_profile_view, name='my')
]
profiles/main.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block title %}
my profile
{% endblock title %}
{% block content %}
{% if confirm %}
<div class="alert alert-primary" role="alert">
Your profile has been updated
</div>
{% endif %}
<div class="text-center">
<img src="{{profile.avatar.url}}" alt="my-profile" class="avatar-big">
</div>
<br>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<button type="submit" class="btn btn-primary mt-3">update</button>
</form>
{% endblock content %}
reports/models.py
from django.db import models
from profiles.models import Profile
from django.urls import reverse
class Report(models.Model):
name = models.CharField(max_length=120)
image = models.ImageField(upload_to='reports', blank=True)
remarks = models.TextField()
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('reports:detail', kwargs={'pk': self.pk})
def __str__(self):
return str(self.name)
class Meta:
ordering = ('-created',)
reports/admin.py
from django.contrib import admin
from .models import Report
admin.site.register(Report)
reports/utils.py
import base64, uuid
from django.core.files.base import ContentFile
def get_report_image(data):
_ , str_image = data.split(';base64')
decoded_img = base64.b64decode(str_image)
img_name = str(uuid.uuid4())[:10] + '.png'
data = ContentFile(decoded_img, name=img_name)
return data
reports/views.py
from django.shortcuts import render, get_object_or_404
from profiles.models import Profile
from django.http import JsonResponse
from .utils import get_report_image
from .models import Report
from django.views.generic import ListView, DetailView, TemplateView
from .forms import ReportForm
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from sales.models import Sale, Position, CSV
from products.models import Product
from customers.models import Customer
import csv
from django.utils.dateparse import parse_date
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
class ReportListView(LoginRequiredMixin, ListView):
model = Report
template_name = 'reports/main.html'
class ReportDetailView(LoginRequiredMixin, DetailView):
model = Report
template_name = 'reports/detail.html'
class UploadTemplateView(LoginRequiredMixin, TemplateView):
template_name = 'reports/from_file.html'
@login_required
def csv_upload_view(request):
print('file is being')
if request.method == 'POST':
csv_file_name = request.FILES.get('file').name
csv_file = request.FILES.get('file')
obj, created = CSV.objects.get_or_create(file_name=csv_file_name)
if created:
obj.csv_file = csv_file
obj.save()
with open(obj.csv_file.path, 'r') as f:
reader = csv.reader(f)
reader.__next__()
for row in reader:
data = "".join(row)
data = data.split(';')
data.pop()
transaction_id = data[1]
product = data[2]
quantity = int(data[3])
customer = data[4]
date = parse_date(data[5])
try:
product_obj = Product.objects.get(name__iexact=product)
except Product.DoesNotExist:
product_obj = None
if product_obj is not None:
customer_obj, _ = Customer.objects.get_or_create(name=customer)
salesman_obj = Profile.objects.get(user=request.user)
position_obj = Position.objects.create(product=product_obj, quantity=quantity, created=date)
sale_obj, _ = Sale.objects.get_or_create(transaction_id=transaction_id, customer=customer_obj, salesman=salesman_obj, created=date)
sale_obj.positions.add(position_obj)
sale_obj.save()
return JsonResponse({'ex': False})
else:
return JsonResponse({'ex': True})
return HttpResponse()
@login_required
def create_report_view(request):
form = ReportForm(request.POST or None)
if request.is_ajax():
image = request.POST.get('image')
img = get_report_image(image)
author = Profile.objects.get(user=request.user)
if form.is_valid():
instance = form.save(commit=False)
instance.image = img
instance.author = author
instance.save()
return JsonResponse({'msg': 'send'})
return JsonResponse({})
@login_required
def render_pdf_view(request, pk):
template_path = 'reports/pdf.html'
obj = get_object_or_404(Report, pk=pk)
context = {'obj': obj}
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="report.pdf"'
template = get_template(template_path)
html = template.render(context)
pisa_status = pisa.CreatePDF(
html, dest=response)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' + html + '</pre>')
return response
reports/forms.py
from django import forms
from .models import Report
class ReportForm(forms.ModelForm):
class Meta:
model = Report
fields = ('name', 'remarks')
reports/upload.js
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
const alertBox = document.getElementById('alert-box')
const handleAlerts = (type, msg) => {
alertBox.innerHTML = `
<div class="alert alert-${type}" role="alert">
${msg}
</div>
`
}
Dropzone.autoDiscover = false
const myDropzone = new Dropzone('#my-dropozne', {
url: '/reports/upload/',
init: function() {
this.on('sending', function(file, xhr, formData){
console.log('sending')
formData.append('csrfmiddlewaretoken', csrf)
})
this.on('success', function(file, response){
console.log(response.ex)
if(response.ex) {
handleAlerts('danger', 'File already exists')
} else {
handleAlerts('success', 'Your file has been uploaded')
}
})
},
maxFiles: 3,
maxFilesize: 3,
acceptedFiles: '.csv'
})
reports/main.html
{% extends "base.html" %}
{% block title %}
reports
{% endblock title %}
{% block content %}
reports
<hr>
{% for obj in object_list %}
<div class="card mb-3">
{% if obj.image %}
<img src="{{obj.image.url}}" class="card-img-top" alt="{{obj.name}}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{obj.name}}</h5>
<p class="card-text">{{obj.remarks|truncatewords:2}}</p>
<a href="{{obj.get_absolute_url}}" class="btn btn-primary">details</a>
<a href="{% url 'reports:pdf' obj.pk %}" class="btn btn-danger">pdf</a>
</div>
</div>
{% endfor %}
{% endblock content %}
reports/detail.html
{% extends "base.html" %}
{% block title %}
{{object.name}}
{% endblock title %}
{% block content %}
{% if object.image %}
<img src="{{object.image.url}}" class="img-fluid" alt="{{object.name}}">
{% endif %}
<br>
<h3>Remarks</h3>
<p>{{object.remarks}}</p>
<hr>
<p>author: <b>{{object.author.user.username}}</b></p>
<p>created: <b>{{object.created}}</b></p>
{% endblock content %}
reports/from_file.html
{% extends "base.html" %}
{% load static %}
{% block scripts %}
<script src="{% static 'reports/upload.js' %}" defer></script>
{% endblock scripts %}
{% block title %}
upload sales files
{% endblock title %}
{% block content %}
<h5>Upload your sales documents</h5>
<br>
<div id="alert-box"></div>
<form id="my-dropozne" class="dropzone dz">
{% csrf_token %}
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
{% endblock content %}
reports/pdf.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PDF {{obj.name}}</title>
<style>
.image {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>{{obj.name}}</h1>
<hr>
<img src={{obj.image.path}} class="image">
<br>
<h3>Remarks</h3>
<p>{{obj.remarks}}</p>
<hr>
<p>author: <b>{{obj.author.user.username}}</b></p>
<p>created: <b>{{obj.created}}</b></p>
</body>
</html>
reports/urls.py
from django.urls import path
from .views import (
create_report_view,
ReportListView,
ReportDetailView,
render_pdf_view,
UploadTemplateView,
csv_upload_view
)
app_name = 'reports'
urlpatterns = [
path('', ReportListView.as_view(), name='main'),
path('save/', create_report_view, name='create-report'),
path('upload/', csv_upload_view, name='upload'),
path('from_file/', UploadTemplateView.as_view(), name='from-file'),
path('<pk>/', ReportDetailView.as_view(), name='detail'),
path('<pk>/pdf/', render_pdf_view, name='pdf'),
]
sales/models.py
from django.db import models
from products.models import Product
from customers.models import Customer
from profiles.models import Profile
from django.utils import timezone
from .utils import generate_code
from django.shortcuts import reverse
class Position(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
price = models.FloatField(blank=True)
created = models.DateTimeField(blank=True)
def save(self, *args, **kwargs):
self.price = self.product.price * self.quantity
return super().save(*args, **kwargs)
def get_sales_id(self):
sale_obj = self.sale_set.first()
return sale_obj.id
def get_sales_customer(self):
sale_obj = self.sale_set.first()
return sale_obj.customer.name
def __str__(self):
return f"id: {self.id}, product: {self.product.name}, quantity: {self.quantity}"
class Sale(models.Model):
transaction_id = models.CharField(max_length=12, blank=True)
positions = models.ManyToManyField(Position)
total_price = models.FloatField(blank=True, null=True)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
salesman = models.ForeignKey(Profile, on_delete=models.CASCADE)
created = models.DateTimeField(blank=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return f"Sales for the amount of ${self.total_price}"
def get_absolute_url(self):
return reverse('sales:detail', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
if self.transaction_id == "":
self.transaction_id = generate_code()
if self.created is None:
self.created = timezone.now()
return super().save(*args, **kwargs)
def get_positions(self):
return self.positions.all()
class CSV(models.Model):
file_name = models.CharField(max_length=120, null=True)
csv_file = models.FileField(upload_to='csvs', null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.file_name)
sales/admin.py
from django.contrib import admin
from .models import Position, Sale, CSV
admin.site.register(Position)
admin.site.register(Sale)
admin.site.register(CSV)
sales/signals.py
from .models import Sale
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
@receiver(m2m_changed, sender=Sale.positions.through)
def calculate_total_price(sender, instance, action, **kwargs):
print('action', action)
total_price = 0
if action == 'post_add' or action=='post_remove':
for item in instance.get_positions():
total_price += item.price
instance.total_price = total_price
instance.save()
sales/utils.py
import uuid, base64
from customers.models import Customer
from profiles.models import Profile
from io import BytesIO
import matplotlib.pyplot as plt
import seaborn as sns
def generate_code():
code = str(uuid.uuid4()).replace('-', '').upper()[:12]
return code
def get_salesman_from_id(val):
salesman = Profile.objects.get(id=val)
return salesman.user.username
def get_customer_from_id(val):
customer = Customer.objects.get(id=val)
return customer
def get_graph():
buffer = BytesIO()
plt.savefig(buffer, format='png')
buffer.seek(0)
image_png = buffer.getvalue()
graph = base64.b64encode(image_png)
graph = graph.decode('utf-8')
buffer.close()
return graph
def get_key(res_by):
if res_by == '#1':
key = 'transaction_id'
elif res_by == '#2':
key = 'created'
return key
def get_chart(chart_type, data, results_by, **kwargs):
plt.switch_backend('AGG')
fig = plt.figure(figsize=(10,4))
key = get_key(results_by)
d = data.groupby(key, as_index=False)['total_price'].agg('sum')
if chart_type == '#1':
print('bar chart')
sns.barplot(x=key, y='total_price', data=d)
elif chart_type == '#2':
print('pie chart')
plt.pie(data=d, x='total_price', labels=d[key].values)
elif chart_type == '#3':
print('line chart')
plt.plot(d[key], d['total_price'], color='green', marker='o', linestyle='dashed')
else:
print('ups... failed to identify the chart type')
plt.tight_layout()
chart = get_graph()
return chart
sales/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Sale
from .forms import SalesSearchForm
from reports.forms import ReportForm
import pandas as pd
from .utils import get_customer_from_id, get_salesman_from_id, get_chart
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
@login_required
def home_view(request):
sales_df = None
positions_df = None
merged_df = None
df = None
chart = None
no_data = None
search_form = SalesSearchForm(request.POST or None)
report_form = ReportForm()
if request.method == 'POST':
date_from = request.POST.get('date_from')
date_to = request.POST.get('date_to')
chart_type = request.POST.get('chart_type')
results_by = request.POST.get('results_by')
sale_qs = Sale.objects.filter(created__date__lte=date_to, created__date__gte=date_from)
if len(sale_qs) > 0:
sales_df = pd.DataFrame(sale_qs.values())
sales_df['customer_id'] = sales_df['customer_id'].apply(get_customer_from_id)
sales_df['salesman_id'] = sales_df['salesman_id'].apply(get_salesman_from_id)
sales_df['created'] = sales_df['created'].apply(lambda x: x.strftime('%Y-%m-%d'))
sales_df.rename({'customer_id': 'customer', 'salesman_id': 'salesman', 'id': 'sales_id'}, axis=1, inplace=True)
positions_data = []
for sale in sale_qs:
for pos in sale.get_positions():
obj = {
'position_id': pos.id,
'product': pos.product.name,
'quantity': pos.quantity,
'price': pos.price,
'sales_id': pos.get_sales_id(),
}
positions_data.append(obj)
positions_df = pd.DataFrame(positions_data)
merged_df = pd.merge(sales_df, positions_df, on='sales_id')
df = merged_df.groupby('transaction_id', as_index=False)['price'].agg('sum')
chart = get_chart(chart_type, sales_df, results_by)
print('chart', chart)
sales_df = sales_df.to_html()
positions_df = positions_df.to_html()
merged_df = merged_df.to_html()
df = df.to_html()
else:
no_data = 'No data is available in this date range'
context = {
'search_form': search_form,
'report_form': report_form,
'sales_df': sales_df,
'positions_df': positions_df,
'merged_df': merged_df,
'df': df,
'chart': chart,
'no_data': no_data,
}
return render(request, 'sales/home.html', context)
class SaleListView(LoginRequiredMixin, ListView):
model = Sale
template_name = 'sales/main.html'
class SaleDetailView(LoginRequiredMixin, DetailView):
model = Sale
template_name = 'sales/detail.html'
sales/urls.py
from django.urls import path
from .views import (
home_view,
SaleListView,
SaleDetailView,
)
app_name = 'sales'
urlpatterns = [
path('', home_view, name='home'),
path('sales/', SaleListView.as_view(), name='list'),
path('sales/<pk>/', SaleDetailView.as_view(), name='detail'),
]
sales/forms.py
from django import forms
CHART_CHOICES = (
('#1', 'Bar chart'),
('#2', 'Pie chart'),
('#3', 'Line chart'),
)
RESULT_CHOICES = (
('#1', 'transaction'),
('#2', 'sales date'),
)
class SalesSearchForm(forms.Form):
date_from = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
date_to = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))
chart_type = forms.ChoiceField(choices=CHART_CHOICES)
results_by = forms.ChoiceField(choices=RESULT_CHOICES)
sales/home.js
console.log('hello world')
const reportBtn = document.getElementById('report-btn')
const img = document.getElementById('img')
const modalBody = document.getElementById('modal-body')
const reportForm = document.getElementById('report-form')
const alertBox = document.getElementById('alert-box')
const reportName = document.getElementById('id_name')
const reportRemarks = document.getElementById('id_remarks')
const csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
const handleAlerts = (type, msg) => {
alertBox.innerHTML = `
<div class="alert alert-${type}" role="alert">
${msg}
</div>
`
}
if (img){
reportBtn.classList.remove('not-visible')
}
reportBtn.addEventListener('click', ()=>{
console.log('clicked')
img.setAttribute('class', 'w-100')
modalBody.prepend(img)
console.log(img.src)
reportForm.addEventListener('submit', e=>{
e.preventDefault()
const formData = new FormData()
formData.append('csrfmiddlewaretoken', csrf)
formData.append('name', reportName.value)
formData.append('remarks', reportRemarks.value)
formData.append('image', img.src)
$.ajax({
type: 'POST',
url: '/reports/save/',
data: formData,
success: function(response){
console.log(response)
handleAlerts('success', 'report created')
reportForm.reset()
},
error: function(error){
console.log(error)