Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using docker secrets without swarm
I recently went trough a nextcloud deployment and I saw at the nextcloud docs that I could use docker secrets without a docker-swarm setup it seems: https://hub.docker.com/_/nextcloud/ -> Docker Secrets Now I have Integrated secrets into my docker-compose file like so: secrets: mariadb_password: file: secrets/mariadb_password.txt services: app: build: .... environment: MYSQL_PWD: /run/secrets/mariadb_password But currently it seems that my application does not use the content of /run/secrets/mariadb_password instead it uses the path to the file and not the content of it. This is how I currently load my mariadb config at my Django application: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'NAME': env.str('MYSQL_DB'), 'USER': env.str('MYSQL_USER'), 'PASSWORD': env.str('MYSQL_PWD'), 'HOST': env.str('MYSQL_HOST'), 'PORT': env.str('MYSQL_PORT'), } } I also have read at the nextcloud docs that: As an alternative to passing sensitive information via environment variables, _FILE may be appended to the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. Do I need to write a initialization script myself? If so, is there a pratical example to do this? thanks in advance -
How to retrieve a GenericRelation data using single query in Django
My aim is to retrieve a GenericRelation data using single query & without use of for loop. Example: I have Customer model & Address model from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Customer(models.Model): name = models.CharField(null=False, blank=False, max_length=255) email = models.EmailField(null=False, blank=False, unique=True) address = GenericRelation(Address) class Address(models.Model): address1 = models.CharField(max_length=255) address2 = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') Bellow is the traditional way i archive GenericRelation data result = [] customer1 = Customer.objects.filter(pk=1) customer1_obj = Customer.objects.get(pk=1) address_of_customer1 = customer1_obj.address.all() result.append({'customer_data': customer1.values(), 'address_data': address_of_customer1.values()}) print('---result---', result) ---result--- [{'customer_data': <QuerySet [{'id': 1, 'name': 'Aakash', 'email': 'aakash@g.com'}]>, 'address_data': <QuerySet [{'id': 2, 'address1': 'Flat 1-2', 'address2': 'Road 1-2', 'content_type_id': 18, 'object_id': 1}, {'id': 1, 'address1': 'Flat 1-1', 'address2': 'Road 1-1', 'content_type_id': 18, 'object_id': 1}]>}] But this is not Good solution. Take too much time when ids is in thousands of range. If is there any other way to archive those data. Then please give your solution in comments.. Note: Make sure your query result get customer & address data in one result. without use of for loop. -
django.core.exceptions.ImproperlyConfigured and TypeError: 'module' object is not iterable
I have a very annoying problem. There was an errors in the project I am creating: django.core.exceptions.ImproperlyConfigured: The included URLconf 'My_Site.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. and TypeError: 'module' object is not iterable views.py: class UserRegisterView(View): def get(self, request): form = UserCreationFormv2() return render(request, "registrationReg.html", {'form': form})` def post(self, request): form = UserCreationFormv2(request.POST) if form.is_valid(): user = form.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') UpdateUser.objects.create(user=user) else: return render(request, "main.html") urls.py: from django.contrib import admin from django.urls import path from MySite.views import OrganizationRegisterView, UserRegisterView urlpatterns = [ path('', OrganizationRegisterView.as_view(), name='Organizators Registration'), path('/user', UserRegisterView.as_view(), name='Regular User Registration') ] probably, there is some mistake in my code, but i cant see it -
Trouble installing django-heroku
I am trying to deploy my django application to heroku When I try and; '''pip install django-heroku''' It gives me this error; ''' ERROR: Command errored out with exit status 1: command: /Users/huntermackenzie/Dev/personal/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info cwd: /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/ Complete output (23 lines): running egg_info creating /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info writing /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/private/var/folders/15/k9lcjv5129v661mkkrsdt09w0000gn/T/pip-install-v2fvrgwp/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.''' Then I try and; '''pip install psycopg2''' And I get the same error. Can someone please help me. Thank you. -
how to make edit functionality by using django form
I have two models parent and child models and they have relationship to each other it means that a child can have a parent,and then i have this template which i pass a child id on it that will display edit fields for parent, the problem that i face is that,i can see the form fields into the template but there is no value on it that will help me to edit here is my child model from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) def __str__(self): return self.Firstnam here is my parent model class Parent(models.Model): child = models.ForeignKey(Child_detail,on_delete=models.CASCADE) Parent_firstname = models.CharField(max_length = 100) Parent_lastname = models.CharField(max_length = 100) Current_address = models.CharField(max_length = 100) def __str__(self): return str(self.Parent_firstname) here is my views.py file for editing parent details def edit_parent(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=ParentForm(request.POST) if form.is_valid(): form.instance.child=child form.save() return redirect('more_details',pk=pk) else: form=ParentForm() context={ 'form':form, 'child':child } return render(request,'functionality/parents/edit.html',context) here is form.py file class ParentForm(forms.ModelForm): class Meta: model=Parent fields=['Parent_firstname','Parent_lastname','Current_address','Phone_number','Parent_job', 'Life_status','Other_parent_name','Other_parrent_phone_number'] labels={ 'Parent_firstname':'Parent Firstname','Parent_lastname':'Parent Lastname', 'Other_parent_name':'Other Parent Name', 'Current_address':'Current Address','Phone_number':'Phone Number', 'Other_parrent_phone_number':'Other Parent Phone Number', } and here is my template {% extends 'base.html' %} {% block content %} <form action="" method="post" autocomplete="on"> {% csrf_token %} <div … -
Dynamic Allowed Host in Django
I'm developing multitenant application using django. Every things works fine. But in the case of ALLOWED_HOST , I've little bit confusion, that how to manage dynamic domain name. I know i can use * for any numbers for domain, But i didn't wan't to use * in allowed host. Here is my question is there any way to manage allowed host dynamically. -
Author of the post is not set to current logged in user
I created this simple model: class FormModel(models.Model): fullname = models.CharField(max_length=150) slug = models.SlugField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) I passed blank=True and null=True so that it can pass form_valid condition. and then set the author of the current post to current logged in user, but sounds I am making a mistake here. Can anyone help. Here is how the views looks like: def FormsView(request): if request.method == 'POST': form = FormsProject(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) form.author = request.user.username print(form.author) form.save() return HttpResponse("Success") else: form = FormsProject() context = { 'form': form, 'user': request.user.username } return render(request, 'forms_project/forms.html', context) Thank You -
How to display Data from two model without creating new model in Django?
I have two models with one common field (email). I using viewset.ModelViewset to list and create data in both the models. My models.py: class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() email = models.EmailField(unique = True ) def __str__(self): return self.email class Status(models.Model): """ Model For status """ email = models.EmailField(unique = True ) status = models.TextField() def __str__(self): return self.email my view.py: class StatusViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Status.objects.all() serializer_class = serializers.StatusSerializer class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer I want to overide List function of Status Viewset to display entire detail of that user. For ex: from schema viewset i have created : { "id": 1, "name": "Yatharth", "version": "1.1", "email": "yatharth@test.com" } and From Staus viewset i have POST the status of Email: yatharth@test.com to Active. From GET of Status VIewset I want to display data like this: { "name": "Yatharth", "version": "1.1", "email": "yatharth@test.com" "status": "Active" } How to do this? -
I need to run Shell Script using django in side a Docker container
my shell file #!/bin/bash echo "Success" exit 1 I called the above file using following command. python file subprocess.call(["bash", "scripts/test.sh"], shell=True) This works fine when running without the Docker container. But it shows an error when running inside the container. Can anyone help me? -
blog_index() missing 1 required positional argument: 'body'
Hi I'm a newbie in django framework and I got an error like this blog_index() missing 1 required positional argument: 'body' this is my code: views.py def blog_index(request,body): body = Post.objects.get(body) posts = Post.objects.filter(body=body) form = ProfileForm(instance=posts) context = {"posts": posts, 'form': form} return render(request, "blog_index.html", context) I want to get data body from post , how to make it possible? Thanks. -
Django Deploy to heroku: Application Error
I deployed my Django project to heroku. It deployed successfully but the page shown Application error. In logs on heroku error be like this. 2020-04-24T05:34:09.500250+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [4] [INFO] Using worker: sync 2020-04-24T05:34:09.506988+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-24T05:34:09.532649+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [11] [INFO] Booting worker with pid: 11 2020-04-24T05:34:10.051702+00:00 heroku[web.1]: State changed from starting to up 2020-04-24T05:34:20.000000+00:00 app[api]: Build succeeded 2020-04-24T05:34:26.126726+00:00 app[web.1]: [2020-04-24 05:34:26 +0000] [4] [INFO] Shutting down: Master 2020-04-24T05:34:41.808971+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/favicon.ico" host=dashboard-retail.herokuapp.com request_id=f5feaeba-075f-4dc7-a637-fe6b271f0d67 fwd="125.24.11.115" dyno=web.1 connect=1ms service=30003ms status=503 bytes=0 protocol=https 2020-04-24T05:34:42.096139+00:00 app[web.1]: [2020-04-24 05:34:42 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10) In Procfile,I set like this web: gunicorn myWeb.wsgi --log-file - -
How to add dynamic URLs for different cities of a country Django-leaflet
I have a shapefile of a country on districts level. I want every district to be clickable on shapefile on Leaflet (Django) and get to another URL where it shows stats of that city or district on another page. How can I set dynamic URLs like each district have a unique id so URL will be based on id? I don't know how to get this process done. -
Count forengkey django rest framework?
When I count the likes i got all the count from database. I would like to count only the likes related with an article class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) comments = CommentSerializer(read_only=True, many=True) likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = "__all__" def get_likes(self, value): return Vote.objects.select_related('article').filter(value=True).count() -
Getting the selenium scraping script output in web browser using django?
I had wrote a script for scrapping the data of all the matches that are being shown in this url https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590 the script which I wrote is scrape.py import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import mysql.connector import pymysql from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # the relevant url url = 'https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590' # the driver path driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds buttons = WebDriverWait(driver,15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) for btn in range(len(buttons)): #elements re-assigned again to avoid stale. buttons = WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) buttons[btn].click() headings= [item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] keys = [item.text for item in driver.find_elements_by_css_selector("div.SEOdd.g1")] values = [item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] driver.execute_script("window.history.go(-1)") print(headings,keys,values) when I run this script in console using python scrape.py then I am getting output i.e scraping all the matches values dynamically now I actually I tried this script in django views.py and want to show the output in web page for that I wrote code like this views.py from django.shortcuts import render from django.http import HttpResponse import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as … -
KeyError at /recommendation/ 'comb'
why I am getting this error at [comb] but when I have already mention it in create.py and in my views too when I have mentioned all the thing to be assign my views.py where I have also mentioned the [comb] def create_sim(): df = pd.read_csv('movies.csv') cv = CountVectorizer() count_matrix = cv.fit_transform(df['comb']) sim = cosine_similarity(count_matrix) return df, sim print("recommendation") def recommendation(request): if request.method == 'POST': movie = request.POST['movie'] movies = recomend(movie) movie = movie.upper() print("here is your movies ", movie) if type(movies) == type('string'): return HttpResponse('recommend.html', movie=movie, movies=movies, t='s') else: return HttpResponse('recommend.html', movie=movie, movies=movies, t='scores') return render(request, 'recommend.html') in this section, I have also mentioned the [comb] but in my ipynb I have mentioned combined_features is that the case or what. Mycreate.py df = pd.read_csv('movie_dataset.csv') df['comb'] = df['cast'] + ' ' + df['keywords'] + \ ' ' + df['genres'] + ' ' + df['director'] cv = CountVectorizer() count_matrix = cv.fit_transform(df['comb']) -
Create Views with DJangocms
I have just started with djnago cms 1 week ago . I have designed a simple html templates and used that template with home page . there is a form which accepts username & password in inside that template. Now my question is how can i connect that form with view.py so that it will check the form data and return response. -
How to change the name/label to delete objects in the change list page in Django admin
I'm working on Django and I want to change the name/label with which the delete action appears in the change list page in Django admin as shown in the pic : my admin.py file looks like this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So is there any way to change it or is it permanent?? Thanks in advance!! -
Stripe InvalidRequestError InvalidRequestError at /payment/stripe/ Request req_5yo1v0CwbYGjTV: Must provide source or customer
Hi I'm trying to charge a user using stripe in Django. The problem I'm facing is that, when I printed my stripeToken value, in the console it is printing "None". That's the reason why I am getting "Invalid Parameters Error". I commented all the errors, just to see the real error, and it was: InvalidRequestError at /payment/stripe/ Request req_5yo1v0CwbYGjTV: Must provide source or customer. Why is my stripeToken value coming None? Can anyone please solve this problem? My Views.py: class PaymentView(View): def get(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) token = self.request.POST.get('stripeToken') print(cart) print(order) print(token) return render(self.request, "orders/payment.html") def post(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) amount = int(order.final_total * 100) # to convert it into cents token = self.request.POST.get('stripeToken') try: # user_stripe = self.request.user.userstripe.stripe_id # customer = stripe.Customer.retrieve(user_stripe) charge = stripe.Charge.create( amount= amount, currency="usd", # card= card, # customer = customer, source = token, description = "Charge for %s" %(self.request.user.username) ) # card = customer.cards.create(card=token) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = int(order.final_total()) payment.save() order.payment = payment order.save() messages.success(self.request, "Your order was successful") return redirect("/") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError … -
How to change the heading of the filter section in change list page of Django admin
I'm working on Django and I want to change the heading of the filter section which is marked in the pic: And my admin file looks like this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So can we change the heading of the filter section without changing any thing else?? Thanks in advance!! -
Django serializers vs values method
What is the difference in using Model_Name.Objects.values().get() and serializers to get the data not in the form of model objects? -
How to add help text for many to many field in Django?
I created this simple model, but need your help to add a help_text: class FormModel(models.Model): fullname = models.CharField(max_length=150) slug = models.SlugField(max_length=255) ... interests = models.ManyToManyField(Interests) I tried several ways, there is a similar question in SO. It didn't work either. Thanks -
NoReverseMatch at /accounts/login/ Reverse for '' not found. '' is not a valid view function or pattern name
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joga\Desktop\project\djangonautic\accounts\views.py", line 24, in login_view return redirect(request.POST.get('next')) File "C:\Users\Joga\testenv\lib\site-packages\django\shortcuts.py", line 41, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\Users\Joga\testenv\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\Users\Joga\testenv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Joga\testenv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /accounts/login/ Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. after reading the traceback im pretty sure the errors at : return redirect(request.POST.get('next')) but i cant figure out whats wrong -
ERROR: Could not find a version that satisfies the requirement django==1.7b1 (from tictactoe) (from versions: 1.1.3 (...) 3.0.5 )
I'm trying to install the "tictactoe" module from pygame (I've already intall pygame), but when I run: pip3 install tictactoe I get an ERROR message (the one from the Title): ERROR: Could not find a version that satisfies the requirement django==1.7b1 (from tictactoe) (from versions: 1.1.3 (...) 3.0.5 ) And also: ERROR: No matching distribution found for django==1.7b1 (from tictactoe) Any idea on what might be the problem? I'm new in programming so it's probably something silly... -
Django sum total price from table items and table transaction
I have two tables, items and transaction, how do i calculate the total price, and displaying the total price in templates class Items(models.Model): items_name = models.CharField(max_length=50) price = models.PositiveIntegerField() def __str__(self): return self.items_name class Transaction (models.Model): items = models.ForeignKey(Items, on_delete=models.CASCADE) qty = models.PositiveIntegerField() def total_price(self): total = self.qty * self.items.price return total total_price = models.PositiveIntegerField(total_price) Here is the View def transaction(request): transactions=Transaction.objects.all() context={'transactions':transactionss} return render(request,'app/transaction.html',context) here is my template {% for transaction in transactions %} <tr> <td>{{transaction.item}}</td> <td>{{transaction.qty}}</td> <td><a class='btn btn-sm btn-info' href="#"> Update</a></td> <td><a class='btn btn-sm btn-danger' href="# ">Delete</a></td> </tr> {% endfor %} <tr><td> {{total_price}} </td></tr> I want to display the full total_price of all transactions, for example item 1 with price 100 * quantity 2 and item 2 with price 200 * quantity 3 . then the total price would be 200 + 600 = 800. I want to display the 800 in the template. -
Django-select2 HeavySelect2MultipleWidget -> Dynamic Choices
What is the correct way to use HeavySelect2MultipleWidget with Dynamic choices ?? I am using Django-select2 HeavySelect2MultipleWidget to fetch and select data by using ajax search from table... I referred Django-select2 documentation and testapp in their github repo, their documentation is not much helpful but in their testapp, they have very basic example. they are feeding choices from custom static list, which is not from database and also not dynamic. it loads everything to choices. if I use combination of ModelMultipleChoiceField and HeavySelect2MultipleWidget and if I pass queryset of respective model then it loads entire table in choices... which I dont want... my existing code looks like this: class CustReqForm(forms.Form): customer = forms.ModelMultipleChoiceField(widget=HeavySelect2MultipleWidget(data_view='customer_search',), queryset=Customer.objects.filter(channel='34342').all() ) I have a huge data in my table. though I filtered in my query, still it loads 100K unique records... Please advice the right method to implement this...