Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Top 10 Sold Products with Django queryset order_by "external value"
I am trying to get top 10 sold products from my models. Models are: Products SoldProducts (list of products included after sold): class SOldProduct(models.Model): I have got a list with Product PK and a Sum of sold products with: best_seller_products = SoldProduct.objects.filter(product__in=products, order__in=orders).values( 'product__pk',).annotate(qty=Sum('quantity')).order_by('-qty')[:6] as result of this queryset: <QuerySet [{'product__pk': 5, 'qty': 22}, {'product__pk': 6, 'qty': 6}]> So I made a two lists. One with the product_pk and other with qty. With the product_pk a got a list off the products with this query: best_seller_products = products.filter(pk__in=list_best_seller_products_pk) The problem i would like to solve is: How sort this products list that i got with product_pk with the qty list. I would mostly prefer to use query instead of creating a "sold" field into Product model. I really apreciate any help or directions on how to do it! Thank you very much -
How do I display the next element of a list in a for loop inside the template
views.py def cust_ledger(request, pk): quant_bal = 0 amt_bal = 0 sb_q = 0 rb_q = 0 sr_q = 0 main = [] for tx in transactions: if tx.tt == 'SB': # Individual tx sb_q = sb_q + tx.quantity main.append(sb_q) # Total quant_bal = quant_bal + tx.quantity amt_bal = amt_bal + tx.amount elif tx.tt == 'RB': rb_q = sb_q - tx.quantity main.append(rb_q) # Total quant_bal = quant_bal - tx.quantity amt_bal = amt_bal - tx.amount else: sr_q = sb_q - tx.quantity main.append(sr_q) # Total quant_bal = quant_bal - tx.quantity amt_bal = amt_bal - tx.amount context = {'transactions':transactions, 'cust':cust, 'quant_bal':quant_bal, 'amt_bal':amt_bal, 'sb_q':sb_q, 'rb_q':rb_q, 'sr_q':sr_q, 'main':main} return render(request, 'customer/ledger.html', context) HTML template {% extends 'base2.html' %} {% load widget_tweaks %} {% load static%} {% block css %} <link rel="stylesheet" href="{% static 'utility.css' %}"> <link rel="stylesheet" href="{% static 'customer/ledger.css' %}"> {% endblock css %} {% block unique %} <div class="header"> <a class="link inv" href="{% url 'inventory' %}"> Inventory</a> <a class="link hist" href="{% url 'cust_board' %}"> Dashboard</a> <h1>Dinar Company</h1> <a class="link home" href="{% url 'cust-l' %}">Back</a> </div> {% endblock unique %} {% block content %} <div class="title_div"> <h1 class="title">{{cust.name}}'s Ledger</h1> </div> <h2 class="date heading">Date</h2> <h2 class="tt heading">TT</h2> <h2 class="id heading">ID</h2> <h2 class="voucher heading">Voucher</h2> <h2 class="debit_q heading">Debit … -
Django Aggregate Models on Field
Hello Im trying to aggregate and Output Data from my Models to my HTML Page Models.py from django.db import models from django.contrib import admin class ClientDB(models.Model): Hostname= models.CharField(max_length=50,primary_key=True) User= models.CharField(max_length=100) class VULDB(models.Model): VID=models.IntegerField(primary_key=True) CVELIST=models.CharField(max_length=50) CVSScore=models.FloatField(max_length=5) Serverity=models.CharField(max_length=25) Title=models.CharField(max_length=1000) Summary=models.CharField(max_length=1000) class ClientVULDB(models.Model): Hostname= models.ForeignKey(ClientDB, on_delete=models.CASCADE) VID=models.ForeignKey(VULDB, on_delete=models.CASCADE) Path=models.CharField(max_length=1000) isActive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['Hostname', 'VID'], name='unique_migration_host_combination' # legt ) ] I would like to create a view that Output and aggregate Data in the Model to my HTML Template. I need help how I can aggregate (and put it in an Queryset?) the data like in the Screenshot I tried it with prefetch_related and querysets but couldent get the Data to aggregate -
ValueError: The view app.views.plus_cart didn't return an HttpResponse object. It returned None instead
views.py from django.db.models import Count from django.shortcuts import render,redirect from django.http import JsonResponse from django.views import View from . models import Product, Cart, Customer from . forms import CustomerRegistrationFrom, CustomerProfileForm from django.contrib import messages from django.db.models import Q def show_cart(request): user = request.user cart = Cart.objects.filter(user=user) amount = 0 for p in cart: value =p.quantity * p.product.discounted_price amount = amount + value totalamount = amount + 40 return render(request,'app/addtocart.html',locals()) def plus_cart(request): if request.method == 'Get': prod_id=request.Get['prod_id'] c = Cart.objects.get(Q(product=prod_id) & Q (user=request.user)) c.quantity += 1 c.save() user = request.user cart = Cart.objects.filter(user=user) amount = 0 for p in cart: value = p.quantity * p.product.discounted_price amount = amount + value totalamount = amount + 40 print(prod_id) data={ 'quantity':c.quantity, 'amount':amount, 'totalamount':totalamount } return JsonResponse(data) script.py $('.plus-cart').click(function(){ var id=$(this).attr("pid").toString(); var eml=this.parentNode.children[2] $.ajax({ type:"GET", url:"/pluscart", data:{ prod_id:id }, success:function(data){ console.log("data = ",data) eml.innerText=data.quantity document.getElementById("amount").innerText=data.amount document.getElementById("totalamount").innerText=data.totalamount } }) }) Internal Server Error: /pluscart/ Traceback (most recent call last): File "C:\Users\SIRI\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\SIRI\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\base.py", line 204, in _get_response self.check_response(response, callback) File "C:\Users\SIRI\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\base.py", line 332, in check_response raise ValueError( ValueError: The view app.views.plus_cart didn't return an HttpResponse object. It returned None instead. [06/May/2023 18:23:59] "GET /pluscart/?prod_id=1 HTTP/1.1" 500 66757 -
How to send a list of objects in soap request with django?
I want to send a request containinga list of objects to soap, using django; i tried as below: data = [{"title": "title1", "pic": "pic1"}, {"title": "title2", "pic": "pic2"}, .... ] wsdl = 'http://test.com/Test/TEST.asmx?wsdl' tac_data = { 'user': {'UserName': 'username', 'Pass': 'password'}, 'request': f"""{data}""" } client = Client(wsdl=wsdl) response = client.service.AddDocLossFile(**tac_data) but I gut the following error: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type \'ViewModels.Dto.DocLossFile\' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.\nTo fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\nPath \'\', line 1, position 1.' does anyone have a solution? -
How to untangle the Django URLs in my project?
I am a beginner in django. Made a project and app by following YouTube Videos and django documentation. I have made an HTML page for sign in, sign up and business sign up repectively. project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), #website.com/admin/ path('', include('signin.urls')), #website.com/ path('home/', include('signin.urls')), #website.com/home/ path('signin/', include('signin.urls')), #website.com/signin/ path('signup/', include('signin.urls')), #website.com/signup/ path('business_signup/', include('signin.urls')), #website.com/business_signup/ ] signin/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.default, name='signin'), path('home/', views.default, name='home'), path('signin/', views.default, name='signin'), path('signup/', views.signup, name='signup'), path('business_signup/', views.business_signup, name='business_signup'), ] I have made for empty path, home and signin redirect to sign in page. Code is like below: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def default(request): return render(request, "default.htm") In the html page: <p>New here? <a href="/signup">Create an account</a></p> All the urls are working but the problem is when i use the {% url 'name' %} in the href of the HTML page like <p>New here? <a href="{% url 'signup' %}">Create an account</a></p> All the redirections are changed to http://127.0.0.1:8000/business_signup/signin/ http://127.0.0.1:8000/business_signup/signup/ http://127.0.0.1:8000/business_signup/business_signup/ I wanted to redirect {% url 'name' %} like http://127.0.0.1:8000/signin/ and similar. Any solutions? -
Django how to mock access token
I have the following code in my testcase. Whenever I'm running the testcase, a new token is generated which is draining my quota. So, how do I mock the token validation? Any help is much appreciated. Thanks Testcase from apps.common.helpers import get_auth0_access_token class TestDatasetListTestCase(APITestCase): def setUp(self): access_token = get_auth0_access_token() self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}") payload = {"label": "new_label"} response = self.client.post(self.url, payload, format="multipart") helpers.py def generate_new_auth0_token() options = { "url": f"https://{auth0_domain}/oauth/token", "headers": {"cache-control": "no-cache", "content-type": "application/json"}, "json": {"audience": audience, "grant_type": grant_type, "client_id": client_id, "client_secret": client_secret}, } res = requests.post(**options) return res.json() or Exception(res.text) -
__fake__.StartUp.DoesNotExist: StartUp matching query does not exist
Applying organizer.0005_newslink_data...Traceback (most recent call last): File "E:\Django Unleashed\suorganizer\manage.py", line 22, in main() File "E:\Django Unleashed\suorganizer\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Django Unleashed\django-unleashed\lib\site- packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "E:\Django Unleashed\django-unleashed\lib\site- packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "E:\Django Unleashed\django-unleashed\lib\site- packages\django\core\management\commands\migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "E:\Django Unleashed\django-unleashed\lib\site- packages\django\db\migrations\migration.py", line 130, in apply operation.database_forwards( File "E:\Django Unleashed\django-unleashed\lib\site- packages\django\db\migrations\operations\special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "E:\Django Unleashed\suorganizer\organizer\migrations\0005_newslink_data.py", line 37, in add_newslink_data startup = StartUp.objects.get( File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\query.py", line 650, in get raise self.model.DoesNotExist( __fake__.StartUp.DoesNotExist: StartUp matching query does not exist. -
How can I display only selected options of a fild type ManyToMany - django
Good morning, I need to display the values selected in the manytomany field named "sfide" in a table I will build with html, how can I do it? thanks I also attach the image of the class "Profilo" with the ManyToMany field "sfide" -
'Builds' Warning on deploying Django project on Vercel from Github
I am currently trying to deploy my Django project from my Github account on the Vercel app. But it is showing the following error- enter image description here Code in the vercel.json file is- { "builds": [{ "src": "blog/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }], "routes": [ { "src": "/(.*)", "dest": "blog/wsgi.py" } ] } Name of the django project is blog. Please help me resolve this problem. Thank you. I tried adding different pieces of code in the vercel.json file as told on different websites but nothing is working. I also ticked the ovveride option of environment variables section which comes when we deploy on vercel but that too is not working. -
From website (javascript) to program (python), how?
I created a couple python tools that I run locally on my computer. Things like programs that automatically export and format transcripts from youtube videos, small scrapers for some social media platforms and programs that automate websites. They're all in terminal format, no GUI or complicated commands. I want to make a website for all of these tools, but I have no idea how to let an user operate these programs through my website and in return get back what the program outputs. For example: Python script where you input a youtube video url, the script takes the url, gets the video id, takes the english transcript of what's being said in that video then it outputs to the user as a nice formatted string. In a website, the user would input the video url in a text box, they'd wait for the program to run and get back the formatted string in another text box. Is there any way to do this without writing the whole program in javascript? -
TypeError: object ChatConsumer can't be used in 'await' expression WebSocket DISCONNECT /chat/dsd [127.0.0.1:13820]
consumer.py: `import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.group_name = f'room_{self.room_name}' # self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() async_to_sync(self.channel_layer.group_send)( f'room_{self.room_name}', { 'value':json.dumps({'status':'online'}) } ) data = { 'type':'connected' } self.send(text_data=json.dumps( { 'payload':'connected', } )) def receive(self,text_data): data = json.loads(text_data) # message = text_data_json['message'] payload = { 'message': data.get('message'), 'sender': data.get('sender') } async_to_sync(self.channel_layer.group_send)( f'room_{self.room_name}', { 'type':'send_message', 'value':json.dumps(payload) } ) def disconnect(self, close_code): pass def send_message(self, text_data): data = text_data.get('value') self.send(text_data = json.dumps( { 'payload':data } )) ` I am making chatroom application, in which on the landing you enter room code and username, and you are redirected to the chatroom page. In the chat room you have an input field to send message, but when I am trying to send a message it shows in the console "WebSocket connection to 'ws://127.0.0.1:8000/chat/dsd' failed" the 'dsd' in the url is the room code. -
django.db.utils.OperationalErrror: no such tabel: django_site
Traceback (most recent call last): File "", line 1, in File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\query.py", line 621, in count return self.query.get_count(using=self.db) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\sql\query.py", line 559, in get_count return obj.get_aggregation(using, ["__count"])["__count"] File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\sql\query.py", line 544, in get_aggregation result = compiler.execute_sql(SINGLE) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\utils.py", line 102, in execute return super().execute(sql, params) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "E:\Django Unleashed\django-unleashed\lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: django_site I am trying Site.objects.count() and getting this OperationalError : no such table: django_site -
Django object of type fraction is not json serializable
from django.http import JsonResponse, HttpResponse from django.shortcuts import render from math import sqrt from fractions import Fraction def index(request): return render(request, 'home/index.html', {}) def multiplication(request): return render(request, 'multiplication/multiplication.html', {}) def compute(request): a = int(request.POST.get("a")) b = int(request.POST.get("b")) c = int(request.POST.get("c")) det = b*b-4*a*c rdet = sqrt(det) x1= (-b-rdet)/(2*a) x2= (-b+rdet)/(2*a) x3= Fraction(15, 45) return JsonResponse({"op_result": det, "op_result2": x1, "op_result3": x2, "op_result4": 2*a, "op_result5": -b, "op_result6": c,"op_result7": x3}) in my view.py, I tried to send back to my html, the results of the function fractions through the var x3 x3= Fraction(15, 45) and sent the result with JsonResponse. But I have an error message : object of type fraction is not json serializable I do not understand where is the mistake. Thank you for your help -
What is the correct way to add static file version in Django?
I am making a web app using Django. Currently, I have created a versions.py file in myproject/myproject directory. Using the template tag, I am getting the version of the static file which is added in versions.py file. But every time I changed the css and js file, manually I have to changed the version of the respective file. versions.py # css versions base_css = 1.1 header_css = 1.1 footer_css = 1.1 . . . # js version base_js = 1.1 . . . Template Tag from myproject import versions register = template.Library() @register.simple_tag def home_base_css(): return versions.home_base_css In Template {% load static %} {% load template_tag_file_name %} <link href="{% static 'css/home/base.css' %}?v={% home_base_css %}" rel="stylesheet" type="text/css"> Is there any better way to do it? -
Issue with Django migration: The field oauth2_provider.AccessToken.application was declared with a lazy reference
I am encountering an issue with Django migration while using the django-oauth-toolkit library in my Django project. The error message states that the field oauth2_provider.AccessToken.application was declared with a lazy reference to 'apis.customapplicationmodel', but the app 'apis' is not installed. Here is some information about my project setup: Django version: 4.0.6 django-oauth-toolkit version: 2.2.0 Project Structure: accs cms apis migrations models __init.py__ custom_application.py static templates views __init.py__ apps.py urls.py owner sonline tnt custom_application.py from django.db import models from oauth2_provider.models import AbstractApplication from tnt.models import TntModel class CustomApplicationModel(AbstractApplication): tnt = models.ForeignKey(TntModel, on_delete=models.CASCADE) class Meta(AbstractApplication.Meta): pass settings.py, which is in sonline directory INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'cms', 'accs', 'tnt', 'owner', 'rest_framework', 'background_task', 'apis', 'oauth2_provider', ] # OAUTH2 settings OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': 604800 } OAUTH2_PROVIDER_APPLICATION_MODEL = 'apis.CustomApplicationModel' When I run the following commands, it gives me the below error: (venv) PS D:\s> python .\manage.py makemigrations Migrations for 'apis': apis\migrations\0001_initial.py - Create model CustomApplicationModel (venv) PS D:\s> python .\manage.py migrate Operations to perform: Apply all migrations: accs, admin, auth, background_task, cms, contenttypes, oauth2_provider, apis, sessions, tnt Traceback (most recent call last): File "D:\s\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\venv\lib\site-packages\django\core\management\__init__.py", … -
Django daterangefield in a form
I have a model looking like this: models.py class CommissionElection(models.Model): electable_time = DateRangeField() And my form looks like this: forms.py class CreateCommissionElection(forms.ModelForm): class Meta: model = CommissionElection fields = ['electable_time',] Right now the electable time displays like this: What widget is needed to make the fields datefields instead of charfields, so you can pick a date out of a calendar instead of writing it out? -
Excluding rows from a model depending on Boolean values in Django
I have a post model and user model The user has a profile page that contains their info and their posts. The Post model is like this: # models.py class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=False) title = models.CharField(max_length=255, verbose_name="Post Title") slug = models.SlugField(null=True, blank=True, unique=False) content = QuillField() topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True, blank=True) is_published = models.BooleanField(null=False, default=True) likes = models.ManyToManyField(User, related_name="post_likes", blank=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug is None: self.slug = slugify(self. Title) super().save(*args, **kwargs) # views.py class UserView(TemplateView): def get(self, request, username=None): if username == None: user = User.objects.get(username=request.user.username) else: user = User.objects.get(username=username) posts = Post.objects.filter(owner__username=username).all() context = {"user": user, "posts": posts} return render(request, "base/user_view.html", context) The user can create a post but can save it as a draft or published it. What I want to achieve is that the user goes to their profile they can see the all their posts that have been published and the ones that have been saved as a draft, but other users can only see the published posts of that user. How can I achieve this in the profile template? or can it be done in the views.py? -
inline-formfactory will update, but not create new items
I have created a recipe app where I use an inline-formfactory to add ingredients to it. For some reason i can edit and add ingredients through a view just fine when there is one ingredient added through the admin panel of my model. If i try to create a new recipe and add ingredients they will not save to the database. Where did I make a mistake? My models and forms look like this: class DrinkRecipe(models.Model): drink_tag = models.ManyToManyField(Tag) drink_tag_rum = models.ForeignKey(Bottle, on_delete=models.SET_NULL, null=True) drink_tag_taste = models.ManyToManyField(TagTaste) name = models.CharField(max_length=255, blank=False, unique=True) drink_description = HTMLField() drink_method = HTMLField() drink_garnish = HTMLField() drink_image = ResizedImageField(size=[1000,600],upload_to=image_upload_handler) drink_active = models.BooleanField(default=True) slug = models.SlugField(unique=True, blank=True, null=True) class Ingredient(models.Model): drink = models.ForeignKey(DrinkRecipe, on_delete=models.CASCADE) ingredient_rhum = models.ForeignKey(Bottle, on_delete=models.CASCADE, null=True, blank=True) ingredient_name = models.CharField(max_length=255, blank=True) ingredient_amount = models.DecimalField(decimal_places=1,max_digits=5, validators=[MinValueValidator(0.01)]) my forms like this: class drinkForm(forms.ModelForm): error_css_class = 'error-field' required_css_class = 'required-field' class Meta: model = DrinkRecipe fields = ['drink_tag','drink_tag_rum','drink_tag_taste','name','drink_description','drink_method', 'drink_garnish','drink_image','drink_active'] labels = { 'drink_tag' : 'Occasion', 'drink_tag_rum' : 'Rhum', 'drink_tag_taste' : 'Taste', } widgets = { 'drink_tag' : forms.SelectMultiple(), 'drink_tag_taste' : forms.SelectMultiple(), } help_texts = { 'drink_tag' : 'You can select multiple', 'drink_tag_taste' : 'You can select multiple', 'drink_tag_rum' : 'Please select the core Rhum for this … -
Aggregate sum of values from Django JSONField
Consider I have a simple model setup with JSONField from django.db import models import random def simple_json_callable(): return {"amount": random.randint(1, 100)} def nested_json_callable(): data = { "l1": { "l2": { "l3": { "amount": random.randint(1, 100) } } } } return data class Foo(models.Model): simple_json = models.JSONField(default=simple_json_callable) nested_json = models.JSONField(default=nested_json_callable) I want to get the sum of amount key from both simple_json and nested_json fields. I tried the following queries Case 1: Annotate and then aggregate result = Foo.objects.annotate( simple_json_amount=Cast('simple_json__amount', output_field=models.IntegerField()), nested_json_amount=Cast('nested_json__l1__l2__l3__amount', output_field=models.IntegerField()), ).aggregate( simple_json_total=models.Sum('simple_json_amount'), nested_json_total=models.Sum('nested_json_amount'), ) Case 2: Aggregate result = Foo.objects.aggregate( simple_json_total=models.Sum(Cast('simple_json__amount', output_field=models.IntegerField())), nested_json_total=models.Sum(Cast('nested_json__l1__l2__l3__amount', output_field=models.IntegerField())), ) In both cases, I got the error django.db.utils.DataError: cannot cast jsonb object to type integer Question What is the proper way to aggregate sum of values from a JSONField in Django? Version Django 3.1.X Python 3.9.X -
How to send information to server from django
My problem is that I have a text field that I want to have, when submitted, sent information to the django server. First am trying to accomplish this as you can see so I haven't built anything more to do this, but my idea is that on clicking the button, I append a value on a list through which I use this. { % for value in list %} { % value % } { % endfor % } I am tryingg, in summary to make this a working ChatGPT application that can successfully send data. The source code is avalible at https://gist.github.com/s0urce-c0de/fce620fdb61c0b9d30e1ac5361cac039. -
Django Server Error (500) when I set Debug - False on True it is working fine
I developed a eccomerce site locally. But now problem is when i set debug false it's return server error 500. I can't find solution for this problem. also same problem production env. Here is my setting file. I am already run manage.py collectstatic properly. Anyone can help me... import os import django_heroku from decouple import config from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY', default='django-insecure-d-2#wapr8ub&e@3+18ed5pjka0v-$clft(jr!cfs!h$lfc*pq%') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) # DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'mptt', 'shop', 'users', 'basket', 'orders', 'payment', 'contacts', 'blog', 'recruitment', 'address', 'settings', ] 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', "whitenoise.middleware.WhiteNoiseMiddleware", ] ROOT_URLCONF = 'app.urls' MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'shop.views.categories', 'settings.views.options', 'basket.context_processors.basket' ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES … -
Work Breakdown Structure gntt chart django
How can I create wbs gantt chart in django? I expect the wbs management gantt chart to be displayed on the web -
The For Loop in function view only sends the last iteration data as context to template
This is my view def cust_ledger(request, pk): cust = Customer.objects.get(id = pk) dbs = [Issue, Receive, SalesReturn] transactions = sorted( [m for db in dbs for m in db.objects.filter(customer=cust).order_by('date_time')], key=attrgetter('date_time') ) quant_bal = 0 amt_bal = 0 sb_q = 0 rb_q = 0 sr_q = 0 for tx in transactions: if tx.tt == 'SB': # Individual tx sb_q = sb_q + tx.quantity # Total quant_bal = quant_bal + tx.quantity amt_bal = amt_bal + tx.amount elif tx.tt == 'RB': rb_q = sb_q - tx.quantity # Total quant_bal = quant_bal - tx.quantity amt_bal = amt_bal - tx.amount else: sr_q = sb_q - tx.quantity # Total quant_bal = quant_bal - tx.quantity amt_bal = amt_bal - tx.amount context = {'transactions':transactions, 'cust':cust, 'quant_bal':quant_bal, 'amt_bal':amt_bal, 'sb_q':sb_q, 'rb_q':rb_q, 'sr_q':sr_q} return render(request, 'customer/ledger.html', context) HTML template {% extends 'base2.html' %} {% load widget_tweaks %} {% load static%} {% block css %} <link rel="stylesheet" href="{% static 'utility.css' %}"> <link rel="stylesheet" href="{% static 'customer/ledger.css' %}"> {% endblock css %} {% block unique %} <div class="header"> <a class="link inv" href="{% url 'inventory' %}"> Inventory</a> <a class="link hist" href="{% url 'cust_board' %}"> Dashboard</a> <h1>Dinar Company</h1> <a class="link home" href="{% url 'cust-l' %}">Back</a> </div> {% endblock unique %} {% block content %} <div … -
Django 'function' object has no attribute 'objects' - django.contrib.auth.models
I cannot insert value in the watchlist table because the user foreign key problem. models.py from django.db import models from django.contrib.auth.models import User class watchlist(models.Model): watchlist_id = models.AutoField(primary_key=True, max_length=10) stock_add_time = models.DateTimeField(auto_now=True) stock = models.ForeignKey(stock, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) objects = models.Manager() def __str__(self): return self.stock_add_time class Meta: db_table = "watchlist" verbose_name = 'watchlist name' views.py from django.contrib.auth.models import User from .models import watchlist @login_required(login_url='login') def watchlist(request): user = User.objects.filter(id=request.user) stock_id = stock.objects.get(stock_id='1') watchlist.objects.create(stock=stock_id, user=user) return render(request, 'watchlist.html', {}) I also try many time but still cannot solve it. I hope someone can help or give me any suggestion.