Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'QuerySet' object has no attribute 'active' in Django rest framework
I am trying to implement Coupon code feature in Django Rest framework. When a user tries to purchase a product and wants to use coupon codes presented on the item, the user should be able to get a discount based on that coupon code. The coupon should be vaild ie should be within the valid till date and also should be active. But when I try to make an order object from postman without sending the coupon codes, I got the following error. AttributeError: 'QuerySet' object has no attribute 'active' Before the application of Coupon code feature, I was able to make an order. My models: class Coupons(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, blank=True,null=True,related_name="coupons") code = models.CharField(max_length=50,unique=True) valid_form = models.DateField() valid_till = models.DateField() active = models.BooleanField(default=False) discount = models.IntegerField(default=0) def __str__(self): return self.code Order model: Here every calculation for the prices are done. class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_ID = models.CharField(max_length=12, editable=False, default=id_generator) #order_items = models.ManyToManyField('OrderItem',blank=True, null=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) current_points = models.FloatField(default=0) total_price = models.FloatField(blank=True,null=True) point_spent = models.FloatField(default=0) coupon_code = models.CharField(max_length=15, blank=True, null=True) def final_price(self): total = sum([_.price_1 for _ in self.order_items.all()]) total -= Decimal(self.price_of_points) dis = self.price_of_coupon print(dis) total = total - … -
how to search or filter data of two different model and return it in one
I have two models. First model is about the main information and the Second one is the detail of the first model(actually its about the way that the first one is delivered) and the second model has the ForeignKey of the first one and each data of the first model can have many data in the second one. what I want to do is to filter the data of both models and return it in one row of table! My First Model : class Report(models.Model): factory_account = models.ForeignKey(Account, on_delete=models.CASCADE) factory_state = models.CharField(choices=State, max_length=20) factory_id = models.IntegerField() factory_name = models.CharField(max_length=50) buyer_state = models.CharField(choices=State, max_length=20) buyer_name = models.CharField(max_length=50) buyer_national_id = models.IntegerField() buyer_city = models.CharField(max_length=50) buyer_address = models.CharField(max_length=500) landline_buyer_phone = models.IntegerField() buyer_phone = models.IntegerField() date = jmodels.jDateField() invoice_number = models.IntegerField(unique=True) bran_number = models.IntegerField() price = models.IntegerField() delivered = models.IntegerField() delivery_balance = models.IntegerField() My Second Model : class DeliverDetail(models.Model): invoice_number = models.ForeignKey(Report, on_delete=models.CASCADE, null=True) date = jmodels.jDateField() delivered = models.IntegerField() car_type = models.CharField(max_length=20) car_tag = models.CharField(max_length=20) driver_name = models.CharField(max_length=50) driver_national_code = models.IntegerField() My Filter.py (Using Django-filter(https://pypi.org/project/django-filter/)): class myFilter(django_filters.FilterSet): car_type = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_type') car_tag = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_tag') driver_name = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__driver_name') driver_national_code = django_filters.NumberFilter(lookup_expr='iexact', distinct=True, field_name='deliverdetail__driver_national_code') class Meta: model = Report fields … -
Django: how to show a narrowed drop-down list based on the previous selection?
For example I would like make an instance CAR with two information: Manufaturer and CarModel. class Manufacturer(models.Model): name = models.CharField(max_length=10, blank=False) class CarModel(models.Model): name = models.CharField(max_length=10, blank=False) class Car(models.Model): producer = models.OneToOneField(Manufacturer, on_delete=models.CASCADE()) carmodel = models.OneToOneField(CarModel, on_delete= models.CASCADE()) Of course before I would make an instance for class Car I would have to make instances for class Manufacturer and CarModel. I would make BMW, Volvo, Toyota for Manucaturer and then series 3, series 5, X5, X7, XC90, V40, Prius, Land Cruiser, Corolla. Finally when I would make an instance for class Car I would see first: BMW, Volvo, Toyota I would choose Toyota and then I would like see in next drop-down list only: Prius, Land Cruiser, Corolla Of course BMW does not manufature Prius :) How can I do something like filter for that? -
What mistake am I making to cause these Django E304 errors?
I cannot for the life of me figure out what I'm doing wrong here, any help would be very much appreciated! The Goal: We have admins and appraisers signing up on the site. Admins can of course do everything you'd expect from the /admin site and appraisers have their own site, /portal. What I'm trying to do now is improve my current model so that I can add more fields to the appraiser users. The admin user's fields are a subset of the appraiser user's fields. The Error: SystemCheckError: System check identified some issues: ERRORS: accounts.Appraiser.groups: (fields.E304) Reverse accessor for 'accounts.Appraiser.groups' clashes with reverse accessor for 'accounts.Admin.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.groups' or 'accounts.Admin.groups'. accounts.Appraiser.user_permissions: (fields.E304) Reverse accessor for 'accounts.Appraiser.user_permissions' clashes with reverse accessor for 'accounts.Admin.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.user_permissions' or 'accounts.Admin.user_permissions'. accounts.Admin.groups: (fields.E304) Reverse accessor for 'accounts.Admin.groups' clashes with reverse accessor for 'accounts.Appraiser.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.groups' or 'accounts.Appraiser.groups'. accounts.Admin.user_permissions: (fields.E304) Reverse accessor for 'accounts.Admin.user_permissions' clashes with reverse accessor for 'accounts.Appraiser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.user_permissions' or 'accounts.Appraiser.user_permissions'. Before … -
How to access list of dictionary in Django template
I am very new to Django and implemented a post-api call by watching couple of tutorials and one of the fields gets a list of dictionaries, want to access the key value pair in Django template, instead it is taking char by char, how to solve this problem? models.py class Leads(models.Model): Name = models.CharField(max_length=50) Mobile = models.CharField(max_length=13) Email = models.CharField(max_length=50) Message = models.CharField(max_length=300) created_on = models.DateTimeField(default=datetime.now()) modified_on = models.DateTimeField(default=datetime.now()) Example input for above api call will be: Name = rakesh Mobile = 1234567890 Email = email@mail.com Message = [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] template.html {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> <td>{{user.Message}}</td> </tr> {%endfor%} If I try like above then the output is rakesh 1234567890 emaik@mail.com [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] If I add another loop for Message field then the Message field is not showing any output: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message %} <td>{{i.key}}</td> <td>{{i.value}}</td> {%endfor%} </tr> {%endfor%} Output: displaying string by string rakesh 1234567890 emaik@mail.com If I try like this then: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message … -
Template tags not working inside an included template
I include tags inside an included template. However, even though I extend the base template, in my templates (list.html) the tags are not rendered. Perhaps something I am missing? base.html: <div class="content-page"> <div class="content"> <div class="container-fluid"> {% include 'partials/pageTitle.html' %} </div> </div> </div> partials/pageTitle.html: <h4 class="page-title">{% block pageTitle %}{% endblock pageTitle %}</h4> list.html (tags not working) {% extends 'base.html' %} {% block pageTitle %} Basic Tables {% endblock pageTitle %} -
django IntegrityError for create object
I have this models . When i use One To One relation ship for real_estate field in Profile model and create new object i get this error => IntegrityError at /admin/users/profile/add/ NOT NULL constraint failed: users_profile.real_estate_id class Business(models.Model): name = models.CharField(max_length=200) image = models.ImageField() homes = models.ManyToManyField(Homes , related_name='home', blank=True) create = models.DateField(auto_now_add=True) number = models.IntegerField() class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) -
Insert a python dictionary into postgres jsonb field
I'm looking to a postgresql query or function to replace the flowing python code def insert_data(pk, data) json_str = Employee.objects.filter(pk=pk).values_list('time_log', flat=True)[0] dt = data["date"] data.pop("date") if json_str.get(f"{dt}") == None: json_str[f"{dt}"] = [data] else: json_str[f"{dt}"].append(data) # time_log is a `jsonb field` Employee.objects.filter(pk=pk).update(time_log=json_str) The code works but not efficient and causes bottlenecks. Data is dictionary containing a date and two datetime objects like this: data = { '2021-08-13': [ { 'clock_in': '2021-08-15T04:16:41.307Z', 'clock_out': '2021-08-14T21:16:44.491-07:00' } ] } IF the key does not exist, make a new key value pair, the key is the date in data and value is a list containing the data dictionary. IF the key exists, append data into key of date from data dictionary. -
what are the various ways for Styling the Django Forms?
was working with Django forms, and to beautify the Django forms I came across widgets, and after learning it got to know that we can customize widgets in two ways: it can be via widget instance or via widget class. Later came across django-crispy; django-bootstrap. Which will do the same beautification of the forms along with various other advantages over other. But was wondering, how many more such library / packages / apps are there, and is there any short of description for each, which might help me and others too. Thanks -
Crontab ModuleNotFoundError
I have prepared a py Script to update my Django database and upload a file to gdrive once a day. Trying to use Crontab along with python to run the py script. ModuleNotFoundError: No module named 'googleapiclient' I have already installed googleapiclient module. There is no error while running the same script in venv (virtual environment). 0 2 * * * /usr/bin/python3 /home/user/folder1/folder11/script2.py How to access the already installed module inside crontab..? -
change table header and content dynamically in JavaScript
I have a web app, frontend using normal HTML, backend using Django. In the HTML page, there's a table, which load data by calling API. I want to change table header dynamically in JavaScript after the if condition(in my case:if params['Add_Information'] == "eText_iBookStore":), so the table could have different header based on user selection. How could I change the header and content of my table in Javascript? <table contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-refresh="true" data-show-fullscreen="true" data-show-export="true" data-height="650" data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="server" data-total-field="count" data-data-field="results"> <thead class="thead-dark"> <tr contenteditable='true'> <th data-field="id" data-sortable="true">ID</th> {# <th data-field="courseId" data-visible="false"></th>#} <th data-field="courseCode" data-sortable="true" data-formatter="renderCourse">Course Code</th> <th data-field="book.title" data-sortable="true" data-formatter="renderTitle">Course Material Title</th> <th data-field="book.isbn" data-sortable="true">ISBN</th> <th data-field="book.publisher" data-sortable="true">Publisher</th> <th data-field="retail_price_display" data-sortable="true">Retail Price</th> <th data-field="semester_course.school" data-sortable="true">School</th> <th data-field="year" data-sortable="true">Year</th> <th data-field="month" data-sortable="true">Semester</th> <th data-field="quota" data-sortable="true">Course Quota</th> </tr> </thead> </table> <script> {% block script %} var $table = $('#bk-table'); var $ok = $('#ok'); $(function () { $ok.click(function () { $table.bootstrapTable('refresh') }); function queryParams(params) { params['limit'] = localStorage['Format']; params['discipline'] = localStorage['discipline']; params['Add_Information'] = localStorage['Add_Information']; if params['Add_Information'] == "eText_iBookStore": ***//Here should be header changing part*** params['publisher'] = $("[name='publisher']").val(); params['code'] = $("[name='code']").val(); console.log(params); return params; } {% endblock %} … -
Django - How to simplify the create new row of a table with many foreign key?
Here is the sample model: class GenderDecode(models.Model): gender_code = models.IntegerField(primary_key= True) gender_explain = models.CharField(max_length=100) class AgeDecode(models.Model): age_code = models.IntegerField(primary_key= True) age_explain = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) age_group = models.ForeignKey(AgeDecode, on_delete = models.CASCADE) gender_group = models.ForeignKey(GenderDecode, on_delete = models.CASCADE) The initial setup of two tables GenderDecode and AgeDecode: GenderDecode gender_code gender_explain 1 male 2 female AgeDecode age_code age_explain 1 young 2 old Provided I want to create a new user - John Male Young. I have to do this. User(name = 'John', age_group = AgeDecode.objects.filter(gender_code=1).first(), gender_group = GenderDecode.objects.filter(age_code=1).first() ).save() I want to do this User(name = 'John', age_group = 1, gender_group = 1 ).save() But I got this error ValueError: Cannot assign "1": "User.gender_group" must be a "GenderDecode" instance. Well, if the above syntax is a must, is there any way to go around to simplify my new row code ? -
How do I get User's updated name from Python Firebase Admin SDK?
I am using FirebaseAuth on Flutter, and send IdToken to my Django backend to use firebase_admin.auth.verify_id_token(id_token) to verify the user and get the user's basic info. But the user's info doesn't show the latest profile. I changed my Google account user name, but the name decoded from IdToken still showing the old name even though I signed out and signed in again on frontend. How do I get the latest user's profile? Thanks -
Django 404 Error: path doesn't go down urls.py
So I'm trying to make an index.html for the homepage of my Django project. I made an app called pages. Note that the templates folder is empty (moving index.html to templates did nothing). admin.py and models.py also contain nothing. I configured my TEMPLATES settings as such: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In my root project folder, urls.py looks like this. from django.contrib import admin from django.urls import path from django.conf.urls import include # from pages.views import home_view urlpatterns = [ path('homepage/', include('pages.urls')), path('admin/', admin.site.urls), path('explorer/', include('explorer.urls')), ] In the views.py file of the pages app: from typing import ContextManager from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # Render the HTML template index.html return render(request, 'index.html', context=ContextManager) In the pages app (not project root folder), urls.py looks like this (I created this file myself): from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And index.html: <!DOCTYPE html> <title>Test</title> <p>Test</p> Here is the full file structure. Here is what happens when I run the server: Where http://127.0.0.1:8000/ is … -
how to set up docker compose to use ssh to connect to AWS RDS on private subnets via EC2 Bastion
I have the following configuration of a django app that ssh'ed into an ec2 bastion and i tried to follow this example https://emmer.dev/blog/tunneling-a-database-connection-with-docker-compose/ I am still not able to configure my docker compose file to accept ssh tunnel to AWS Postgres RDS which reside in a private subnets. version: "3.9" services: app: build: ./app restart: always env_file: .env volumes: - ./app:/app - ./app/static:/app/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - "app_network" db: image: postgres restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - "app_network" networks: app_network: driver: bridge volumes: postgres_data: What happen is that using django itself via python manage.py runserver i am able to connect to the RDS instance and everything is fine. Now when i try to do the same with docker compose, docker compose exec app python manage.py migrate or try to access RDS from django shell inside the docker compose after it started with docker-compose up -d , the database crash with the message below: django.db.utils.OperationalError: could not translate host name "xxx.zzz.us-east-z.rds.amazonaws.com" to address: nodename nor servname provided, or not known clearly the issue is that docker compose is not picking the ssh tunnel connection i have tried multiple … -
Django & Js question slider with a next button appear on last question
i have a questions slider made with JS with a next button to go to next questions, i want to disable that button in last slide which is the submit slide. I have tried to remove the id from last slide but it wont appear in the sliders any help or advices to improve the code will be great Here is my code: HTML: W <div class="slider"> <form class="form" action="" method="post"> <!-- fade css --> {% csrf_token %} {% for question in questions %} <div class="myslide fade"> <div class="txt"> <p>{{question.question}}</p> <input id="{{question.id}}" type='radio' name="{{question.id}}" value="{{question.category}}"> <label for="{{question.id}}">Yes</label> <br> <input id="{{question.id}}1" type='radio' name="{{question.id}}" value="no"> <label for="{{question.id}}1">No</label> <br> </div> <img src="{{question.img.url}}" style="width: 100%; height: 100%;"> </div> {% endfor %} <div class="myslide fade"> <div class="txt"> <p>You finished all questions</p> <input type="submit" class="btn" value="Submit"> </div> <img src="{% static 'img/img4.jpg'%}" style="width: 100%; height: 100%;"> </div> <a class="next" onclick="plusSlides(1)">Next</a> </form> </div> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = … -
select_related and prefetch_related django
I have these 4 models: class User(models.Model): user = ... class Subject(models.Model): subject = ... class Section(models.Model): section= ... class Profile(models.Model): user= ... class student(models.Model): student = foreignkey(User) enrolled_subjects = ManyToMany(Subject) section = foreignkey(Section) profile = foreignkey(Profile) how can I get all related objects to Student object using select_related and prefetch_related to get? -
How To Create Chained Filter Form Fields Using Django Smart Selects
I have been searching online about how to make chained selections on filter forms (not forms). What I want to do is, select district according to the city that is selected. With normal forms I can make dependent dropdowns, but when it comes to filter forms, it does not seem to work. Here is my settings.py USE_DJANGO_JQUERY = True INSTALLED_APPS = [ 'smart_selects', ] Here is my template <form method="get"> {% csrf_token %} {{ form.media.js }} {{ myFilter.form|bootstrap }} <button type="submit" class="filter filtrele">Ara</button> </form> Here is my models.py class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(city, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) gizlilik_sozlesmesi = MultiSelectField(choices=GIZLILIK_CHOICES, max_length=1000, max_choices=1, null=True) sartlar_sozlesmesi = MultiSelectField(choices=SARTLAR_CHOICES, max_length=1000, max_choices=1, null=True) isim = models.CharField(max_length=100) ana_kategoriler= MultiSelectField(choices=ANACATEGORY_CHOICES, max_length=1000, max_choices=5, null=True) usta_kategorileri= MultiSelectField(choices=USTACATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) bakici_kategorileri= MultiSelectField(choices=BAKICICATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) temizlikci_kategorileri= MultiSelectField(choices=TEMIZLIKCICATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = ChainedForeignKey(District, chained_field="city", chained_model_field="city",show_all=False, auto_choose=True, null=True, sort=True) website = models.CharField(max_length=200, default='ananas.website', null=True) eposta = models.CharField(max_length=200, null=True) aciklama = models.TextField(max_length=10000, null=True) telefon = models.CharField(max_length=200, null=True) # aciklama = models.TextField(max_length=1000, null=True) profil_resmi = models.ImageField(default='ananas.jpg', upload_to='profile_images') resim_1 = models.ImageField(default='ananas.jpg', upload_to='profile_images') resim_2 = … -
How to set leaflet map layer selected as default
In my django app I have a leaflet map with two layers "active_event_layer" and "inactive_event_layer". I can select wich layer I want to see in the top right menu. But when the page is loaded no layer is selected by default, so in order to see a layer I must selected it first. What i want to do is to set a layer by default, so, when the page is loaded the "Active events" layer is selected by default. Here is my code: var active_event_collection = {{ active_events|geojsonfeature:"name"|safe }}; var inactive_event_collection = {{ inactive_events|geojsonfeature:"name"|safe }}; function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.name); } function map_init(map, options) { var active_event_layer= L.geoJson(active_event_collection, {onEachFeature: onEachFeature}) var inactive_event_layer = L.geoJson(inactive_event_collection, {onEachFeature: onEachFeature}) var basemaps = { "Gray scale": L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }), Streets: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }) }; var overlayMaps = { "Active events": active_event_layer, "Inactive events": inactive_event_layer, }; var features = L.control.layers(basemaps, overlayMaps).addTo(map); map.fitBounds(active_event_layer.getBounds()); } -
AttributeError 'Model' object has no attribute 'get_FOO_dispay'
qs = Model.objects.all() q = qs.get(id=1) q.get_field_dispay() returns 'Model' object has no attribute 'get_field_dispay' Am I not using it correctly? -
unsupported operand type(s) for /: 'method' and 'method', Django
Good afternoon community, I am new to Django, thus, I apologize in advance if my question happens to be silly. I am working on an investing project and I get the following error when I try to render the following method from the model: unsupported operand type(s) for /: 'method' and 'method' Here under is the code that I wrote, models.py: class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name #Company methods def net_income(self): return self.revenue - self.expenses def net_assets(self): return self.total_assets - self.total_liabilities def return_on_equity(self): return self.net_income / self.net_assets HTML FILE <li>Net income: {{company.net_income}}</li> <li>Net assets: {{company.net_assets}}</li> <li>Return on equity: {{company.return_on_equity}}</li> Note that both net_income and net_assets work just fine. The error rises with the last method, return on equity. I look forward to your enlightenment. -
Saving image files in django media instead of using base64 in quill editor?
I am using django as a backend and providing the api using rest-framework,I would like to use quill editor for my wysiwyg editor? Can anyone help me out in saving the image to django media files instead of saving as base64 it to the database?Thank you By the way , I am using vue for my frontend framework -
Django custom JSONField
I got JSONFields that I have to encode and decode every trip, the problem is I got few of them, so I'm trying to make a custom field like this: class JSONField(models.JSONField): """A Field to encode & decode JSONField.""" def __init__(self, default=dict, encoder=None, decoder=None): self.encoder = encoder self.decoder = decoder self.default = default def get_prep_value(self, value: Any) -> Any: if value is None: return value return json.dumps(value, default=self.default, cls=self.encoder) def from_db_value(self, value, expression, connection): if value is None: return value return json.loads(value, cls=self.decoder) But when I use it on the model class Employee(models.Model): time_log = JSONField() I get this error AttributeError: 'JSONField' object has no attribute 'name' File "/Users/mac/Documents/Payroll/payroll/models.py", line 106, in <module> class Employee(models.Model): File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 781, in contribute_to_class self.set_attributes_from_name(name) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 768, in set_attributes_from_name self.name = self.name or name AttributeError: 'JSONField' object has no attribute 'name' How can I fix this problem? -
Django Annotate the Sum of a Foreign Key's Duration Values
I'm trying to get 5 foo objects whose children (bar) have the longest combined duration: foo = Foo.objects.annotate( sum_of_bar_duration=Sum("bar__duration") )\ .order_by('-sum_of_bar_duration')[:5] My Models: class Foo(models.Model): name = models.CharField(max_length=30, unique=True) #REVIEW deleted blank, null = False since this is default class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) duration = models.DurationField() But I ended up getting this error: django.core.exceptions.FieldError: Unsupported lookup 'duration' for BigAutoField or join on the field not permitted. Does anyone know why? How can I fix this? -
No module named W0614 pylint (fatal)
I'm working on a Django project and this error keeps coming up on the first line of every file I work on. I recently reset my computer and this is my first time using VSCode after. Please, what should I do?