Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass kwargs from django Fixture to django Signal
I need to pass the extra parameter from Django fixture to Django pre_save signal. I tried couple of ways but unable to do so. Django Fixture: [ { "model": "club_courses.Country", "pk": 1, "is_created": "False", // This is the extra paramter that I need in the django signal "fields": { "code": "PK", "name": "Pakistan" } } ] Django Signal: @receiver(pre_save, sender=Country) def populate_dates(sender, instance, *args, **kwargs): if kwargs['raw']: instance.updated_at = timezone.now() instance.created_at = timezone.now() Any help would be highly appreciated. Thanks. -
adding form attribute to inputfield
I am trying to achieve submitting a form with input fields being outside of the form (see here). Therefore I want to add the form="" attribute to my inputfields, as described here: class TestForm(forms.Form): class Meta: model = Product fields = ["number"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["number"].widget.attrs.update({"class": "form-control w-50"}) ## works self.fields["number"].widget.attrs.update({"form": "testformid"}) ## does not work in the template the inputfield renders as: <input type="number" name="number" value="8" class="form-control w-50" required="" id="id_number"> how can I add the form="..." correctly? -
Django redirect to view with kwarg not working
My goal is to redirect the client to the chat session detail view if they are trying to open a new chat session with someone they already have a chat session with. Everything works fine but when I tried to open a duplicate chat session, it didnt get redirected and all what i got is a blank json response //views.py class ChatSessionListView(generics.ListCreateAPIView): serializer_class = ChatSessionSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return ChatSession.objects.filter(Q(initiator=self.request.user) | Q(receiver=self.request.user)) def perform_create(self, serializer): receiver_username = self.request.data['username'] receiver = get_object_or_404(User, username=receiver_username) chat_session = ChatSession.objects.filter(Q(initiator=self.request.user, receiver=receiver) | Q(initiator=receiver, receiver=self.request.user)) if chat_session.exists(): return redirect('v1:chat:chat_session_detail', session_id=chat_session[0].pk) else: serializer.save(initiator=self.request.user, receiver=receiver) // urls.py urlpatterns = [ path('', views.ChatSessionListView.as_view(), name='chat'), path('<str:session_id>/', views.ChatSessionDetailView.as_view(), name='chat_session_detail') ] -
Django cumulative sum in model (sqlite)
My model is: class transaction(models.Model): transactiondate = models.DateField() category = models.ForeignKey(category, on_delete=models.PROTECT, default=0) details = models.CharField(max_length=200, null=True) amount = models.DecimalField(decimal_places=2, max_digits=10) accountid = models.ForeignKey(account, on_delete=models.PROTECT) And I'm getting a cumulative total for each date using a raw SQL query: def cumulativebalance(): query = """SELECT id, transactiondate, SUM("amount") OVER (ORDER BY transactiondate) AS "cumsum" FROM "transactions_transaction" GROUP BY transactiondate ORDER BY transactiondate ASC, "cumsum" ASC """ return balance = transaction.objects.raw(query) This does return the output I'm looking for. My question is whether there's a way in Django that I can incorporate this into my model instead of having it as raw SQL? What I've tried I did find a previous similar question and I've adapted the answer to my own model: test = transaction.objects.annotate( cumsum=Func( Sum('amount'), template='%(expressions)s OVER (ORDER BY %(order_by)s)', order_by="transactiondate" ) ).values('transactiondate', 'cumsum').order_by('transactiondate', 'cumsum') But this gives me an error: OperationalError at /transactions/ near "OVER": syntax error. I don't understand what this is telling me. The SQL which was generated is shown in the traceback. My best guess is that it should be PARTITION BY after OVER instead of ORDER BY, but I don't know how I could change that from my python code. ('SELECT "transactions_transaction"."transactiondate", ' 'CAST(CAST(SUM("transactions_transaction"."amount") AS … -
IndexError: tuple index out of range - Django
I am getting IndexError: tuple index out of range when trying to do a consult to the DB (Heroku postgres): views.py: def get_total_per_month(request, year): user= User.objects.values("id").filter(username=request.user) query = ( f"SELECT to_char(date_trunc('month', \"move_date\"), 'MM') AS month_number," f" sum( CASE WHEN \"move_id\" = 1 THEN \"move_value\" WHEN \"move_id\" = 2 THEN -\"move_value\" END ) as total" f" FROM move_control WHERE \"user_id\" = {user[0]['id']}" f" AND \"move_date\"::text LIKE '{year}%' GROUP BY month_number" ) # Retrieve data for p in Move.objects.raw(query): print(p) When trying to retrieve de data the following error shows: File "C:\Users\LonxfUser\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) IndexError: tuple index out of range I've tried this query directly from the database and it works, so maybe i'm missing something. I have looked at the documentation of Django but what i've tried didn't work. -
Django view function for navbar included
I have my page only for navigation bar and I include it in base page. Now I have a menu in that navigation bar and links I get from database(that links are my categories). But how can I call my function in views without path, because I don't need to have path for navigation bar? And I need that view function to get data from database. models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() info = models.TextField(default="Informacion a Completar") image = models.ImageField(blank=True) views.py def CategoryView(request): context = { 'items' : Item.objects.all() } return render(request, 'categories_bar.html', context=context) categories_bar.html <li class="nav-item"></li> {% for category in items %} <div> {{ items.category }} </div> {% endfor %} </li> base.html {% include "categories_bar.html" %} -
Returning lists from url in Django
Is there a way how to return lists that are passed in to url as parameters? I've noticed that if a list is passed to a view url then when you access the said passed list in the view via self.kwargs['parameter'] and print it then the result will be ['item', 'item2'] which looks like a list, however the type(self.kwargs['parameter']) will actually be of <'str'> not a <'list'>. The example url that has a list passed looks something like this: http://127.0.0.1:8000/%5B'list_item',%20'another_list_item'%5D/%5B'list_item1',%20'another_list_item1'%5D/ Am I correct in stating that self.kwargs['parameter'] only takes the raw string of the url and does not know what type of data was passed? -
how to give path in pipeline config file?
2022-01-13 15:50:40.558948: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0. INFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',) I0113 15:50:40.563051 140140612618112 mirrored_strategy.py:376] Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',) INFO:tensorflow:Maybe overwriting train_steps: None I0113 15:50:40.798899 140140612618112 config_util.py:552] Maybe overwriting train_steps: None INFO:tensorflow:Maybe overwriting use_bfloat16: False I0113 15:50:40.799189 140140612618112 config_util.py:552] Maybe overwriting use_bfloat16: False WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/model_lib_v2.py:526: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version. Instructions for updating: rename to distribute_datasets_from_function W0113 15:50:40.848803 140140612618112 deprecation.py:347] From /usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/model_lib_v2.py:526: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version. Instructions for updating: rename to distribute_datasets_from_function Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/utils/label_map_util.py", line 159, in load_labelmap text_format.Merge(label_map_string, label_map) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 735, in Merge allow_unknown_field=allow_unknown_field) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 803, in MergeLines return parser.MergeLines(lines, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 828, in MergeLines self._ParseOrMerge(lines, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 850, in _ParseOrMerge self._MergeField(tokenizer, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 947, in _MergeField (message_descriptor.full_name, name)) google.protobuf.text_format.ParseError: 1:1 : Message type "object_detection.protos.StringIntLabelMap" has no field named "Coverall". During handling of the above exception, another exception occurred: Traceback (most recent call last): File "model_main_tf2.py", line 113, in tf.compat.v1.app.run() File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/platform/app.py", line 40, in run _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File "/usr/local/lib/python3.7/dist-packages/absl/app.py", line 303, … -
Can I query an ERP in Django app if the ERP database is not in the Django model?
In my company we do machining. I have to build an app in which people can declare tool changes. The machines are listed in the company ERP, so the app has to query the ERP to get the machines list. So, the user can select the machine on which he is working and declare his tool change. The ERP is used only read-only here. I think Django could be a good tool to build this app. But I wonder if it is a good idea to query the ERP without integrating its base to the Django project model. There would be only some direct SQL (pyodbc) queries to the ERP to prepare the HTML forms. I must confess that if I have some experience with Python (including pyodbc), I am starting with Django. -
Why is the html not recognising the view function?
I am trying to build an inventory management with Django. When building delete option, I am encountering an error. The error message is "Reverse for 'delete' not found. 'delete' is not a valid view function or pattern name." I will paste my code below. Delete function code: def delete(request, iid): obj = inventory.objects.get(id=iid) obj.delete() return render(request, 'main/lists.html') HTML Template code: <a class="btn btn-danger bg-gradient" href="{% url 'delete' i.id %}" role="button">Delete</a> Please give me a valid solution. -
Django: Create manualy session cookie and authenticate later with it
I am using Django-Rest-Framework with token authentication. In my Android App I want to open a webview and display some content from a view which needs authentication. Because of this I wrote a rest call to fetch a session id. /rest/getsessionid/ => looks like that: from django.contrib.sessions.backends.db import SessionStore class GetSessionKeyView(APIView): def get(self, request, format=None): if request.user.is_authenticated: s = SessionStore() s.create() return Response({'sessionid': s.session_key}) return Response({'notauthenicated': True}) Unfortunately the returned sessionid is not working. Why? -
how to reshape django queryset and show in template
I wang to reshap my django queryset and this queryset showed in page like this. I want it showed in one row, and the first column mergered and displayed in one one string. This is can be done in python and mysql with group by function. how can I get in django queryset? Thank you very much for any kind suggestions -
Delete unapplied migrations Django
I modified a model field in my local environment and made the migrations. Every thing seemed fine until I pushed it to production. I tried to apply the migrations to my DB and received an error: cannot ALTER TABLE because it has pending trigger events I ended up just reverting to the previous migration, which solved the problem for now. But now I have these unapplied migration files pending and I need to find a way to either delete them or ignore them. What is the best solution moving forward? Local Production -
React app can't reach to backend python application on localhost on same server
i have one peculiar situation as below .......... i have one public cloud VM which has public ip say 160.159.158.157 (this has a domain registered against it) ...... i have one python-django application (backend) which cors-enabled serving data through rest api port 8080 ...... i have one react app running on same vm on different port (3000) which is accessing the python-django app and supposed to produce one report...... Problem is -- when i use http://:8080/api/ or http://:8080/api/ my application is working fine but when i try to fetch data from localhost like http://localhost:8080/api/ or http://127.0.0.1:8080/api/ react app failed to fetch data...... getting error -- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080/api/. (Reason: CORS request did not succeed). Status code: (null). in developer-tools i tried to use below axios.get(baseURL, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', } this is too not helping me out .... Any idea to over come it ? when i use localhost my request from react not able to react backend Python app -
Object has no attribute "_set" in djangoe
Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react and have the following blog post and blog comment models class BlogComment(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True) name = models.CharField(max_length=200, null=True, blank=True) comment = models.TextField(null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) class BlogPost(models.Model): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) body = models.TextField() dateCreated = models.DateTimeField(auto_now_add=True) And the serializers for both models are: class CommentSerializer(serializers.ModelSerializer): class Meta: model = BlogComment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = "__all__" def get_comments(self, obj): comments = obj.comment_set.all() serializer = CommentSerializer(comments, many=True) return serializer.data The endpint of comment is path('posts/<str:pk>/comment/', CreateCommentView, name="create-comment"), The endpoint is working. I'm able to add comment to posts both from the front end. The error comes when I try to map through the comments for each post. get the errorAttributeError: 'BlogPost' object has no attribute 'comment_set' Here is the code I'm using to map through to display all the blogs of a particular post in the blog details page in react <div variant='flush'> {blog.comments.map((comment) => ( <div key={comment.id}> <strong>{comment.name}</strong> … -
OpenCV and MacOS - NSWindow drag regions should only be invalidated on the Main Thread
Background info: I am using python 3.9, Django 4.0.1, OpenCV 4.5.5.62, MacOS Big Sur 11.6 I am creating a face detection/recognition for my DJango application, however when I try to get the camera feed displayed I am recieving the following error: 2022-01-14 13:38:51.299 Python[78727:759513] WARNING: NSWindow drag regions should only be invalidated on the Main Thread! This will throw an exception in the future. Called from ( 0 AppKit 0x00007fff22cdbed1 -[NSWindow(NSWindow_Theme) _postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 352 1 AppKit 0x00007fff22cc6aa2 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1296 2 AppKit 0x00007fff22cc658b -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42 3 AppKit 0x00007fff22fd083c -[NSWindow initWithContentRect:styleMask:backing:defer:screen:] + 52 4 cv2.abi3.so 0x00000001194f5334 cvNamedWindow + 564 5 cv2.abi3.so 0x00000001194f4c8a cvShowImage + 154 6 cv2.abi3.so 0x00000001194f2711 _ZN2cv6imshowERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEERKNS_11_InputArrayE + 1329 7 cv2.abi3.so 0x000000011870d999 _ZL18pyopencv_cv_imshowP7_objectS0_S0_ + 601 8 Python 0x0000000105855eab cfunction_call + 59 9 Python 0x0000000105816d5d _PyObject_MakeTpCall + 365 10 Python 0x00000001058ef49c call_function + 876 11 Python 0x00000001058ec933 _PyEval_EvalFrameDefault + 25219 12 Python 0x0000000105817528 function_code_fastcall + 104 13 Python 0x00000001058ef40c call_function + 732 14 Python 0x00000001058ec9cb _PyEval_EvalFrameDefault + 25371 15 Python 0x0000000105817528 function_code_fastcall + 104 16 Python 0x00000001058ed043 _PyEval_EvalFrameDefault + 27027 17 Python 0x00000001058f0103 _PyEval_EvalCode + 2611 18 Python 0x00000001058174b1 _PyFunction_Vectorcall + 289 19 Python 0x00000001058ed043 _PyEval_EvalFrameDefault + 27027 20 Python 0x0000000105817528 function_code_fastcall + 104 21 Python 0x000000010581956a … -
Como utilizar um protocolo modbus com django?
Estou utilizando o django para desenvolver um sistema de monitoramento. Este sistema de monitoramento utilizara o protocolo de comunicação Modbus RTU. Tenho um formulário dinâmico aonde utilizei o inline formset, pois um dispositivo pode ter vários registros, este formulário esta funcionando corretamente. O que acontece que não estou conseguindo pegar alguns dados salvos no banco de dados, pois necessito dos dados de id do escravo e do número do registrador para solicitar uma informação. Estou utilizando a biblioteca mimimalmodbus. Obs: não estou conseguindo pegar o id_escravo e nem o numero_registrado no banco de dados. O meu condigo esta na Views.py no django instrument.serial.stopbits = 1 instrument.serial.timeout = 0.05 # seconds instrument.serial.xonxoff = False instrument.precalculate_read_size = False instrument.mode = minimalmodbus.MODE_RTU # rtu or ascii mode instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) #a =instrument.read(numero_registrador , id_escravo) a = instrument.read_register(289, 1) -
How to change permission based on request.query_params in Django rest frameworks?
I merged together two views that almost does the same thing except the permission, I want to change permission based on: if company id is in the params. If not, it would use a simple IsAuthenticated class and also created a permission for IsCompany. class FilesView(ListAPIView): serializer_class = FileSerializer permission_classes = (IsAuthenticated,) ... def get_queryset(self): if 'company' in self.request.query_params: # In this case I want the IsCompany Permission class return get_company_files(self) # Otherwise the regular one return get_personal_files(self) -
In my Inventory App, have been trying to make multiple sales at once which prompt me to create two models one for ordering second for save sales
in anytime i tried to submit my order it wont submit the quantity then, have been trying harder to get it submit but always get this error ( Field 'quantity' expected a number but got 'None'.) Here is my models... permanent sale save table class Sales(models.Model): delivery_date = models.DateField(auto_now_add=True) discount_price = models.IntegerField(blank=True, null=True) quantity = models.IntegerField(default = 0, null = True, blank = True) amount_received = models.IntegerField(default = 0, null = True, blank = True) payment = models.ForeignKey(Payment, on_delete = models.CASCADE) # balance = models.IntegerField(default = 0, null = True, blank = True) issued_to = models.ForeignKey(Customer, on_delete = models.CASCADE) unit_price = models.IntegerField(default = 0, null = True, blank = True) status = models.CharField(max_length=100) def __str__(self): return self.issued_to.company_name def draft(self): return self.status == 'Draft' def paid(self): return self.status == 'Paid' def Unpaid(self): return self.status == 'Unpaid' This is order table... class SalesItems(models.Model): pick_id = models.IntegerField(default= 0) item = models.ForeignKey(Product, on_delete = models.CASCADE,default = 1) cost_price = models.CharField(max_length= 100) # status = models.CharField(max_length=10) discount = models.IntegerField(default = 0, null = True, blank = True) amount_received = models.IntegerField(default = 0, null = True, blank = True) selling_price = models.IntegerField( default= 0) quantity = models.IntegerField(default= 0) total_cost = models.IntegerField(default= 0) buying_time = models.DateTimeField(auto_now_add=True) update_time … -
How to use Bootstrap 'Dashboard' example in my Django project?
I currently use bootstrap components (4.3.1) but I would like to use a full example: https://getbootstrap.com/docs/4.1/examples/dashboard/ But there are not many explanations to use it, except to download source code but there are so many files that I am lost. I've read the documentation (https://getbootstrap.com/docs/4.1/getting-started/introduction/) but not really explained how to use full example... -
Django Authentication credentials were not provided. problem
I have an 'Authentication credentials were not provided. ' error while trying to get Response from server, and here is the code... I can register user, and new token is created, and when I call login URL, I get token in response, but when I try to access url using that Token, I get this error. Here is the code I followed this tutorial: "https://www.youtube.com/watch?v=Wq6JqXqOzCE" for register and login user... Django project code: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } Here is urls.py urlpatterns = [ path('register', views.register_view, name='register'), path('login', obtain_auth_token, name='login'), path('testuri', views.example_view, name="example_view") ] Here is the views.py and this method is called @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) And here is apache httpd.conf file edited WSGIPassAuthorization On ServerName localhost:80 #Django project LoadFile "C:/Python39/python39.dll" LoadModule wsgi_module "C:/Users/userr/djangoProjects/virtualEnvDjango/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Python39" WSGIScriptAlias / "C:/Users/userr/djangoProjects/projects/appblproject/appblproject/wsgi.py" WSGIPythonPath "C:/Users/userr/djangoProjects/projects/appblproject/" <Directory "C:/Users/userr/djangoProjects/projects/appblproject/appblproject/"> <Files wsgi.py> Require all granted </Files> </Directory> I have tested it using Postman, but also in this way: Token is created few minutes ago and I think it is valid, it must be.. curl -X GET http://127.0.0.1:8000/testuri -H 'Authorization: Token 05183628a512124442b976330a21d5fde9d142fd' Am I missing … -
ERROR in src\containers\Login.js Line 35:5: Parsing error: Unexpected token (35:5)
Hello guys I'm new in React while watching a tutorial I'm getting this error and I checked it multiple times and compared it with the one in tutorial and can't find any difference. I'm trying to create a user authentication with Django and React. I'm using sublime text 3 as an editor and I have also Visual Studio Code installed. Should I install any extension to handle this problem? Can you help me with this parsing error? import React, { useState } from 'react'; import { Link, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; const Login = () => { const [formData, setFormData] = useState({ email: '', password: '' }); const { email, password } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = e => { e.preventDefault(); // login(email, password) }; // Is the user Authenticated? // Redirect them to the home page return ( <div className='container mt-5'> <h1> Sign in </h1> <p> Sign into your account </p> <form onSubmit={e => onSubmit(e)}> <div className='form-group' <input className='form-control' type='email' placeholder='Email' name='email' value={email} onChange={e => onChange(e)} required /> </div> <div className='form-group' <input className='form-control' type='password' placeholder='Password' name='password' value={password} onChange={e => onChange(e)} minLength='6' required /> … -
Django and Iyzco Integration
I am trying build e-commerce back-end system with Django. But I don't have any idea about the payment system. I researched for Iyzco tutorial for Django but couldn't find any halber things. So Can anybody suggest to me any tutorial or website or any course? -
'float' object is not iterable in django queryset
class TransactionHistoryListSerializer(serializers.BaseSerializer): class Meta: model = CustomerVisit def to_representation(self, instance): price = 0 package_price = booking_models.TestBooking.objects.filter(customer_visit=instance).values_list("package__test__test_mrp", flat=True)[0] for price in package_price: pass return{ 'visit_id':instance.id, 'customer_name':{ 'salutation':instance.customer.salutation, 'first_name':instance.customer.first_name, 'middle_name':instance.customer.middle_name, 'last_name':instance.customer.last_name}, 'dob':instance.customer.date_of_birth, 'amount':sum([k.amount for k in booking_models.TestBooking.objects.filter(customer_visit=instance)]) + (price if price else 0), 'discount': sum([k.discount for k in booking_models.TestBooking.objects.filter(customer_visit=instance)]), 'paid_amount': sum([k.amount for k in payment_models.Payment.objects.filter(customer_visit=instance)]) } here tes_mrp is float type. I searched and got solution to use list comprehension but still not working. I tried [[price] for price in package_price], for price in package_price: a = list(str(price)) but still getting float object is not iterable. Surely i am doing something wrong. Can somebody help. Thank you !! -
Accessing dictionary values in a list of dicts django
I have this code that translates my queryset into a list of dict groupmembers = GroupUser.objects.filter(group_id=group_id) memberlist = [] for member in groupmembers: user = User.objects.get(username=member.username) entry = { "username":user.username, "first_name":user.first_name, "last_name":user.last_name } memberlist.append(entry) How can I access each individual value in the list of dict? I tried to use: <ul> {% for key, value in memberlist.member %} <li>{{ member.username }} {{ member.first_name }} {{ member.last_name }}</li> {% endfor %} </ul> But it was raising an error, what's the appropriate code to use