Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to print in html the group permission in Django
if the customer sign in and he has permission to see the data that the admin has given him, he will see it after he sign in, but if the admin doesn't give him permission, this message will appear You are not authorized to view this page in my case no matter the permission given the admin this message always appears You are not authorized to view this page @login_required(login_url='loginpage') @allowed_users(allowed_roles=['active', 'staff']) def adminpage(request): return render(request, 'Homepage/adminsite.html') def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: username = request.POST['username'] request.session['username'] = username return redirect('adminpage') else: return render(request, 'Homepage/adminlogin.html') return render(request, 'Homepage/adminlogin.html') this is my decorators.py def unathenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('loginpage') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator this is my admin site (permission) this is my login looks like after I sign in -
Django Sql ERROR 1064 when accessing table
I cannot access one of the tables in my database. I can't even delete the table by myself, so I am not sure what to do. Here is the error: ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'match' at line 1 So this error appears every time I am doing an operation on that table (describe, select, drop, etc.) I have deleted the model from my code, but that doesn't remove the table from the db. -
Is a Machine Learning model made with keras and tensorflow and embeded like a website with django without database can be called a static website?
I have a website that actually deploys a model made with keras and tensorflow and is used for image recognition . the website has no database ... the model is pretrained . Can I call it a static website ? Can I Host the website on Netlify. -
login user from chrome extension
I need help in authenticate user login from chrome extension with jwt This is my manifest file { "manifest_version": 2, "name": "Time tracker", "description": "use this extension to send url and time to server", "author": "Ashkan Ganj", "version": "1.0", "browser_action": { "default_icon": "/icons/16.png", "default_title": "Time Tracker", "default_popup":"popup.html" }, "permissions": [ "tabs", "activeTab", "http://127.0.0.1:8000/*", "https://jsonplaceholder.typicode.com/posts", "storage", "http://*/", "https://*/" ], "content_scripts": [ { "matches": ["http://127.0.0.1:8000/*","https://jsonplaceholder.typicode.com/posts"], "js": ["packages/jquery-3.5.0.min.js","popup.js"] } ], "background": { "scripts": [ "background.js","packages/jquery-3.5.0.min.js" ], "persistent": false } } and my popup js to send login info, my problem is: how to send request and get access and refresh token and store them in session storage in order to login user $("#submitbtn").click(function (sendReq) { var email = $("#email").val(); var password = $("#password").val(); sessionStorage.setItem("userToken", ""); }); function sendReq() { let sendReq = (ev) => { let url = "https://jsonplaceholder.typicode.com/posts"; let h = new Headers(); let req = new Request(url, { method: "POST", mode: "cors", }); fetch(req) .then((resp) => resp.json()) .then((data) => { console.log(data[0]); }) .catch((err) => { console.error(err.message); }); }; } my path to get token and refresh token api/token and api/token/refresh my rest framework get token pic Thanks for your helps. -
Django Rest Framework: make a field not required in modelviewset create
I have a model which have got a field for showing time it created, named created_time. I don't want created_time to be required when creating model, but I want it to be in retrieved data from model! This is its serializer: class ModelSerializer(ModelSerializer): class Meta: model = Model fields = ['name', 'created_time'] And this is its viewset: class ModelApiView(ModelViewSet): serializer_class = ModelSerializer def get_queryset(self): return Model.objects.filter(user=self.request.user.id) def perform_create(self, serializer): serializer.save(user=self.request.user, created_time=datetime.now()) Right now, by get request it sends a list of Model objects with name and created_time which is perfect. But when I post a new Model to be created, containing just its name, it sends me this error message: { "datetime": [ "This field is required." ] } -
Django PIL AttributeError: type object 'ImageFont' has no attribute 'truetype'
Please help me to understood what I do wrong. I use wagtail. In models.py import code. Nothing else is imported with the ImageFont name. from PIL import Image from PIL import ImageDraw from PIL import ImageFont Function code def save_image(img, text): pos = (10, 20) black = (3, 3, 3) font = ImageFont.truetype("arial.ttf", 40) in_path = dirPath + '/media/original_images/' + str(img) out_path = dirPath + '/media/to_share_imgs/' + str(img) photo = Image.open(in_path) drawing = ImageDraw.Draw(photo) drawing.text(pos, text, fill=black, font=font) photo.save(out_path) I get an error Django PIL AttributeError: type object 'ImageFont' has no attribute 'truetype' -
How to get the data including the relation table's entry with a GET request in DRF
I'm trying my hand at DRF recently and I've got this issue below to be solved for my project. I think you people can help me out here. I've two Models class JobsMaster(models.Model): job_id = models.CharField(max_length=128, unique=True) job_name = models.CharField(max_length=128) scheduled_time = models.CharField(max_length=128) args = models.TextField() interval = models.CharField(max_length=50) repeat = models.CharField(max_length=100) class JobProcessDetails(models.Model): job_id = models.ForeignKey('JobsMaster') sequence = models.IntegerField() step_name = models.CharField(max_length=128) records = models.IntegerField(null=True,blank=True) created_by = models.CharField(max_length=155,default='system') created_on = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (('job_id', 'sequence'),) Corresponding Serializers class JobsMasterSerializer(serializers.ModelSerializer): class Meta: model = JobsMaster fields = '__all__' class JobProcessDetailsSerializer(serializers.ModelSerializer): class Meta: model = JobProcessDetails fields = '__all__' their Viewsets class JobsMasterViewSet(viewsets.ModelViewSet): queryset = JobsMaster.objects.all() serializer_class = JobsMasterSerializer filter_fields = ('job_id',) class JobProcessDetailsViewSet(viewsets.ModelViewSet): queryset = JobProcessDetails.objects.all() serializer_class = JobProcessDetailsSerializer filter_fields = ('job_id','sequence',) I do not know if this is the right way to build viewsets and serializer but it worked for me. I want to write a GET request from UI to fetch the data from JobProcessDetails which includes the data from the related JobsMaster table as well. for example, the response data should be containing the below fields job_id : xxxxx sequence : xxxx step_name : 'xxxx' records : xxxx created_by : 'xxxxx' created_on : dd/mm/yyyy job_id__job_name … -
Finding intersection of two querysets of two different models
My models.py looks something like class RelevanceRelation(TimeStampable, SoftDeletable, models.Model): relevance_type = models.ForeignKey( RelevanceType, on_delete=models.CASCADE, related_name="relevance_relations" ) name = models.CharField(max_length=256, verbose_name="Relevance Relation Name") def __str__(self): return self.name class RelevanceRelationValue(TimeStampable, SoftDeletable, models.Model): entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="relevance_relation_values" ) relevance_relation = models.ForeignKey( RelevanceRelation, on_delete=models.CASCADE, related_name="values" ) name = models.CharField(max_length=256, verbose_name="Relevance Relation Value") def __str__(self): return self.name And I have two querysets q1 = RelevanceRelationValue.objects.filter(entity=<int>) q2 = RelevanceRelation.objects.filter(relevance_type=<int>) Now is there a way to find intersection of q1 and q2 i.e I wan't to display all the values of q2 whose id is present in q1 as rulevance_relation for example q1 = ------------------------------- | entity | relevance_relation | ------------------------------- | 1 | 1 | | 1 | 2 | | 1 | 3 | ------------------------------- and q2 = ------------------------------- | id. | relevance_type | ------------------------------- | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 1 | | 5 | 1 | | 6 | 1 | ------------------------------- so q3 should be ------------------------------- | id. | relevance_type | ------------------------------- | 1 | 1 | | 2 | 1 | | 3 | 1 | ------------------------------- Thanks in advance. -
How to send javascript variable to django
I am building a web app, where a user can set a value to a specific number. It looks like that <button type="button" class="btn btn-outline-primary" onclick="decrease()"> +1 </button> <button type="button" class="btn btn-outline-primary" onclick="increase()"> -1 </button> <script> var a = 0; function increase() { a--; document.getElementById("val").innerHTML = a; } function decrease() { a++; document.getElementById("val").innerHTML = a; } </script> Now I would like add an other button like: <button type="button" class="btn btn-outline-primary" onclick="send()"> send it </button> But I don't really now how to send it (maybe I should use axaj and POST). I would like to access the value from my django view.py file and process it further and send it back (here it's GET). How can I do it? Appreciate any help here -
connection error when importing pytorch/fastai apache
I have a Django app running locally when I tried deploying it doesn't work on apache unless I comment the import of the library ptporch/fastai in my views. the app works locally on the same environment I use for the mod_wsgi. i'm using django 2.1.7 python 3.6 mod_wsgi 4.7 windows server 2016 I have set the WSGIApplicationGroup to %{GLOBAL} already ( for other libraries like NumPy ). this how my vhosts looks like : <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On WSGIApplicationGroup %{GLOBAL} ErrorLog "logs/Eyelizer.error.log" CustomLog "logs/Eyelizer.access.log" combined WSGIScriptAlias / "C:\Users\administrator\Eyelizer\Eyelizer\wsgi_windows.py" <Directory "C:\Users\administrator\Eyelizer\Eyelizer"> <Files wsgi_windows.py> Require all granted </Files> </Directory> </VirtualHost> the apache service is running but when I try to access any page it just gives connection error and the import line is just from fastai.vision import * -
Can I Use A PDF As A Template In ReportLab
Im using ReportLab in Django to create pdf documents but cannot find any information on whether or not I can use a pdf as a template rather than have it begin with a blank file. The reason I dont just want to add the template contents within Django is that I have a watermarked pdf id like to use. My very basic code so far: def generate_enrolment_pdf(request): # get user user = request.user doc = SimpleDocTemplate(settings.MEDIA_ROOT+'\pdfs\\enrolment_form_%s.pdf' %user.id) styles = getSampleStyleSheet() enrolment_form = [Spacer(1,2*inch)] style = styles["Normal"] text = ("Name: %s %s" % (user.personalinformation.first_name, user.personalinformation.surname)) p = Paragraph(text, style) enrolment_form.append(p) enrolment_form.append(Spacer(1,0.2*inch)) doc.build(enrolment_form) Thank you. -
Google Cloud Storage vs Google Cloud CDN
I have several video content that I share through my Google Cloud Storage through my Django Google App Engine Application with signed url mechanism associated with an expiration time. def get_signed_url(self, entity): blob = bucket.get_blob(entity.url) logging.info(entity.url) expiration_time = timezone.now() + timedelta(minutes=120) signed_url = blob.generate_signed_url(expiration_time) logging.info(signed_url) return signed_url Although it has been explained in [here][1] possible usage relationship of GCS and Google Cloud CDN, would this be applicable to stream video content (MP4 or MPEG-DASH with MP4) through Google Cloud Storage as it is mentioned to have an implicit CDN itself. If using Google CDN is a wiser way to broadcast online video content, what would be the best strategy to achieve this, how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage ? -
Choosing an asset manager: can django-pipeline organize filename fingerprints?
Django 3.0.6 Django-Pipeline 2.0.2 I'm choosing a ready made application to combine JavaScript and CSS files. What I need: 1. HTML5 Manifest. 2. Filename fingerprinting (making unique filenames for combined files every time). Othervise if we configure components to be cached by browsers and proxies, users will not get updates when those components change. Now I'm considering: django-pipeline I have chosen it from these alternatives: https://djangopackages.org/grids/g/asset-managers/ It supports HTML5 manifest. Could you tell me whether it can organize filename fingerprints? -
i am unable to install mysqlclient using cmd
C:\Users\Yash Patel>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\yash patel\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\YASHPA~1\AppData\Local\Temp\pip-install-sc96zvsc\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\YASHPA~1\AppData\Local\Temp\pip-install-sc96zvsc\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\YASHPA~1\AppData\Local\Temp\pip-record-diaiyo1_\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\yash patel\appdata\local\programs\python\python37-32\Include\mysqlclient' cwd: C:\Users\YASHPA~1\AppData\Local\Temp\pip-install-sc96zvsc\mysqlclient\ Complete output (30 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Ic:\users\yash patel\appdata\local\programs\python\python37-32\include" "-Ic:\users\yash patel\appdata\local\programs\python\python37-32\include" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS … -
Django form JSON
Please tell me where the problem is: I need to process a JSON request, what should I access and what should I return? and this is the essence of the problem, because the answer comes to me on the server, that there is a problem with the token. contact.html: <form class="feedback__form" id="contact_form" role="form" action="{% url 'contact' %}" method="post"> {% csrf_token %} <div class="feedback__inv-msg feedback__response-msg"> <span> ERROR</span> </div> <div class="feedback__form-wrapper"> <ul class="feedback__field-list"> <li class="feedback__field-item"> <div class="feedback__field-title txt txt_font_mp_regular txt_size_18"><span>YOUR NAME</span></div> <div class="feedback__field-inp"> {{ contact_form.contact_name }} </div> </li> <li class="feedback__field-item"> <div class="feedback__field-title txt txt_font_mp_regular txt_size_18"><span>YOUR MAIL</span></div> <div class="feedback__field-inp"> {{ contact_form.contact_email }} </div> <li class="feedback__field-item"> <div class="feedback__field-title txt txt_font_mp_regular txt_size_18"><span>YOUR PHONE</span></div> <div class="feedback__field-inp"> {{ contact_form.contact_phone }} </div> <li class="feedback__field-item"> <div class="feedback__field-title txt txt_font_mp_regular txt_size_18"><span>YOUR PROBLEM</span></div> <div class="feedback__field-inp"> {{ contact_form.content }} </div> </li> <div class="feedback__controls"> <button class="btn btn_compact feedback__sender" type="submit">SEND</button> </div> <div class="feedback__response"> <div class="feedback__positive feedback__response-msg"><span>YOUR MESSAGE WAS SENT</span></div> <div class="feedback__negative feedback__response-msg"><span>YOUR MESSAGE WASNT SENT</span></div> </div> </form> <script type="text/javascript"> class Form { constructor(){ this.element = document.querySelector(`.feedback`) this.init() this.isValid = false this.values = {} } addClassesToImps(){ for(let elem of this.element.querySelectorAll(`input`)) elem.classList.add(`inp`) this.element.querySelector(`input[type="hidden"]`).classList.remove(`inp`) } getStructure(){ this.addClassesToImps() this.form = this.element.querySelector(`.feedback__form`) this.inps = this.element.querySelectorAll(`.inp`) this.reqInps = this.element.querySelectorAll(`.inp[required]`) this.sender = this.element.querySelector(`.feedback__sender`) } handleValidityCheck(elem){ if(!elem.checkValidity()){ elem.classList.add(`inp_invalid`) this.isValid = false } … -
Can we pass a default parameter into url of view function anywhere from the html page
I have this nav bar in my html page, on clicking it needs to re-direct to the same page cart-home so passing the hard values on each nav item clicked. Can I pass a value of 'mobiles' into url(If in case no nav item is clicked) anywhere on my base.html file / this can be handled in views in any way? base.html <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #f8f9fa!important;"> <a class="navbar-brand" href="#"><stron>Categories</strong></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'cart-home' 'mobiles' %}"><strong>Mobiles</strong></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'cart-home' 'laptops' %}"><strong>Laptops</strong></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'cart-home' 'ca' %}"><strong>Computer Accessories</strong></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'cart-home' 'ma' %}"><strong>Mobile Accessories</strong></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'cart-home' 'others' %}"><strong>Others</strong></a> </li> </ul> </div> </nav> views.py @login_required def home(request, category): filtered_orders = Order.objects.filter( owner=request.user.profile, is_ordered=False) current_order_products = [] if filtered_orders.exists(): user_order = filtered_orders[0] user_order_items = user_order.items.all() current_order_products = [item.product for item in user_order_items] print(category) if category: context = { 'products': Product.objects.filter(product_type=category), 'current_order_products': current_order_products, 'title': 'Home', } else: context = { 'products': Product.objects.filter(product_type='Mobiles'), 'current_order_products': current_order_products, 'title': 'Home', } return render(request, 'product/cart_home.html', … -
Cannot order a sliced queryset
I have this: def get_most_frequent_ledger(self): """ Returns ordered queryset of ledgers by count """ if self.lineitems(): ledgers = self.lineitems().values("ledger").annotate(count=Count('ledger')).order_by("-count") else: return None return Ledger.objects.get(pk=ledgers[0]['ledger']) But need this: def get_most_frequent_ledger(self): """ Returns ordered queryset of ledgers by count """ if self.lineitems()[0:9]: ledgers = self.lineitems()[0:9].values("ledger").annotate(count=Count('ledger')).order_by("-count") else: return None return Ledger.objects.get(pk=ledgers[0]['ledger']) I basically want the query to only look at the ten most recent lineitems. The code says I can't order a sliced queryset. Is there a workaround? -
Django user permission to view the record
How do i know if that user have a permission to view the record or data? and how do i call it in my template? thank you in advance. def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: username = request.POST['username'] request.session['username'] = username if request.user.has_perm('app_name'): return render(request, 'Homepage/adminsite.html' ?????) else: return render(request, 'login.html') return render(request, 'login.html') -
Bootstrap fixed width table columns in container fluid
I have a question for you. I'm trying to fix the size of my table colum in a container fluid div. I have tried to set style="width: xx.x%" but it continues to change based on the cell content. I have also tried with max-with, but it continues to do not work. Below my code: <div class="container-fluid"> <div class="row"> <div class="col-12"> <table class="table table-sm text-nowrap"> <thead> <tr class="bg-info text-white"> <th style="max-width: 1%">2020</th> <th style="max-width: 9%">Voci</th> <th class="text-center" style="max-width: 7.5%">Gen</th> <th class="text-center" style="max-width: 7.5%">Feb</th> ....... I want that the column have a fixed width (ad example max and min equal to 7.5%). How could I get this in bootstrap? -
saving multiple models in django
i need some help in my django project. i am new and am trying to save data to three models in view form. I am new to django and am trying to develop a web app for a farm management. My form i want to register a farm. i have three models, which are related and i want them to be save to the database from on function. The model has three models as Phonenumbers, address and farm. Model.py from django.db import models from django.contrib.auth.models import User from datetime import datetime, date class Farms(models.Model): farm_name = models.CharField(max_length=200, blank = True) recorded_by = models.ForeignKey(User, default= None, null=True, on_delete=models.CASCADE) def __str__(self): return self.farm_name COUNTRY_CHOICES = ( ('Nig','Nigeria'), ('AF', 'Afghanistan'), ('AL' ,'Albania'), ('DZ' , 'Algeria'), ('AX' , 'Aland'), ('AS' , 'American'), ('AI' , 'Anguilla'), ( 'AD' , 'Andorra'), ('AO' , 'Angola'), ('AN' ,' Antilles - Netherlands'), ) class Address(models.Model): street_name = models.CharField(max_length = 200, blank = True) street_no = models.CharField(max_length = 50, blank = True) city = models.CharField(max_length = 200) state = models.CharField(max_length = 200) country = models.CharField(max_length = 200, choices=COUNTRY_CHOICES, default='Nig') farms = models.ForeignKey(Farms, on_delete=models.CASCADE) class Telephone(models.Model): phonenumber = models.CharField(max_length = 200) farms= models.ForeignKey(Farms, on_delete=models.CASCADE) def __str__(self): return self.phonenumber Form.py from django … -
django ValidationError not raised in test but raised in shell
I have a model defined below which invokes the manager in the clean() method. from django.core.exceptions import ValidationError from django.db import models from re import sub class Vessel(models.Model): name = models.CharField(max_length=50) stripped_name = models.CharField( max_length=50, unique=True, null=True, blank=True ) def save(self, *args, **kwargs): stripped_name = sub(r'\s+', ' ', str(self.name).upper().strip()) stripped_name = sub(r'^M[^a-zA-Z]*V\s*', '', stripped_name) stripped_name = sub(r'[^\w]', '', str(stripped_name).upper()) self.stripped_name = stripped_name super().save(*args, **kwargs) def clean(self): stripped_name = sub(r'\s+', ' ', str(self.name).upper().strip()) stripped_name = sub(r'^M[^a-zA-Z]*V\s*', '', stripped_name) stripped_name = sub(r'[^\w]', '', str(stripped_name).upper()) if Vessel.objects.all().filter(stripped_name = stripped_name).exists(): return ValidationError("Vessel name exists.") In a freshly flushed shell, IntegrityError is raised fine. >>> from my_random_app.models import Vessel >>> vessel = Vessel(name='PM Hayabusa') >>> vessel.save() >>> vessel = Vessel(name=' M/V PM-HAYABUSA') >>> vessel.save() # Raises IntegrityError Even ValidationError is raised fine. >>> from my_random_app.models import Vessel >>> vessel = Vessel(name='PM Hayabusa') >>> vessel.save() >>> vessel = Vessel(name=' M/V PM-HAYABUSA') >>> vessel.clean() # Raises ValidationError But in the automated test, ValidationError is not raised. from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from django.test import TestCase from my_random_app.models import Vessel class VesselTest(TestCase): def setUp(self): pass def test_a(self): vessel = Vessel(name='PM Hayabusa') vessel.save() vessel = Vessel(name=' M/V PM-HAYABUSA') self.assertRaises(IntegrityError, vessel.save) def test_b(self): vessel = Vessel(name='PM Hayabusa') … -
Shopping cart DB not showing number of Individual Items Ordered
I'm trying to create a shopping cart model, I've created the Order Model, OrderItem model and Also the Item model. Although I find it difficult to link the order it model to the order in the API view. here's the Model class Pizza(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) desc = models.CharField(max_length=150) price = models.IntegerField() url = models.CharField(max_length=250) def __str__(self): return self.name class OrderItem(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey("Pizza", on_delete=models.CASCADE, null=True) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null=True) amount = models.IntegerField(null=True) def __str__(self): return self.product.name class Order(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) email = models.CharField(max_length=150) address = models.CharField(max_length=150) total = models.IntegerField() created_at = models.DateTimeField(default=timezone.now) items = models.ManyToManyField(OrderItem) def __str__(self): return self.name //The viewset class OrderViewSet(viewsets.HyperlinkedModelSerializer): # permission_classes = [IsPostOrIsAuthenticated,] serializer_class = OrderSerializer queryset = Order.objects.all().order_by('-created_at') Currently, I cant display the amount attribute of the order item in my API, It just shows the id and Also the link to the individual orderitem in an order -
Save data into a model automatically
I'm buildin an api rest, also I consume an api who returned some data there is a method called get_department who return a list def get_departments(): response = requests.get(PLACES_ENDPOINT) if response.status_code == 200: data = response.json() departamentos = [] for item in data: departamentos.append(item['departamento']) departamentos = sorted(set(departamentos)) return departamentos there is a model class Department(models.Model): name = models.CharField(max_length=40, unique=True, blank=False) def __str__(self): return self.name I want to create an object for every item in the list departamentos I was thinking maybe overwrite the init method of Department model to save every record -
Static files don't load in django login.html
My problem: static files in django can't load in my login.html. For example, it perfectly loads in my index.html, but not in login.html. I've tried everything: changing settings, urls, nothing works. Here is the code for login.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Login</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body data-spy="scroll" data-target=".site-navbar-target" data-offset="300"> <div class="site-wrap"> <div class="site-mobile-menu site-navbar-target"> <div class="site-mobile-menu-header"> <div class="site-mobile-menu-close mt-3"> <span class="icon-close2 js-menu-toggle"></span> </div> </div> <div class="site-mobile-menu-body"></div> </div> <header class="site-navbar py-4 js-sticky-header site-navbar-target" role="banner"> <div class="container-fluid"> <div class="d-flex align-items-center"> <div class="site-logo mr-auto w-25"><a href="index.html">LearnContact</a></div> <div class="ml-auto w-25"> <nav class="site-navigation position-relative text-right" role="navigation"> <ul class="site-menu main-menu site-menu-dark js-clone-nav mr-auto d-none d-lg-block m-0 p-0"> <li class="cta"><a href="#contact-section" class="nav-link"><span>Contact Us</span></a></li> </ul> </nav> <a href="#" class="d-inline-block d-lg-none site-menu-toggle js-menu-toggle text-black float-right"><span class="icon-menu h3"></span></a> </div> </div> </div> </header> <div class="intro-section" id="home-section"> <div class="slide-1" style="background-image: url({% static 'images/hero_1.jpg' %});" data-stellar-background-ratio="0.5"> <div class="container"> <div class="row align-items-center"> <div class="col-12"> <div class="row align-items-center"> <div class="col-lg-6 mb-4"> <h1 data-aos="fade-up" data-aos-delay="100">Learn From The Expert</h1> <p class="mb-4" data-aos="fade-up" data-aos-delay="200">Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime ipsa nulla sed quis rerum amet natus quas necessitatibus.</p> <p data-aos="fade-up" data-aos-delay="300"><a href="#" class="btn btn-primary py-3 px-5 btn-pill">Admission Now</a></p> </div> <div class="col-lg-5 ml-auto" data-aos="fade-up" data-aos-delay="500"> <form … -
Django - How to get count for select fields in model within same dictionary
I am currently working on producing data analytics, and I am struggling with grouping the data in the format that is required. This is my models.py class CustomerInformation(models.Model): status = ( ('lead', 'Lead'), ('client', 'Client'), ) customer_name = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=status, default='lead') creator = models.ForeignKey('UserProfile', related_name='customers', on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateField(default=timezone.now) Assuming there are 5 instances of this model, namely: 1) customer_name: '-', status: 'lead', creator: 'User 1', created_date: '23 May 20' 2) customer_name: '-', status: 'lead', creator: 'User 1', created_date: '21 May 20' 3) customer_name: '-', status: 'lead', creator: 'User 2', created_date: '08 May 20' 4) customer_name: '-', status: 'client', creator: 'User 2', created_date: '16 May 20' 5) customer_name: '-', status: 'client', creator: 'User 2', created_date: '04 April 20' I am trying to get the data to be in this format: { April: [{ creator: 'User 2', lead_count: 0, client_count: 1}], May: [{ creator: 'User 1', lead_count: 2, client_count: 0}, { creator: 'User 2', lead_count: 1, client_count: 1}] } Basically, I want to be able to count the number of times a value (lead or client) is selected from the status field, per user, per month. I tried using annotation, but it returned the counts in …