Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Server Error (500) After Django Deployment
This error when I ran "heroku logs --tail" Continuation of the error Here is the Github repo link: https://github.com/rhedwan/HNGi8XI4GStage2to3 -
How to get String value instead of number in foreign key field in django?
Here's my models class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot class jenkinsHistory(models.Model): robotName = models.ForeignKey(Robot, on_delete=models.CASCADE, blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100,blank=True) jenkinsBuildStatus = models.CharField(max_length=200,blank=True) errorMsg = models.CharField(max_length=500,blank=True) Param = models.CharField(max_length=500,blank=True, null=True) def __str__(self): return self.robotName I have assign data in jenkinsHistory table from Robot table. here's the code that how i assign the data def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) hist = jenkinsHistory(robotName= pi,jenkinsBuildStatus='Jenkins-Running') hist.save() now i want to show that data in a table in my UI. so that i have written this view def Robot_History(Request,id): fm = list(jenkinsHistory.objects.values('id','robotName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param').filter(robotName=id)) print("hello",fm) rob = Robot.objects.all() return render(Request, 'hello/robotHistory.html',{'jenkinsHistory': fm,'robot': rob}) and here's my html {% for hist in jenkinsHistory %} <tbody> <tr> <td>{{hist.id}}</td> <td>{{hist.robotName}}</td> <td>{{hist.jenkinsBuildNumber}}</td> <td>{{hist.jenkinsBuildStatus}}</td> <td>{{hist.errorMsg}}</td> <td>{{hist.Param}}</td> </tr> </tbody> {% endfor %} But when i got the data the foreign key field coming as a id not string but in my django admin it is coming as a string only how to solve that issue? -
NoReverseMatch at /account/login/ (Trying to use Class based authentication views)
I am trying to use Django's class based authentication views and am getting the following error when attempting to access the login view: NoReverseMatch at /account/login/ Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Error during template rendering In template /Users/justin/Desktop/Programming/Python/django_book/social/website/account/templates/base.html, error at line 0 All authentication templates are stored at templates/account/registration/ and dashboard.html is stored at account/templates/account/, here is the code: urls.py: from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.dashboard, name = 'dashboard'), path('login/', auth_views.LoginView.as_view(), name = 'login'), path('logout/', auth_views.LogoutView.as_view(), name = 'logout'), ] login.html: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in. If you don't have an account <a href="{% url "register" %}">register here</a></p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> </div> {% endblock %} base.html: {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title%}{% … -
jquery.formset.js custom buttons and positions
how can i change the buttons with jquery.formset.js? I would like to put it in the click event for the blue one to create a new empty object to be compiled, while for the red one the elimination of the object. Using those I only get links and if I put the classes I create the button but I can't place it where I want. Can someone help me? image example -
Font Awesome icons don't display in dropdown menu from <select> <option> in Firefox
I'm creating an anime list using Django. You can see this list in the 2-columns table. You can add titles and next to them you can set the status by selecting one of Font Awesome icons in the dropdown menu created by using HTML tags select and option. The problem is when I want to select one of the icons I can't see what icon I choose. Instead of it, there are some squares. The problem appears on Firefox but on Chrome it doesn't exist. Besides the dropdown menu, icons display normally. Part of index.html code: <h2>Legenda:</h2> <ul> <li>Obejrzane/przeczytane: <i class="fas fa-check"></i></li> <li>Nieobejrzane/nieprzeczytane: <i class="fas fa-times"></i></li> <li>Do obejrzenia/przeczytania: <i class="fas fa-flag"></i></li> <li>W trakcie oglądania/czytania: <i class="fas fa-circle"></i></li> </ul> <a href="{% url 'jam_app:new_title' %}">+ Dodaj tytuł</a> <table> <th>Tytuł</th> <th>Status</th> {% for title in titles %} <tr> <td> <a href="{% url 'jam_app:detail' title.id %}">{{ title }}</a> </td> <td> <form action="jam_app:index"> <select class="fa"> <option value="fas fa-check">&#xf00c</option> <option value="fas fa-times">&#xf00d</option> <option value="fas fa-flag">&#xf024</option> <option value="fas fa-circle">&#xf111</option> </select> </form> </td> </tr> {% endfor %} </table> I've found that maybe I should do something with Access-Control-Allow-Origin. I tried to add some code like here in the first answer or download the add-on 'Allow CORS: Access-Control-Allow-Origin' but … -
How can I allow users to update details? I am getting NOT NULL constraint failed
from django.contrib.auth.signals import user_logged_in from django.shortcuts import redirect, render from django.contrib.auth.models import User,auth from django.contrib.auth import authenticate,logout from django.contrib import messages from django.contrib.auth.decorators import login_required @login_required def update(request): if request.method=="POST": firstname=request.POST.get('first_name') lastname=request.POST.get('last_name') """email=request.POST.get('email') username=request.POST.get('username')""" #password=request.POST.get('password') cur=request.user print(cur) print('i came till here') user=User.objects.filter(username=cur).update(first_name=firstname,last_name=lastname) user.save() print('i came here') return redirect('profile') else: print('i came to elses block') redirect('index') I want users to update their details but I am getting error when I try to submit "Not null constraint" The problem is only in the update function. Any help will be appreciated. -
2013, 'Lost connection to MySQL server during query' in Django While executing query in MySQL
2013, Lost Connection to MySQL query Getting error while executing query in MySQL. This error is coming while executing MySQL queries from Django framework. Please suggest ways to solve the problem. Already tried with CONN_MAX_AGE property. -
CHANGE VALUE OF FIELD WHEN SUBMITTING ANOTHER FOEM THAT CONTAINS THIS FIELD AS PRIMARY KEY DJANGO
I HAVE TWO CLASSES THE FIRST ONE (CoupeLithologique) HAS A FIELD (ref_coupe) AS PRIMARY KEY THE SECOND ONE (Sondage)HAS IT AS FOREIGN KEY (coupe) I WANT TO CHANGE THE VALUE OF FOREIGN KEY (coupe)WHEN SUBMITTING THE FORM (CoupeLithologiqueModify)OF THE FIRST CLASS (CoupeLithologique) AUTOMATICALLY. ***Models.py:*** class CoupeLithologique(models.Model): ref_coupe = models.CharField(max_length=10, blank=True, null=True) machine_coupe_lithologique = models.CharField(max_length=10, blank=True, null=True) technicien = models.ForeignKey('Technicien', models.DO_NOTHING, blank=True, null=True) class Sondage(models.Model): ref_sondage = models.CharField(max_length=10, blank=True, null=True) profondeur_total_sondage = models.CharField(max_length=10,blank=True, null=True) niveau_piezometrique_sondage = models.CharField(max_length=40, blank=True, null=True) observation_sondage = models.CharField(max_length=30, blank=True, null=True) log_strati = models.ImageField(upload_to='img/bsd_images/',blank=True, null=True) profil_pressio_sondage = models.ImageField(upload_to='img/bsd_images/',blank=True, null=True) projet = models.ForeignKey(Projet, models.DO_NOTHING, related_name='projet',blank=True, null=True) coupe = models.ForeignKey(CoupeLithologique, models.DO_NOTHING,related_name='coupe' ,blank=True, null=True) section = models.ForeignKey(Sections, models.DO_NOTHING, related_name='section',blank=True, null=True) geom = models.PointField(geography=True, default=Point(0.0, 0.0)) class Meta: managed = True db_table = 'sondage' ***Views.py :*** def ajouter_coupe(request): if request.method == "POST": form = CoupeLithologiqueForm(request.POST) if form.is_valid(): form.save() return redirect('/Coupe//Afficher') else: form = CoupeLithologiqueForm() return render(request, 'Ajouter_Coupe.html', {'form': form,'techniciens':Technicien.objects.all()}) ***HTML:*** <div id="form_c" style="width:450px;display:none;"> <h2 style="text-align:center; color: rgba(255,255,255, 0.8) !important;">Modifier Sondage</h2><hr> <form action="{%url 'app_technicien:Ajouter_c'%}" method="POST"> {%csrf_token%} <tr><th><label for="id_ref_coupe">Ref coupe:</label></th><td><input type="text" name="ref_coupe" maxlength="10" id="id_ref_coupe"></td></tr> <tr><th><label for="id_machine_coupe_lithologique">Machine coupe lithologique:</label></th><td><input type="text" name="machine_coupe_lithologique" maxlength="10" id="id_machine_coupe_lithologique"></td></tr> <tr><th><label for="id_technicien">Operateur:</label></th><td><select name="technicien" id="id_technicien"> {% for tech in techniciens %} <option value="{{tech.pk}}" >{{tech.nom_technicien}}</option> {%endfor%} </select></td></tr> <button id="enr" type="submit" name="login" class="btn btn-fill btn-primary" … -
Get the specific details of selected item
I would like to show the selected part's Standard pack value into a non-editable box. I have two models Part (also foreign key in DeliveryIns table) and DeliveryIns and during creating a deliveryins user has to choose a Part name. So after choosing the Part name in DeliveryIns form, I would like to show the Standard pack value of that selected/chosen Part into a box. models.py class Part(models.Model): partno = models.CharField(max_length=50) partname = models.CharField(max_length=50) standardpack = models.PositiveIntegerField(default= 0) def __str__(self): return self.partname views.py def create_deliveryins(request): from django import forms form = DeliveryInsForm() forms = DeliveryInsForm(request.method == 'POST') if forms.is_valid(): di_id = forms.cleaned_data['di_id'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] supplier = forms.cleaned_data['supplier'] q = Part.objects.get(id=part.id) deliveryins = DeliveryIns.objects.create( di_id=di_id, product=product, part=part, supplier=supplier, ) return redirect('dins-list') context = { 'form': form } return render(request, 'store/addDins.html', context) Can anyone help to how to pass the Standard pack value from Parts table after selecting a Parts name in DeliveryIns form? -
Django model's OneToOne relationship - AttributeError: object has no attribute
please help ! I am building a simple maintenance ticketing system. model Ticket captures the initial data. model UpdateTicket enables a responder to update details on the Ticket as well as including additional field for comment and a timestamp. UpdatedTicket has a OneToOne relationship with Ticket but I get an AttributeError: 'Ticket' object has no attribute when I try to access the associated data. (even though in the site admin section the relationships are working fine) Here are the models from django.db import models from django.utils import timezone from django.urls import reverse from members.models import Member class Ticket(models.Model): """ model to represent maintenance issue ticket """ # id = models reporter = models.ForeignKey(Member, on_delete=models.CASCADE, null=True, related_name='+', db_column='reporter') location = models.ForeignKey(Member, on_delete=models.PROTECT, null=True, related_name='+', db_column='location') date_reported = models.DateTimeField(default=timezone.now) description = models.TextField(max_length=100) contractor = models.ForeignKey('Contractor', on_delete=models.PROTECT, null=True) class Meta: ordering = ['date_reported'] permissions = [ ("can_message", "add a new message"), ("can_update", "update a ticket"), ] def __str__(self): """ string to return the model name as text""" return f'{self.reporter}, {self.date_reported} GOTO -> ' def get_absolute_url(self): """Returns the url to access a particular ticket instance.""" return reverse('maintenance-ticket', args=[str(self.id)]) class UpdatedTicket(models.Model): ticket = models.OneToOneField(Ticket, on_delete=models.CASCADE, related_name='_ticket', primary_key=True,) comment = models.TextField(max_length=300, null=True) date_updated = models.DateTimeField(default=timezone.now) class … -
Django reverse foreign key leading to duplicate queries
I'm trying to use ViewSet to return list of all assets with the asset type name (instead of just id) but according to django-debug-toolbar, my queries are being duplicated leading to slower results. 1 Asset type can have multiple assets. So, when I try to retrieve all assets (children) -- it's trying to fetch the asset type (parent) names for each of the assets (children) but it's running one query for every asset (child). Looks something like this: It's duplicated 6 times because I have 6 values in the Asset table currently. QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.99 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.99 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (27,) 6 similar queries. Duplicated 3 times. 3.00 Sel Expl + QUERY = 'SELECT TOP 21 [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type] WHERE [mm_asset_type].[id] = %s' - PARAMS = (29,) 6 similar queries. Duplicated 3 times. … -
getting expected curl output in postman.. but not the same when using django view.py
Im doing payment integration in my website and following curl is from phonepe api docs. While using curl its working but not with request.post method in django Here is the curl: curl --location --request POST 'https://mercury-uat.phonepe.com/v4/debit/' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'X-CALLBACK-URL: https://www.demoMerchant.com/callback' \ --data-raw '{ "merchantId":"M2306160483220675579140", "transactionId":"TX123456789", "merchantUserId":"U123456789", "amount":100, "merchantOrderId":"OD1234", "mobileNumber":"9xxxxxxxxx", "message":"payment for order placed OD1234", "subMerchant":"DemoMerchant", "email":"amit***75@gmail.com", "shortName":"Amit" }' And CurlOutput: { "success": false, "code": "BAD_REQUEST", "message": "Please check the inputs you have provided.", "data": {} } But im doing the same thing in django view.py im getting empty dictionary in output Here is code: class test(generics.GenericAPIView): def post(self, request): url = "https://mercury-uat.phonepe.com/v4/debit/" headers = { "Accept": "application/json", "Content-Type": "application/json", "X-CALLBACK-URL": "https://www.demoMerchant.com/callback" } data = { "merchantId":"M2306160483220675579140", "transactionId":"TX123456789", "merchantUserId":"U123456789", "amount":100, "merchantOrderId":"OD1234", "mobileNumber":"9xxxxxxxxx", "message":"payment for order placed OD1234", "subMerchant":"DemoMerchant", "email":"amit***75@gmail.com", "shortName":"Amit" } response = requests.post(url, data=data, headers=headers).json() print(response) return Response(response) output: {} -
How can I solve this local variable referenced before assignment in below code?
def Robot_History(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) fm = list(jenkinsHistory.objects.values('id','robotName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param').filter(robotName=pi)) # print("hello",fm) rob = Robot.objects.all() return render(Request, 'hello/robotHistory.html',{'jenkinsHistory': fm,'robot': rob}) That is my code, whenever i try to sun the code i got the error local variable 'fm' referenced before assignment How to solve that ? -
I wanted to create api for my django project but i alos need to connect Machine Learning project which has a docker file. Now how should i create api?
I have a Machine learning file with Dockerfile. Now i need to create the api and access the ML model in django. How should I do that. Thank you -
How do I use the response from ModelSet view inside my view in Django?
I have a class defined as : class ObjectView(viewsets.ModelViewSet): serializer_class = serializers.ObjectSerialzer queryset = ObjectModel.objects.all() The serializer is defined as: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email', 'username') This creates all the necessary endpoints with various methods like get, post, put etc.. I want to use the data returned from this View with the method get inside of a view. Is there a way to do it or a better way to achieve this function? -
Strange connection error while notifications by celery on heroku
Does anyone know why I'm getting this and how to debug it? WSCONNECTING /ws/notifications/TOKEN" - - DEBUG Upgraded connection ['xxxxxxxx', 23494] to WebSocket DEBUG Creating tcp connection to ('xxxxx.compute.amazonaws.com', 15049) INFO failing WebSocket opening handshake ('Access denied') WARNING dropping connection to peer tcp4:10.1.27.42:23494 with abort=False: Access denied DEBUG WebSocket ['xxxxxx', 23494] rejected by application WSREJECT /ws/notifications/TOKEN -
Option to see/edit objects details in ManyToMany field in Django admin
if we select a foreign key object we get a option to edit that object as shown in image below. But there is no edit option or a way to see the objects in many to many field as you can see below. Is there any option to open the object in a different object and see it's values? -
I want to reflect the images with wagtail
Current state *When I uploaded image files on wagtail, although it is going well to read image title but images itself was destroyed. so the titles is only showed on the display of both admin and user side. I browsed through some blogs and websites on media and static, but this problem has not been resolved for many days. In addition, after using s3, the CSS of admin side might or might not be reflected depending on the browser. development environment python==3.7.3 Django==3.2.6 gunicorn==20.1.0 psycopg2==2.9.1 wagtail==2.14 whitenoise==5.3.0 DB == postgres server == Heroku stack-18 aws s3 ==== the CSS was kept by whitenoise before adapting s3 but I don't know whether to need adding two STATICFILES_STORAGE, therefore remove the one. I could not use collectstatic command, though essensial code comment out for previous code #base.py PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # aws settings """ AWS_ACCESS_KEY_ID = 'AKIAXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXX' AWS_STORAGE_BUCKET_NAME = 'XXXXXXXXXXXXXXX' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = None """ AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'XXXXXXXXXXXXX.com.s3.amazonaws.com' AWS_URL = os.environ.get('AWS_URL') AWS_DEFAULT_ACL = 'public-read' # static settings """ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_LOCATIONS = 'static' STATICFILES_STORAGE = … -
Webpack ERROR in multi frontend/src/index.js
I get an error when I try to run in dev mode, there is an error in the main file, tell me how I can fix this, thanks in advance "scripts": { "start": "react-scripts start", "test": "react-scripts test", "eject": "react-scripts eject", "dev": "webpack --mode development frontend/src/index.js --output-path frontend/static/frontend/", "build": "webpack --mode production frontend/src/index.js --output-path frontend/static/frontend/" }, Ошибка ERROR in multi frontend/src/index.js Module not found: Error: Can't resolve 'frontend/src/index.js' in 'E:\Work\Folder\src' @ multi frontend/src/index.js main[0] -
Can not user login() function of Django ? Encounter __init__() takes 1 positional argument but 3 were given [closed]
From this link: https://docs.djangoproject.com/en/3.2/topics/auth/default/ I tried to do the login,however, I encounter the __init__() takes 1 positional argument but 3 were given error. Here is the views.py file in my app: class login(generics.GenericAPIView): def post(self, request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return HttpResponse("Login success") else: return HttpResponse("Login fail") When call, I got this error: login(request, user) TypeError: __init__() takes 1 positional argument but 3 were given I thought it is something relating to Session so I here is my middleware in settings.py 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', 'django.contrib.sessions.middleware.SessionMiddleware' # I added this row ] Here is my app/urls.py from django.urls import path from . import views urlpatterns = [ path('add', views.add_new_user.as_view(), name='Add new user'), path('login', views.login.as_view(), name='Login to user') ] -
Application error on Deploying Djngo (Python) app
I had deployed my website built with Django via Github. It displays an "Application error". How do I get access to the app via the command line? I want to know the "heroku logs --tail". kindly help me with the code to run. -
How to Containerize sqlite3 and Django app in separate containers for local dev
My project is a web application which is using two technologies wiz: Django + Sqlite3 + Neo4J. I am working on writing docker-compose file so that I can create complete env in just one cmd. The thing which is not clear to me is how I can create three separate container, 1 for Djano, 1 for sqlite3, 1 for neo4j so that app can easily work together. Here the catch point is when Django app run migrate cmd, it create some config.db file in its file system and it should also be shared with sqllite3 db. So how does people handle sqlite3 and Django container issue where table skeleton is created by Django before starting the server and at the same time they want to run sqlite3 in a separate container. my docker-compose.yml: version: '3' volumes: local_neo4j_data: {} local_sqllite_data: {} networks: ecosystem_network: driver: bridge services: neo4j: image: neo4j:latest #4.3.3-community latest container_name: neo4j ports: - "7474:7474" - "7687:7687" networks: - ecosystem_network environment: - NEO4J_AUTH=neo4j/eco_system - NEO4J_dbms_memory_pagecache_size=512M volumes: - ${HOME}/neo4j/data:/data - ${HOME}/neo4j/logs:/logs - ${HOME}/neo4j/import:/var/lib/neo4j/import - ${HOME}/neo4j/plugins:/plugins sqllite3: image: nouchka/sqlite3:latest container_name: sqllite3 stdin_open: true tty: true volumes: - local_sqllite_data:./root/db networks: - ecosystem_network myapp_python: container_name: myapp_python build: context: . dockerfile: compose/Dockerfile volumes: - local_sqllite_data:./myapp_dashboard/config.db … -
Django: Creating unique collection of form elements for every product in e-commerce app
I'm trying to develop a new app in django I'm going to create an easy e-commerce app. This app contains model that include all possible products in the shop. class Product (models.Model): name=models.CharField(max_length=20) and another one that contains all possible form elements for products. class Product (models.Model): id=models.ForeignKey(products, on_delete=models.CASCADE) amount=DecimalField(max_digits=6, decimal_places=2) weigth=DecimalField(max_digits=6, decimal_places=2) color=models.CharField(max_length=20) country=models.CharField(max_length=20) batterycapacity=amount=DecimalField(max_digits=6, decimal_places=2) size=DecimalField(max_digits=2, decimal_places=1) My goal is to create uniqe form collection for every product because for example shoes has different collection of chareacteristic from for example battery. My question is. Is there any way to match chosen form elements for every product? May be instead creating model to connect proper form elements to particular product i should use forms.py in some way. Any suggestions? -
Django aggregate sum on child model field
Consider the following models: from django.db import models from django.db.models import Sum from decimal import * class Supply(models.Model): """Addition of new batches to stock""" bottles_number = models.PositiveSmallIntegerField( bottles_remaining = models.DecimalField(max_digits=4, decimal_places=1, default=0.0) def remain(self, *args, **kwargs): used = Pick.objects.filter(supply=self).aggregate( total=Sum(Pick.n_bottles))[bottles_used__sum] left = self.bottles_number - used return left def save(self, *args, **kwargs): self.bottles_remaining = self.remain() super(Supply, self).save(*args, **kwargs) class Pick(models.Model): """ Removals from specific stock batch """ supply = models.ForeignKey(Supply, on_delete = models.CASCADE) n_bottles = models.DecimalField(max_digits=4, decimal_places=1) Every time an item (bottles in this case) is used, I need to update the "bottles_remaining" field to show the current number in stock. I do know that best practice is normally to avoid storing in the database values that can be calculated on the fly, but I need to do so in order to have the data available for use outside of Django. This is part of a stock management system originally built in PHP through Xataface. Not being a trained programmer, I managed to get most of it done by googling, but now I am totally stuck on this key feature. The remain() function is probably a total mess. Any pointers as to how to perform that calculation and extract the value … -
Stripe 'card-element' is not displaying. Why?
Completely losing my mind with this... I am creating a ecommerce website with django. I use Stripe as Payment Gateway Provider. I don't understand ...Stripe 'card-element' is not displaying. Why ? For information, the card-element used to be displayed correclty in the previous days. I could simulate payments which were recorded in my Stripe account... The thing is, I have checked with older versions of my code which used to work (in case I did a mistake since). But none of them is working... It's driving me crazy. Anything wrong with my code ? Any idea ? checkout.html {% extends 'main.html' %} {% load static %} {% block content %} <script src="https://js.stripe.com/v3/"></script> <div class="container"> <div class="row"> <div class="col d-flex justify-content-center align-items-center"> <h3 class="text-primary fw-bold">PAIEMENT PAR CARTE</h3> </div> </div> <div class="row "> <div class="col d-flex justify-content-center align-items-center"> <form id="payment-form" method='POST' class="col"> {% csrf_token %} <div class="form-control" id="card-element"></div> <div class="sr-field-error" id="card-errors" role="alert"></div> <button id="payer-submit" class="btn btn-primary"> <div class="spinner-border spinner-border-sm text-light d-none" id="spinner" role="status"></div> <span class="text-white" id="button-text">Pay</span> <span class="text-white" id="order-amount"></span> </button> </form> </div> </div> <div class="row "> <div class="col d-flex justify-content-center align-items-center"> <form id="payload" method='POST' class="col" action="/payment/payment-bycard-complete"> {% csrf_token %} <input id ="data-payload" type="hidden" name="payload"/> </form> </div> </div> </div> <script type="text/javascript" src="{% static …