Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my url in "not matching any url" when it is? I have no idea how to fix it, am I doing something wrong?
Im not gonna lie, this doesnt make any sense to me, why is this trying to access 'post-details' instead of 'create-post' and how do I fix it? Thank you in advance error: NoReverseMatch at /create/ Reverse for 'post-details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/post/$'] Request Method: GET Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-details' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/post/$'] Post create view: class PostCreate(CreateView): model = Post form_class = PostCreateForm template_name = 'post/post_create.html' context_object_name = 'form' def get_success_url(self): return reverse('post:home') def form_valid(self, form): form.instance.author = self.request.user.profile return super().form_valid(form) My urls: from django.urls import path, include from . import views app_name = 'post' urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/post/', views.PostDetails.as_view(), name='post-details'), path('search/', views.search, name='search'), path('comment-delete/<pk>/', views.CommentDelete.as_view(), name='comment-delete'), path('comment-update/<pk>/', views.CommentUpdate.as_view(), name='comment-update'), path('tag/<str:name>/', views.PostTagList.as_view(), name='tag-posts'), path('create/', views.PostCreate.as_view(), name='create-post') ] post_create.html file from my PostCreate view: {% extends 'base.html' %} {% block content %} <div class="container mt-5 mb-5"> <form action="" class="commenting-form" method="post" enctype="multipart/form-data"> <div class="row"> <div class="form-group col-md-12"> {% csrf_token %} {{ form.tags }} <div class="form-group col-md-12"> <button type="submit" class="btn btn-secondary mt-2">Edit comment</button> </div> </div> </div> <div class="row"> <div class="form-group col-md-12"> {% csrf_token %} {{ form.body }} {{ form.picture … -
Select2 multi-select items showing outside the input field, overlapping with other fields
I'm using Select2 multi select in a Django app, and I'm having an issue where the selected items are being drawn outside the input field. Any thoughts on how the css has been mucked up to cause this? image showing multi-select items outside the field Thanks, Glenn -
Handle/fix django.core.exceptions.SuspiciousFileOperation in unit testing Django (nosetests)
I want to write a test for a Managment command that reads a file and does something. Everything works as expected. And for clean organization of my test files (in this case I check whether the read CSV file has certain validations), I want to place the test CSV file under my_project/my_app/tests/files/test_me.csv. And, when I run the test, Django is throwing this error django.core.exceptions.SuspiciousFileOperation: The joined path (/code/my_project/my_app/test/files/test_me.csv) is located outside of the base path component (/code/media). Here is my test code, class CommandTestCase(TestCase): def test_command_load_client(self): """Happy path for load client from a CSV File""" call_command('my_command_that_does_some_csv_checks', os.path.join(BASE_DIR, "my_app/tests/files/test_me.csv"),) # self.assertEqual(some_assertions, 1) If I put this file under /code/media however, this error does not occur. But I do not want to store it under /code/media. How to solve this problem? Note: I come from a Rails background. -
Renaming a field on a Django queryset with group by
I'm counting the users by month that have been registered this year. from rest_framework.response import Response from django.db.models.functions import TruncMonth from django.db.models import Count from django.db.models import F return Response(User.objects .filter(date_joined__year=timezone.now().year) .annotate(month=TruncMonth('date_joined')) .values('month') .annotate(qtd=Count('id')) .values('date_joined__month', 'qtd') The result of this queryset it's been returned as: [{"date_joined__month": 1,"qtd": 5},{"date_joined__month": 2,"qtd": 35}] I want to change the name of the field "date_joined__month" to "month_id" and keep the counting and group by logic. I already tried to add the following approaches, but they both returned the full date format instead return only the month id: "month_id": "2021-01-07T15:26:53.080136Z" .annotate(month_id=F('date_joined__month')) .values('qtd', 'month_id')) or .values('qtd', month_id=F('date_joined__month'))) -
How can I get the value for type "textinput" as manytomanyfield data in django's modelform?
goal : The data on the board has a tag. To update and save the tag,'forms.py' must first fetch the data using modelform. Problem : I was trying to get data as dict type using'value_from_datadict'. The modelform class couldn't access it. And'print message' was put in'value_from_datadict' to confirm, but it was not displayed. # forms.py class ManyToManyInput(forms.TextInput): def value_from_datadict(self, data, files, name): print("value_from_datadict inside") value = data.get(name) if value: return value.split(",") class BoardUpdateForm(forms.ModelForm): class Meta: model = Board fields = ["title", "contents", "tags"] # fields = "__all__" labels = { "title": ("title"), "contents": ("contents"), "tags": ("tag"), } widgets = { "contents": forms.Textarea(attrs={"cols": 80, "rows": 20}), "tags": ManyToManyInput().value_from_datadict(), } help_texts = {} error_messages = { "title": { "required": ("Please enter the title."), }, "contents": { "required": ("Please enter your content."), }, } In order to use the update form, I sent the data using the "Instance" option like the following source code. # view.py def board_update(request, pk): try: board = Board.objects.get(pk=pk) except Board.DoesNotExist: raise Http404("There are no board data") if request.method == "POST": form = BoardUpdateForm(request.POST) if form.is_valid(): print("inside is_valid") user_id = request.session.get("user") usert = Usert.objects.get(pk=user_id) tags = form.cleaned_data["tags"].split(",") board.title = form.cleaned_data["title"] board.contents = form.cleaned_data["contents"] board.writer = usert board.save() print("board :", … -
Confusing field accessing on m2m field in a query set
I have a django project with several models. Two of this models are: class Attack(models.Model): spell = models.ForeignKey("Spell", models.CASCADE, null=True) attacker = models.ForeignKey("Ent", models.CASCADE, related_name='attacker') defender = models.ForeignKey("Ent", models.CASCADE, related_name='defender') defender_pts_before = models.IntegerField(default=0, blank=False, null=False) damage_caused = models.IntegerField(default=0, blank=False, null=False) and class Ent(models.Model): name = models.CharField(max_length=50, blank=False, null=False) raze = models.CharField(max_length=50, blank=False, null=False) damage = models.CharField(max_length=50, blank=False, null=False) weakness = models.CharField(max_length=50, blank=False, null=False) health = models.FloatField(default=100, blank=False, null=False) attacks = models.ManyToManyField('self', through=Attack, symmetrical=False, related_name='attacked_from') battles = models.ManyToManyField(Battle, through=BattleParticipant, related_name='battles_part') As you can see the Ent model has a m2m field to itself through the Attack model. This is for representing the attacks between ents. The attack model stores all the damage the attacker caused to the defender in the damage_caused field (which is calculated when the attack is saved). I need to know for each ent the total damage it has caused in all the attacks, so I built the following query: Ent.objects.all().annotate(dmg=Sum('attacks__attacker__damage_caused')) but this doesn't seems to work. It only seems to work the right way with this query: Ent.objects.all().annotate(dmg=Sum('attacks__defender__damage_caused')) Tests I've created some entries to check the query (a single attack from one ent to another) In [106]: e1, e2 = Ent.objects.all().annotate(dmg=Sum('attacks__attacker__damage_caused'))[:2] In [107]: e1, e2 Out[107]: (<Ent: … -
DJANGO - How to store Model data in another model by modifying the __init__ and save() methods, with a Test Driven development approach?
So, lets assume I have two models, my main model where I have the data that goes to my endpoint, and a second model that I'm using to store the changes made to a field of the main model. They're very simple, like this: Main Model: M class MyModel(TimeStampedModel, models.Model): """A simple model""" field_1 = models.CharField(max_length=255, null=True, blank=True) field_2 = models.CharField(max_length=255, null=True, blank=True) choice_field = models.CharField( max_length=32, choices=ChoiceModel.choices, default=None, null=True, blank=False ) And the storing Model: Class MyModelHistory(models.Model): choice_field_from = models.CharField(max_length=32, null=True, blank=False) choice_field_to = models.CharField(max_length=32, null=True, blank=False) changed_at = models.DateTimeField() Now, there are various ways to connect these two. To make it easier, I'm only intereseted in tracking the changes made to choice_field. We could do it with signals or by modifying the __init__ and save methods of MyModel. For my application, I have to do with the latter, so here's what I've got so far: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #import pdb; pdb.set_trace() if self.pk is None: self._old_choice = None else: self._old_choice = self.choice_field def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._old_choice != self.choice_field: MyModelHistory.objects.create( choice_field_from=self._old_choice, choice_field_to=self.choice_field, changed_at=timezone.now(), ) I'm making the tests to make sure this approach works in all possible scenarios. For example, when you … -
How to estabilish ContentType relation in Django for Laravel Polymorphic related data?
I have a database that was created and working for the Laravel application, it contains a table with shared data for multiple models using "Laravel Polymorphic Relationships" For example, this is Comment model that contains comments for the Product, Post, Seller. id commentable_type commentable_id Comment 1 App\Product 1 Comment text 2 App\Product 2 Comment text 3 App\Seller 1 Comment text I need to use this table in the Django application, I tried to create relation using ContentType Framework but no success because it's requires ContentType (int) relation to determine the model, but in the database, I have string values for _type. Any suggestions on how to deal with it? -
Multiple values using GET method in my template? with django
I am trying to send info using GET method and the django paginator. I am using buttons to send the request and on my views display the corresponding list, that works fine. However, the problem is when I change page to page=2 or whatever, the url is replaced. For example: you click the button A and the url should appear webpa.com/expedient?letter=A and when you clic next page, it is replaced webpa.com/expedient?page=2 instead of webpa.com/expedient?page=2&letter=A My template is as follows: <form action="expedient" method="GET"> <button type="submit" name="letter" value="A">A</button> <button type="submit" name="letter" value="B">B</button> <button type="submit" name="letter" value="C">C</button> <button type="submit" name="letter" value="G">G</button> <button type="submit" name="letter" value="L">L</button> <button type="submit" name="letter" value="N">N</button> </form> and the paginator also in the same template is: {% if is_paginated %} <nav aria-label="Paginador de portafolio"> <ul class="pagination"> <li class="page-item"><a class="page-link" {% if page_obj.has_previous %} href="?page={{ page_obj.previous_page_number }}"{% else %} href="#" {% endif %}>Anterior</a></li> {% for num in page_obj.paginator.page_range %} <li class="page-item"><a class="page-link" href="?page={{ num }}">{{num}}</a></li> {% endfor %} <li class="page-item"><a class="page-link" {% if page_obj.has_next %} href="?page={{ page_obj.next_page_number }}" {% else %} href="#" {% endif %}>Siguiente</a></li> </ul> </nav> {% endif %} How can I send the value of the letter in the form and the page number? -
Capturing Images from Webcam Using OpenCV , Django and show the captured image in HTML Page
I want to capture the image using OpenCV in Django web application and show captured image in HTML page and needed to compare the captured image with the previously detected images. can anyone give me idea how to code ? -
how can i use try and except while getting model objects?
i am new to python and django, i have to use a try and except block with the following code, as i am trying to get a model class object but in case if database is empty so for that i need to use try and except. if(txStatus=='SUCCESS'): order=Order.objects.get(id=id) #NEED TRY ACCEPT BLOCK FOR THIS URL = payment_collection_webhook_url request_data ={} json_data = json.dumps(request_data) requests.post(url = URL, data = json_data) return Response(status=status.HTTP_200_OK) -
How can I completely convert my django application to a andriod mobile application
How to convert my django web application to a complete andriod mobile application to use in the andriod platforms -
IntegrityError: FOREIGN KEY constraint failed in django
I have a django view that causes FOREIGN KEY constraint failed. This is coming from a related question def return_book(request,pk): books = Books.objects.filter(school = request.user.school).get(id = pk) book = Issue.objects.get(book_id_id=pk,book_id__school_id = request.user.school.id) user = CustomUser.objects.get(id=request.user.id) Return.objects.create(borrowed_item_id=book.id,returner=user) Books.Addbook(books) Issue.objects.get(book_id_id=pk).delete() return redirect("view_books") The erro is returned at Issue.objects.get(book_id_id=pk).delete() I don't know the exact cause of this error. Could somebody explain to me what's going on hat causes the error> The Traceback is below. Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 209, in return_book Issue.objects.get(book_id_id=pk).delete()#Borrower_id is also required in the filter File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 947, in delete return collector.delete() File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\deletion.py", line 396, in delete count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 43, in delete_batch num_deleted += self.do_query(self.get_meta().db_table, self.where, using=using) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\subqueries.py", line 23, in do_query cursor = self.get_compiler(using).execute_sql(CURSOR) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql cursor.execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", … -
Issue in Login with Django sqlite3 database
enter image description here **I want to login with the email that existed in the table named "user" in the sqlite3 database. Whenever I am trying to find matching the emails as given photo. The "for" loop checking only the 1st email from the table of the database. What should I do to check all the emails existed there and then login when both are matched. Please help me to solve it. ** -
i tried to deploy my Django app in Heroku
I used this command to do it but I have an error : pip install python-git pip install gunicorn pip install django-heroku pip freeze > requirements.txt npm install -g heroku heroku login heroku create dmracademy git init git status git add . git commit -m "first version uploaded" heroku git:remote -a dmracademy git push heroku master after I write git push heroku master i have this error: enter image description here -
Unable to login to django admin after a customized Models
I have successfully created several superusers using python manage.py createsuperuser but I am unable to login in the admin despite providing the right credentials. Here is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.utils import timezone class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, full_name, phone, password, next_of_kin_name, next_of_kin_number, **extra_fields): values = [email, full_name, phone, next_of_kin_name, next_of_kin_number] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, full_name=full_name, phone=phone, next_of_kin_name=next_of_kin_name, next_of_kin_number= next_of_kin_number, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, full_name, phone, next_of_kin_number, next_of_kin_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, full_name, phone, next_of_kin_name, next_of_kin_number, password, **extra_fields) def create_superuser(self, email, full_name, phone, next_of_kin_number, next_of_kin_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, full_name, phone, next_of_kin_name, next_of_kin_number, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) full_name = models.CharField(max_length=150) phone = models.CharField(max_length=11) next_of_kin_number= models.CharField(max_length=11) next_of_kin_name = models.CharField(max_length=150) #date_of_birth = models.DateField(blank=True, null=True) #picture = models.ImageField(blank=True, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True,) … -
Could not find a version that satisfies the requirement pywin32 on cpanel
My os is windows 10 where I can install pywin32 without having any problem but When I'm going to install pywin32 on Cpanel(Namecheap) in my Django app then showing the following error. Please notice the image where everything is almost the same version just python 3.9.2 on windows and python 3.8.6 on Cpanel. Also, I tried several pywin32 version on CPanel but didn't work. enter image description here Which procedure I should follow to install pywin32 or pypiwin32 on my Cpanel? Thanks in Advance. -
How to return to HTTP_REFERRER instead of passing a template to TemplateResponse?
I am writing an application that has a page with content ideas. User has the ability to schedule any post right from this page. The schedule button calls a view SocialPost that schedules a post and then redirects the user to the same page from where it came using return HttpResponseRedirect(request.META.get('HTTP_REFERER')). This works perfectly fine. However, I am also using a middleware and TemplateResponse hook to decrement the user-allocated quota. I understand that in order to make TemplateResponse hook to work I should return TemplateResponnse in the view instead of HttpResponseRedirect. The problem is that I don't have the html file path to pass in TemplateResponse. The equivalent I have been using is return TemplateResponse(request, request.META.get('HTTP_REFERER')). This is not working. Can you please guide how to redirect to the same page from user came using TempalteResponse. -
How to prevent a user from manually going to some specific urls?
In my app, I want the user to access one specific url when he has paid the money via paypal client-side integration. my paypal integration comes from here. Now at the end(of the given link) I have to redirect the user to another page, by doing this, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); window.location.href='/accepted/{{transaction_id}}'; }); Now at the accepted page, I have to do some serious tasks that includes inserting records to database about the whole transaction. If user pays the money and go to that page, it's fine. But if the user inspected the page(by pressing F12) and manually moved to that url, he wouldn't pay but the transaction will be stored on the database. How can i avoid this? Please guys, I have been stuck for a long time. Thank you:) -
How to refer a submit element after submiting the form?
I am trying to refer a submit element after submitting a form but it is not working. At first, a tab named London consists a form and after submitting the form the result is stored in Paris tab. But after I submit the form, the form redirects to the same page and to the same tab instead of Paris tab. Here is the code: main.html <div class="tab"> <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button> <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button> <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button> </div> <div id="London" class="tabcontent "> <h3 class='poppins'>Your Map</h3> <form method='POST' onsubmit="openCity(event, 'Paris'); return false">{% csrf_token %} {{ form.as_p }} <input type='submit' value='Save' class="login-btn poppins"/> </form> </div> <div id="Paris" class="tabcontent"> <h3>Paris</h3> <p>Paris is the capital of France.</p> <img src="{{ image_url }}"> </div> <div id="Tokyo" class="tabcontent"> <h3>Tokyo</h3> <p>Tokyo is the capital of Japan.</p> </div> </div> </div> <script> function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } Here is the Image of the main.html -
Django redirect a custom rendered 404.html template
I want to redirect a custom template when an invalid url is entered in my Django website. When an incorrect URL, for example /home/ll, is entered then 404.html is shown on the screen and the url is redirected to /error. -
(Internal Server Error) on django web push notifications with heroku
I'm building a messages app where a user can send incognito messages so the reciever wouldn't know who send the message.. any way just needed to implement push notifications so whenever new message come to a user he receives a push notificatoin I've followed this article which i found after some searching and it worked perfect for me on the local host ,how ever when i tried to deploy my app on heroku that didn't work things I've faced 1- error on the front end first time i tried it out it worked perfect but just as I reloaded the page I found this error in the console registerSW.js:66 POST https://stalker-rat.herokuapp.com/webpush/save_information 500 (Internal Server Error) this 66 line is responsible for saving the information about the registered service worker I think , but this caused problems as the service worker was already saved , i thought that the browser would handle this .. any way this is my code const res = await fetch('/webpush/save_information', { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json', }, credentials: "include" }); at first i thought this was some thing about the csrftoken but adding it to the post request didn't do any thing error … -
from ._compat import PY2 ModuleNotFoundError: No module named 'pydrive._compat'
On running the script in init.py file: from ._compat import PY2 from .constants import FIELD_TYPE from .converters import escape_dict, escape_sequence, escape_string from .err import ( Warning, Error, InterfaceError, DataError, DatabaseError, OperationalError, IntegrityError, InternalError, NotSupportedError, ProgrammingError, MySQLError) from .times import ( Date, Time, Timestamp, DateFromTicks, TimeFromTicks, TimestampFromTicks) I get the following error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "E:\project\pydrive-project-master\pydrive-project-master\pydrive\pydrive\__init__.py", line 27, in <module> from ._compat import PY2 ModuleNotFoundError: No module named 'pydrive._compat' I already have PyDrive installed in the environment. How do I resolve this error? -
Running Total in Django Template
I listed debit and credit for my account transactions. Now I want to running total in last column by debit subtracted by credit added with previous arrived amount as running total (as you know). Thanks for your support. my view: def listaccounttrans(request): alltrans = FinTransDetail.objects.all() context = {'alltrans': alltrans} return render(request, 'waccounts/list_account_trans.html', context) my html: {{% extends 'wstore_base_generic.html' %}} {% block content %} <h3>Table</h3> <div> <table id="customers" > <thead> <tr> <td>AcctCode</td> <td>TransNo</td> <td>TransDate</td> <td>AcctDetail</td> <td>Debit</td> <td>Credit</td> <td>Balance</td> </tr> </thead> <tbody> {% for acct in alltrans%} <tr> <td>{{ acct.fd_acct }}</td> <td>{{ acct.fd_no}}</td> <td>{{ acct.fd_no.fh_dt}}</td> <td>{{ acct.fd_no.fh_detail }}</td> <td>{{ acct.fd_debit }}</td> <td>{{ acct.fd_credit }}</td> <td>{{ acct.fd_no}}</td> # needs running total here# </tr> {% endfor %} </tbody> </table> </div> {% endblock %} my template is showing now: AcctCode TransNo TransDate AcctDetail Debit Credit Balance 1101 94 May 18, 2021 Detail 11.00 0.00 94 (needs to be replaced with 1101 94 May 18, 2021 Detail 0.00 11.00 94 running balance) [total balance] -
Django models to hold a list of objects from another Model
I am creating a shopping cart for an e-commerce platform. I have made a Products model and the I need to create a Cart model. One cart can have multiple products in it. I need to create a field products in the cart which is a list of multiple product objects. I am not sure how to do it but I can think of two ways:- Create a list of ids of all the products Create a list which contains the product objects inside of them (this might save lookup time) The product model looks like this:- class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='market/static/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) The foreignkey relation doesn't seem to work here because it only stores one entry at a time. I think ManytoManyFields might work but I am not able to connect it between these two models.