Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Conditions in a queryset
I have a table "Table" and a field "field". I need to filter the table with the following condition: if (field.isdigit() and len(strip(field)) <= 4): do somethimg or if (field.isdigit() and int(field) <= 10000): do somethimg How would it look like in a query? Table.objects.filter(condition).update(field="xxx") Thank you -
Django authentication for Zoom Meetings
I have a django project which is being used as centralised user authentication for most of our applications. The project is customised as per our requirements to allow mobile and OTP authentication. Can we use this authentication for Zoom meetings? I came across this Zoom SSO. But not able to understand what changes I will have to make in the existing django application. Any guidance will be a great help. -
Django request.POST.get() returns None
I face a problem and I can't find a solution. I'm trying to redirect to the previous page after login. Somehow the ?next=request.path returns none when trying to request.POST.get() after submission. This is my Html code that directs the user to the login page, taking the request.path as "next page after login" value. {% if user.is_authenticated %} <button class="btn" data-toggle="modal" data-target="#inquiryModal"> <a class="btn btn-primary border rounded-0" role="button" href="#">Make an Inquiry</a> </button> {% else %} <a class="btn btn-primary border rounded-0" role="button" href="{% url 'login' %}?next={{ request.path|urlencode }}" >Make An Inquiry</a> {% endif %} This is the login page html code. <div class="login-clean" style="background-color: #fff;"> <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <!--- ALERTS --> {% include 'partials/_alerts.html' %} <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email"></div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> <button class="btn btn-primary btn-block" type="submit">Log In</button> </div> </form> </div> Views.py file def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] valuenext = request.POST.get('next') print(valuenext) user = auth.authenticate(username=email, password=password) # if user is found and not from listing page login and redirect to dashboard if user is not None and valuenext == "": auth.login(request, user) messages.success(request, 'You are now succesfully logged in') … -
map anonymous user data when user login/register using session_key in django
I Have an app where anonymous user comes select item and add to cart and see the total price of the item selected i store these with a session_key , NOW after adding to cart user proceed to login and register , so after getting register/login i want to map the data user selected as an anonymous. views.py def ResultTest(request): request.session.create() var = request.POST.get('selectedTests') abc = UserSelectTest() abc.session_key = request.session._session_key #abc.user = request.user abc.testselected = request.POST['selectedTests'] abc.save() models.py class UserSelectTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) session_key = models.CharField(max_length=32, null=True) testselected = models.TextField() here in views i have commented request.user as anonymous user doesn't have any user instance providing user null is equal to true doesn't work So how can i map session_key after user login/register ? -
if column have same name then return one of same kind. django
database img now by doing something like this datatotemplates= playlist.objects.filter(playlist_name=playlist_name) I want output as 1st hello1 gfh ertr dg all i want is not to repeat same name. thank you -
Django/Pythons is Messages - Unique Error displays the field
I am very new to Django/Python programming so hopefully this is a simple fix. I have created a Model that when I try and add a duplicate record (via a ModelForm), the message that is returned to my template displays the unique field twice in the message. It appears like : "fieldname" "classname" with this "fieldname" already exists. How do I display the fieldname once. The message currently displayed is : FirstNamePerson with this FirstName already exists. What I would like to see is : Person with this FirstName already exists. Any assistance would be greatly appreciated. Thanks Models.py: class Person(models.Model): FirstName = models.CharField(max_length=20, primary_key=True) Template.html {% for message in messages %} <div class="alert alert-{{ message.tags }}"> message: {{ message | striptags }} </div> {% endfor %} -
Passing The ID of a Field in another Field of the same model Django
Hello, I am trying to pass the ID of a Model in an Image Field URL(upload_to) and then access it Through a URL unique to The instance. Here's What I did (Amature); class User(models.Model): serial = models.AutoField(primary_key=True) profile = models.ImageField(upload_to=f"profiles/{serial}/") But all I'm Getting is OSError. I wanted to save the file to profiles/{serial}/ directory in the app. So Every Instance of the Model has its own Directory. And Then access it Through host:port/api/users/{serial}/profile.jpg My View Set is served through host:port/api/users Is there a way I can Do it? Any Help is Highly Appreciated. A Detailed Explaination is Even more Appreciated. -
How to import a dictionary to templates using django?
So I am tying to make minesweeper for a school project using python django. My plan is to call a function onclick that would send the button id to views.py and find the corresponding number (number of bombs surrounding it) and return it to templates. I tested to see if my function is sending the id to views.py and it works but when i try to print the corresponding value through templates, it doesnt print anything. I'm wondering why and how do I fix it? Here's my code in templates: <body> <form id='klik' method='POST' action='{% url "klik" %}'> {% csrf_token %} <input type='hidden' name='ID' id='ID' value='{{ID}}' /> </form> <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; document.getElementById("klik").submit(); print({{vrijednost}}); docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } document.body.appendChild(docFrag); </script> </body> And my code in python: def klik(request): ID = request.POST['ID'] vr = r[ID] d = dict() d['vrijednost']= vr print(d) return render(request,'index.html', d) -
linking to the index.html to other html page in Django
I am new to django project. what I was trying to do is when user press the " Call us now" button on my nav-bar it links to the other html pages ( here: contact.html) in the index.html code: </ul><a href="contact.html"><button class="btn btn-primary" type="button">call us now!</button></a></div> in the views.py from django.shortcuts import render def index(request): return render(request, 'jobs/index.html') def contacts(request): return render(request, 'jobs/contact.html') in the urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.index, name='index'), path('contact/', jobs.views.contacts, name='contact'),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)** -
Product matching query does not exist Django
i am trying to insert product in my database using django custom fields, but it's showing me error that Product matching query does not exist. it would be great if anybody could figure me out where should i make changes in my code. thank you so much in advance. views.py class ProductAdd(APIView): def post(self, request, format=None): data = request.data title = data['title'] slug = data['slug'] description = data['description'] # created_on = data['created_on'] # status = data['status'] queryset = Product.objects.filter(title__contains=title,slug__contains=slug,description__contains=description) query_slug = Product.objects.get(slug__exact=slug).first() try: if query_slug == None: # queryset.annotate(Count(title,slug,description,created_on,status)) queryset.annotate() Response({"msg":"product added succesfully!"}, status=HTTP_201_CREATED) else: print("query already exist!") except ValueError: return Response(status=HTTP_400_BAD_REQUEST) -
How do I solve this django-private-chat error?
so I've been trying to implement django-private-chat into an existing problem but always encountered an error. So, I tried to run the example project found on under django-private-chat on Github and I received the same error. Thanks for the help! 25.04.20 10:45:49:ERROR:Error in connection handler Traceback (most recent call last): File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/websockets/server.py", line 191, in handler await self.ws_handler(self, path) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/handlers.py", line 259, in main_handler user_owner = get_user_from_session(session_id) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/utils.py", line 15, in get_user_from_session session = Session.objects.get(session_key=session_key) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get num = len(clone) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor = self.connection.cursor() File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. 25.04.20 10:45:49:DEBUG:server ! failing OPEN WebSocket connection with code 1011 25.04.20 10:45:49:DEBUG:server - state = CLOSING 25.04.20 10:45:49:DEBUG:server > Frame(fin=True, opcode=8, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False) 25.04.20 10:45:49:DEBUG:server x half-closing TCP connection 25.04.20 10:45:49:DEBUG:server - event = connection_lost(None) 25.04.20 10:45:49:DEBUG:server - state = CLOSED 25.04.20 10:45:49:DEBUG:server x … -
How to link static files in django, if the path is provided by the context in html?
Here is my views.py file: from django.shortcuts import render def page(request): css = 'temp/css.css' return render(request, 'temp/index.html', {'css': css}) and templates/temp/index.html file: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static '{{ css|safe }}' %}"> </head> <body> Hello Page </body> </html> and static/temp/css.css file: * { width: 100vw; height: 100vh; background: red; } After rendering source of the page is: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/static/%7B%7B%20css%7Csafe%20%7D%7D"> </head> <body> Hello Page </body> </html> but I am expecting ... <link rel="stylesheet" type="text/css" href="/static/temp/css.css"> ... Why it is not working? Is there any way to do this? How to link a static file if the path is provided by the context in html? -
After changing field to read only, the form displays pk instead of value/ django forms
When I add this line of code to my form: borrower = forms.CharField( widget=forms.TextInput(attrs={'readonly': 'readonly'})) The value of borrower is showing up as pk instead of its real value. Any idea why is that? Whole form: class AmendLoan(ModelForm): borrower = forms.CharField( widget=forms.TextInput(attrs={'readonly': 'readonly'})) class Meta: model = BikeInstance fields = ( 'borrower', 'frame_number', 'due_back', 'status' ) When I remove readonly, everything works fine, but I need this field to show up, but it cant be changed. -
Django query set for sums records each month
I have the following models structure: Product | Price | Quantity | Total* | Date of purchase Product A | 10 | 1 | 10 | 1/01/2020 Product B | 10 | 2 | 20 | 1/02/2020 *totale is created with a manager function in the models.py. I want to have the sum for each month of each type of product in another app of my project. Something like this: Product | Gen | Feb | Mar | Apr | May | Jun | .... Product A | 10 | 0 | 0 | 0 | 0 | 0 | .... Product A | 0 | 20 | 0 | 0 | 0 | 0 | .... This is my models.py class Product(models.Model): nome= models.CharField() class MaterialeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).annotate( total=F('quantity')*F('price'), ) class Materiale(models.Model): product= models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quantity=models.DecimalField() price=models.DecimalField() date=models.DateField() obejcts=MaterialManager() -
How to do server side validation of sign up form in django?
I am new to django and I have create a sign up form and its working but when I try to validate password fields to see the if password1 and password2 is matched then I get error. For instance, if my password1=12345678 and password1= TY123456 then I get an error "The view website.views.signUp didn't return an HttpResponse object. It returned None instead". Basically, I just want to dipslay error instead of redirecting to error page. Can anyone help me please? How to do server side validation of signup form.Many Thanks. view.py def signUp(request): form = UserCreationForm() if request.method == 'POST': filled_form = UserCreationForm(request.POST) if filled_form.is_valid(): password1 = filled_form.cleaned_data['password1'] password2 = filled_form.cleaned_data['password2'] if password1 != password2: note='You password does not match' return render(request,'signup.html',{'form':form, 'note':note}) else: filled_form.save() return redirect('login') else: return render(request,'signup.html',{'form':form}) signup.html <h1>Sign Up</h1> <span style="color: red;">{{note}}</span> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Sign Up</button> </form> urls.py from django.contrib import admin from django.urls import path, include from website.views import home,signUp urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('signup/',signUp, name='signup'), path('',home,name='home') ] -
IntegrityError at /accounts/signup in django when trying to signup
this is my blog : http://gorani-dncvb.run.goorm.io/ I am trying to build a signup page for my django blog. I finished writing codes for template/view/form/url, and successfully connected to the page : http://gorani-dncvb.run.goorm.io/accounts/signup. So I came to think there is no problem in template/url. but the problem arises after trying signup, It saids : IntegrityError at /accounts/signup UNIQUE constraint failed: auth_user.username and this is my view code : def signup(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = User.objects.create_user(username=username, password=raw_password) return redirect("post_list") else: form = SignupForm() return render(request, 'registration/signup.html', {'form':form}) and this is form code : class SignupForm(forms.ModelForm): class Meta: model = User fields = ('username','password',) (I didn't used UserCreateForm on purpose) There's definitely no overlapping another user, so why I'm seeing this error message? -
Is sending token authentication information via cookie headers secure?
0 i am by no means a security engineer , and i have barely started my journey as a web developer. Im utilizing a python package known as django for my backend , react.js for my front end . Recently i have incorporated django-channels , which is a package that gives me the ability to use websockets in my project. Since i have decoupled my front and backends , the basis of authentication im using is via tokens (will look into using jwt) . The issue is that with javascript , it is not possible to send authentication headers via websocket connection (or so im told) , therefore a lot of people are using cookies to send this authentication token instead. Heres an example snippet of how i am sending the token from my front end: const path = wsStart + 'localhost:8000'+ loc.pathname document.cookie = 'authorization=' + token + ';' this.socketRef = new WebSocket(path) doing this allows me to then extract out the token information through utilizing a customized middleware on my backend . import re from channels.db import database_sync_to_async from django.db import close_old_connections @database_sync_to_async def get_user(token_key): try: return Token.objects.get(key=token_key).user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware: """ Token authorization middleware … -
Only show last record in html
I am new for Django. I want to list all passenger in each flight. However, the display is only the passenger of last flight only. I think it may be something wrong in my html. My code in view.py as follows:- def list (request): flights = Flight.objects.all() for flight in flights: for flight in flights: passengers = Flight.objects.get(pk=flight.id).passengers.all() for passenger in passengers: context = { "flights": flights, "flight":flight, "passengers": passengers, "passenger":passenger, } My HTML is listed as follow:- {% block body %} <h1>Flights</h1> <div class = "list"> {% for flight in flights %} <li> <a href="{% url 'flight' flight.id %}"> Flight #{{ flight.id }}: {{ flight.origin }} to {{ flight.destination }} </a> <ul> <li>Flight Number: {{ flight.id }}</li> <li>Origin: {{ flight.origin }}</li> <li>Destination: {{ flight.destination }}</li> <li> {% for passenger in passengers %} <--- I think it should have some instruction to point to flight Passengers: <ul> <li> {{passenger}} </li> {% empty %} <li>No passengers</li> {% endfor %} </ul> </li> </ul> </li>{% endfor %}</div>{% endblock %} Last flight passenger appear only. Would any one can help me to review if any missing ? Thanks a lot for your help The results is only show last flight passenger -
Django Form - Filter a list based on Foreign Key Value
So basically I have the following in my models.py class Company (models.Model): title = models.CharField(max_length=100) short = models.CharField(max_length=50,default='NA') class AccountingGroups(models.Model): title = models.CharField(max_length=50, unique=True) description= models.CharField(max_length=150,blank=True) section = models.ForeignKey(Section, on_delete=models.PROTECT) class Transaction (models.Model): description = models.CharField(max_length=100) date_created= models.DateField(auto_now_add=True) posting_date = models.DateField() user=models.ForeignKey(User, on_delete=models.PROTECT) company = models.ForeignKey(Company, on_delete=models.PROTECT) account_group = models.ForeignKey(AccountingGroups, on_delete=models.PROTECT) income_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0) expenditure_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0) Now I am displaying the transaction Form on the browser so to log in all the income and expenditure of a particular company. The below is the forms.py file. class TransactionForm(ModelForm): #posting_date = DateField(input_formats=['%d/%m/%Y']) posting_date = DateField(widget=DatePickerInput(format='%d/%m/%Y').start_of('event active days'), input_formats=('%d/%m/%Y',), required=False) class Meta: model = Transaction fields = ['description','posting_date','account_group','income_amt','expenditure_amt'] Now the structure of the website is that each each company that i have in my database has a distinct url. When i go to each url i can view/edit or create a new/existing transaction for that particular company. Now what I'm asking if whether I can restrict the form so that it will show only the Accounting Groups for that particular company only rather than displaying all the accounting groups irrespective on which company I m trying to create the transaction on. -
How to redefine a display form field so it shows a content with filtring?
I have some models classes. And some classes have bounding fields with another class. Each class have the field - author. I whould like that for each user the form bounding field shows only those data which was created these authors. For example: class "TypeJob" has field "author". User Jhon created a TypJob - "Painting". User Alex created a TypJob - "Cleaning". When Jhon opens the form and click "type job" field, he sees both type job: painting and cleaning. I whould like that he sees and could choose only "painting". Because he is it author. Django 3 -
Value Error : "<User: ClipUo>" needs to have a value for field "id" before this many-to-many relationship can be used
I am making a program with multiple user hierarchies. My models.py - class Role(models.Model): ROLE_CHOICES = ( (1,'ADMIN'), (2,'HR'), (3,'MGR'), (4,'EMP'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES,primary_key=True) def ___str___ (self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) class Admins(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) class HRs(models.Model): user = models.PositiveSmallIntegerField(choices=Role.ROLE_CHOICES) first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) My views.py - class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'ADMIN' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/form1/forms/') class HRSignUpView(CreateView): model = User form_class = HRSignUpForm template_name = 'form1/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'HR' return super().get_context_data(**kwargs) def form_valid(self,form): user = form.save() login(self.request, user) return redirect('/form1/forms') Initially it was user.roles = 2 or 1 but I changed it after that induced an error to .set() based on the recommendation of the debugger. My forms.py - from django.contrib.auth.forms import * from django.db import transaction from .models import * class AdminSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fname = forms.CharField(max_length=256) lname = forms.CharField(max_length=256) @transaction.atomic def save(self): user = super().save(commit=False) user.roles.set(1) user.save() admin1 = Admins.objects.create(user=user) admin1.first_name.add(*self.cleaned_data.get('fname')) admin1.last_name.add(*self.cleaned_data.get('lname')) return user class HRSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User @transaction.atomic() def save(self, commit=True): user = super().save(commit=False) … -
Using a GenericRelation attribute as a unique_together
I recently learned the benefits of using GenericForeignKey and GenericRelation, so I started transitioning some of my models.ForeignKey() attributes to GenericRelation(). I'm using the boilerplate definitions inside my Product class: class Product(models.Model): [...] content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Before transitioning to GenericRelation, one of my models used unique_together: class Rank(models.Model): pub_date = models.DateField(db_index=True) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) day_rank = models.IntegerField() class Meta(object): unique_together = ['pub_date', 'product'] However, when I try changing Rank's product attribute to this: [...] product = GenericRelation('Product', on_delete=models.DO_NOTHING) class Meta(object): unique_together = ['pub_date', 'product'] I get the following error: 'unique_together' refers to field 'product' which is not local to model 'Rank'. Is it possible to find a workaround for this error? Why was I able to use a ForeignKey but not a GenericRelation when defining unique_together? -
Is it a good idea to build a website fully in python and django
I realize this is a very general question, and do not expect a perfect answer, but I am currently working on building a full and well running website from scratch. It is a bit of a double project for me since I am learning python at the moment, and wanted to build it in said language. However I know visual basic and am very comfortable in that, but I want to expand my knowledge of languages, while also doing something with a purpose. I want to know if that is a good endeavor, not so much if possible more so I do not know where to start since I know I have to do both front end and back end work, and python is coming along well for me, however I keep seeing web resources that say that it is not a good idea and do not understand why that is. I am familiar with HTML and CSS and am prepared to put the bells and whistles on to make things look nice and pretty, however I want to know why I cannot or should not use python to link my database to the webpage alongside other scripting languages to … -
ValueError: Expected table or queryset, not str
This might be something really simple but I can't put my finger on it. I created a table using django-tables2 and added a checkbox column in it, above the table I created an actions dropdown for delete and edit inside a form, here's my html code <div class="container"> <div class = "mt-5"> <h1 class="display-4">My Table</h1> <form action="/delete_or_edit_item/" method="POST"> {% csrf_token %} <select name="action_options"> <option value="delete">Delete</option> <option value="edit">Edit</option> </select> <input type="submit" class="btn btn-info px-3 py-1 ml-2 mb-1" value="Go"> {% render_table mytable %} </form> </div> </div> I created a single function based view for it, here's the code in views.py, I know my problem is here somewhere in my action == 'edit'... def delete_or_edit(request): if request.method == "POST": pks = request.POST.getlist("selection") # handle selection from table action = request.POST.get('action_options') selected_objects = my_tbl.objects.filter(object_id__in=pks) if action == 'delete': selected_objects.delete() return HttpResponseRedirect("/") selected_object = my_tbl.objects.get(object_id__in=pks) if action == 'edit': form = my_tbl_form(request.POST or None, instance=selected_object) if form.is_valid(): form.save() return HttpResponseRedirect("/") return render(request, 'staffplanner/index.html', {'form':form}) in my urls.py urlpatterns = [ path('', views.index, name = 'home'), ... path("delete_or_edit_item/",views.delete_or_edit), ] in my tables.py class myTable(tables.Table): selection = tables.CheckBoxColumn(accessor='object_id', attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False) class Meta: model = my_tbl template_name = "django_tables2/bootstrap-responsive.html" fields = ('selection','object_id','manufactured','expiry','company','category') attrs … -
Django ORM sum all fields value of onetoone fields
This is my models: class Bill(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) flat_rent = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) gas = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True ) I know a way but i dont like this: like bill = Bill.objects.get(--------) total = bill.gas + bill.flat_rent But I think this is bad practice, coz, I have more than 20 fields in this model. So I want to know the total of all these fields in single line of query. Can anyone help me in this case?