Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The price should change well when adjusting the quantity, but it doesn't change when it's one
The price should change well when adjusting the quantity, but it doesn't change when it's one. What's the problem? It works correctly from two. I want to modify this code and sleep comfortably. Great developers, please help me. script $(document).ready(function () { $('.price_btn input[type="button"]').on('click', function () { var $ths = $(this); var $par = $ths.parent().parent(); var $obj = $par.find('input[type="text"]'); var $input = $par.find('input[id="price2"]'); var $price2 = parseInt($par.find('strong[name="price2"]').text().replace(/[^0-9]/g, "")); var val = $obj.val(); if ($ths.val() == '-') { if (val > 1) $obj.val(--val); $input.val($price2); } else if ($ths.val() == '+') { if (val < 30) $obj.val(++val); $input.val($price2); } //수량 변경 var unit_amount = $par.find('.price_unit').text().replace(/[^0-9]/g, ""); var quantity = val; pay_unit_func($par, unit_amount, quantity); pay_total_func(); }); function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); html " <div class=\"price_btn\">\n" + " <input type=\"button\" value=\"-\" class=\"minus_btn\">\n" + " <input style=\"width: 15%;\" type=\"text\" value=\"0\" class=\"number\" name=\"quantity\" id=\"quantity\">\n" + " <input type=\"button\" value=\"+\" class=\"plus_btn\">\n" + " </div>\n" + " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<strong name=\"price2\" id=\"price2\" class=\"price_amount\" … -
Invalid block tag on line 30: 'update_variable', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
I want to declare a variable and update its value inside a template in django.How can I do that? -
Convert mysql query to django orm with requires same table
I am trying to convert sql code to django orm code. I don't want to use python raw function SELECT u.`user_id` as 'dp_id', cp.`email` as 'dp_email', cp.`name` as 'dp_name', u2.`user_id` as 'cm_id', cp2.`email` as 'cm_email', cp2.`name` as 'cm_name' FROM `user` u INNER JOIN customer_profile cp ON u.`customer_profile_id` = cp.`id` INNER JOIN branch_user bm ON bm.`child_user_id` = u.`user_id` AND bm.`parent_role_id` = 14 AND bm.`is_deleted` = 0 INNER JOIN user u2 ON u2.`user_id` = bm.`parent_user_id` AND u2.`is_deleted` = 0 INNER JOIN customer_profile cp2 ON u2.`customer_profile_id` = cp2.`id` WHERE u.`user_id` = ? AND u.`is_deleted` = 0 I did something like this : cp_emails = User.objects.filter(branch_user_childUser__parent_role_id=14, branch_user_childUser__is_deleted=0).select_related('customer_profile').prefetch_related('branch_user_childUser') But i am not able to add user u2 to django orm as it's same user table and that too compare with "bm" i.e this line "ON u2.user_id = bm.parent_user_id" My models: class User(models.Model): user_id = models.AutoField(primary_key=True) customer_profile = models.ForeignKey( 'login.CustomerProfile', on_delete=models.CASCADE, default=None ) class BackboneUserManagerMapping(models.Model): child_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING) parent_user = models.ForeignKey('login.User', related_name='branch_user_childUser', on_delete=models.DO_NOTHING) parent_role_id = models.IntegerField() is_deleted = models.BooleanField(default=False) class CustomerProfile(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) email = models.EmailField(default=None, unique=True) mobile = models.CharField(max_length=13, default=None) alt_mobile = models.CharField(max_length=13, null=True) name = models.CharField(max_length=255, default=None) -
Cannot assign "'1'": "Groups.profile" must be a "Profile" instance
I have Profile Model that have instance model user.. I am trying to create group using form. that group model have Profile model as instance, so how do I select authenticated user automatic to create group, I getting confused... This is my Group Model class Groups(models.Model): profile = models.ForeignKey(Profile, related_name='my_groups', on_delete=models.CASCADE) groups_name = models.CharField(max_length=150) slug = models.SlugField(max_length=150, unique=True) cover_pic = models.ImageField(upload_to='images/groups/', null=True, blank=True) type_group = models.CharField(max_length=150) created_date = models.DateTimeField(auto_now_add=True) about_group = models.TextField(max_length=600) members = models.ManyToManyField(Profile,through="GroupMember") def __str__(self): return self.groups_name This is my profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') slug = models.SlugField(max_length=100, unique=True) profile_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True) cover_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True) user_bio = models.TextField(null=True,blank=True, max_length=255) designation = models.CharField(blank=True,null=True, max_length=255) education = models.CharField(blank=True, null=True, max_length=255) marital_status = models.CharField(blank=True, null=True, max_length=60) hobbies = models.CharField(blank=True, null=True, max_length=500) location = models.CharField(blank=True, null=True, max_length=500) mobile = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.user) This is form for create group class GroupCreateForm(forms.ModelForm): class Meta: model = Groups fields = ('cover_pic', 'profile', 'groups_name', 'type_group', 'about_group') profile = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control input-group-text', 'value':'', 'id':'somesh', 'type': 'hidden', })) This is create group html file this is html page this is error.. -
How to auto-check Google approved scopes on OAuth page?
I've been fully verified for the Google Calendar API as shown in the image below... ...but when users hit my OAuth consent screen on the webflow, the box is unchecked by default on the calendar as shown in the following image... Is there any way to ensure that the box is checked by default? I'm using Django as my framework with the code below for the auth flow: flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( env('GOOGLE_CLIENT_SECRET'), scopes=['https://www.googleapis.com/auth/calendar.events','https://www.googleapis.com/auth/userinfo.email', 'openid'] ) flow.redirect_uri = env('GOOGLE_FLOW_REDIRECT_URI') authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true' ) -
How can I do to exclude some null values using queryset django?
I have a queryset B and I want to exclude null values so I did that : B.exclude(mycolumn__in[0, {"total": 0}]) because sometimes I can have JSON Field with null values. But I noticed that I can have that cases : {"total": 0, "2": 0}]) or {"total": 0, "5": 0}]) and like all the values are null I would like to exclude them also. How can I do that using exclude() ? Thank you very much ! -
How to fetch data from AWS S3 bucket using Django Rest API
I'm trying to fetch my media files from a django rest api using a jquery async function, this function worked fine in development but now I've deployed the app to Heroku and my media files are being served by an AWS S3 bucket, so this fetch function doesn't work anymore. music.js async function getUserTracks() { await fetch("http://127.0.0.1:8000/music/music_all/?format=json") .then(res => res.json()) .then(data => { for (item of data) trackNames.push(item['title']), trackUrl.push(item['track']), albums.push(item['artist_name']) // console.log(trackNames, trackUrl, albums) }); } As you can see the fetch url is a localhost address, my question is how can I fetch these files, now that they are in AWS? -
How to show UpdateView form below field to be updated
I trying to learn web-dev with django. As an exercise I am trying to build something where you have a document and within each document you have blocks of text that you can update (like a wiki but much more simpler). My models.py looks like this, from django.db import models from django.urls import reverse # Create your models here. class LatexBlock(models.Model): code = models.TextField(max_length=2000, help_text='Enter latex code') def __str__(self): return self.code class Document(models.Model): title = models.CharField(max_length=200) code = models.ManyToManyField(LatexBlock) def __str__(self): return self.title def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('doc-detail', args=[str(self.id)]) What I would like to do it is use ajax to make a form appear below a LatexBlock and then be able to update it. So I have a document detail view which does this. {% for block in document.code.all %} <div> <!--<a href="{% url 'block-update' pk=block.pk%}" class="float-right">[Edit]</a>--> <button onclick=TestsFunction("{{block.pk}}","{% url 'block-update' pk=block.pk%}","{{request.path}}") class="btn btn-outline-info btn-sm float-right">Edit</button> {{block|linebreaks}} <div id="edit-btn-{{block.pk}}" style="display: none"> <form action="{% url 'block-update' pk=block.pk%}" method="post"> {%csrf_token%} <input type="text" id="edit-val-{{block.pk}}" name=""><br> <input type="submit" value="Submit"> </form> </div> </div> {% endfor %} TestsFunction is where I show the form and then submit the form. <script> function TestsFunction(pk,url,success) { var T = … -
AWS Beanstalk Django Cannot Connect to RDS Instance Because Wrong Private IP Resolved from RDS Endpoint
My setup: AWS RDS MySQL Instance located in a custom VPC (Private Subnet) AWS Beanstalk Django app located in the same custom VPC (Public Subnet) Beanstalk EC2 Private IP: 10.0.2.37 RDS Endpoint: stockpeektestdbcachekafka-trading-db.cxapiv8ipcaj.ap-southeast-1.rds.amazonaws.com RDS Private IP after using telnet to the RDS Endpoint inside Beanstalk EC2: 10.0.4.163 The problem: I keep getting DB connection refused error with my Django app Looking closer at the error msg: it is because the RDS endpoint URL is resolved to the EC2 Private IP instead Error Image Link This is still happening although I have set DB HOST in settings.py to be the RDS Endpoint How to fix this endpoint resolve error? Thanks!` -
Python Django init.py
Here is the errors I am facing for the last 2 days. I try many things but not work. Kindly help me out. First the project was run, after that it is not running.enter image description here The code is Below : """ Settings and configuration for Django. Read values from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global_settings.py for a list of all possible variables. """ import importlib import os import time import traceback import warnings from pathlib import Path import django from django.conf import global_settings from django.core.exceptions import ImproperlyConfigured from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import LazyObject, empty ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG = ( 'The PASSWORD_RESET_TIMEOUT_DAYS setting is deprecated. Use ' 'PASSWORD_RESET_TIMEOUT instead.' ) DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG = ( 'The DEFAULT_HASHING_ALGORITHM transitional setting is deprecated. ' 'Support for it and tokens, cookies, sessions, and signatures that use ' 'SHA-1 hashing algorithm will be removed in Django 4.0.' ) class SettingsReference(str): """ String subclass which references a current settings value. It's treated as the value in memory but serializes to a settings.NAME attribute reference. """ def __new__(self, value, setting_name): return str.__new__(self, value) def __init__(self, value, setting_name): self.setting_name = setting_name class LazySettings(LazyObject): """ A lazy … -
Django - Why I got Boolean result when I try to get data from the DB?
my view: def add_word(request): current_date = timezone.now() english = request.POST.get("the_word_in_english", False) hebrew = request.POST.get("the_word_in_hebrew", False) context = request.POST.get("How_To_Remember", False) name = request.POST.get("your_name", False) Words.objects.create(pub_date=current_date, English_word=english, Hebrew_word=hebrew,How_To_Remember=context, Name=name) return HttpResponseRedirect("/polls/") {% if search %} {% for item in word %} <p> </p> <b>{{ item.English_word }} </b> <br> {{ item.Hebrew_word }} <br> {{ item.How_To_Remember}} {{ item.Name }} </p> {% endfor %} {%else%} {{message}} {%endif%} All the field is gives regular result (string) just 'How_To_Remember' field give True/False result I tried to delete the migrations few times and the DB and create new one and I'm getting the same result every time.. -
How to perform periodic tasks within Django?
I have a web app on Django platform. I have a method within views.py: def task(): print("my task") how can I run it every day once? I need a very simple solution and it should be independent of other tasks (parallel). -
How to Foreign_Key value instead of id in django rest framework without read_only=True
I working on project with drf where I'm getting serializer data as follows which is absolutely fine: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": 2, "item": 1, "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } but I want to get as following: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": "user name", "item": "product name", "price: "3.44", "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } I tried using drf RelatedField and PrimaryKryRelatedField but in all these cases I need to make corresponding fields as read_only=True which I want to skip. I also tried with depth = 1 which gives entire details My Model: class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) item = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{} - {} - {} - {} - {}".format(self.user, self.item, self.quantity, self.created_at, self.updated_at) My serializer: class CartSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(source='user.first_name' ,queryset=User.objects.all(), many=False) class Meta: model = Cart fields = ['id', 'user', 'item', 'quantity', 'created_at', 'updated_at'] My View: class CartViewSet(viewsets.ModelViewSet): queryset = Cart.objects.all().order_by('id') serializer_class = CartSerializer def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.serializer_class( queryset, context={'request': request}, many=True) … -
How to represent text in the JavaScript input box?
How do I print text in the input box? No matter how hard I try, there is no change. I want to put the JavaScript I wrote in the input box. html " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<input class=\"price_amount\" id=\"price2\" name=\"price2\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\" value=\"0\">" + "원\n" + " </div>\n" + script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('input[type="text"]').text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('input[type="text"]').text(total_price.toLocaleString()); } -
TypeError: issubclass() arg 1 must be a class, strartapp
I have been working on a Django project. And when I try to use python3 manage.py startapp newletters I have such an error: File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/evgenia/PycharmProjects/CarDealer/venv/lib/python3.8/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class -
Django SQL query to ORM implementation involving Joins and Group By
This query should return the total sum of (quantity - qty_fulfilled) grouped by product_id. I'm stuck trying to convert this postgres sql query into an ORM query. This sql query works, but get_queryset() method in the Admin models does not support RawQueryset as indicated here, so this needs to be in a Queryset form. select t1.id, t3.req_from_orders from inventory_inventory t1 left join product_app_product t2 on t1.product_id = t2.id left join ( select product_id, sum(quantity) - sum(qty_fulfilled) as req_from_orders from order_app_cartitem oac group by oac.product_id ) t3 on t1.product_id = t3.product_id Models: * Inventory * product_id (OneToOneField) * id (UUID) * Product * id (UUID) * CartItem * id (UUID) * product_id (ForeignKey) * quantity (int) * qty_fulfilled (int) * Inventory <-> Product <-* CartItem Tried using annotate(RawSQL="<query>", params=(param,)) but params cannot take in dynamic ids. Any help would be greatly appreciated. -
DRF - APIView and Serializing a model with multiple foreign Keys(User)
How to save multiple foreign keys(User) data? models class HireProfessional(models.Model): hireBy = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") hire_start_date_time = models.DateTimeField(default=timezone.now) hire_end_date_time = models.DateTimeField(default=timezone.now) seriliazer class HireProfessionalSerializer(serializers.ModelSerializer): class Meta: model = HireProfessional fields = '__all__' views class HireProfessionalCreateApp(APIView): permission_classes = (IsAuthenticated, IsClientUser,) def get_user(self): user = self.request.user return user def post(self, request, pk, format=None): user = User.objects.filter(id=pk).first() serializer = HireProfessionalSerializer(data = request.data, instance=user) data = {} if serializer.is_valid(): hire = serializer.save(owner=self.get_user()) data['hireTo'] = hire.hireTo return JsonResponse ( { "message":"professional hired success.", "success" : True, "result" : data, "status" : status.HTTP_201_CREATED } ) else: data = serializer.errors return Response(data) It returns hireBy, user: "This field is required." how do I solve this problem? Does anybody have any idea? -
django filters icontains with __in lookup
Similar to this question: django icontains with __in lookup I am attempting to filter a single field with multiple values using the django-filters package. For example, I have a model Content with field paragraph. I want to return the object if Content.paragraph contains string "McDonald" or Content.paragraph contains string "MacDonald". Essentially be able to pass multiple icontains to a single field. Thanks! -
Nginx is rendering the wrong website. Does anyone know why?
My website 1 Nginx .conf file is rendering website 2 on my server. So both websites render website 2. I want website 1 to render a Django website. Website 2 is just a normal HTML website. The files for both the websites are located in /home/webserver not in /var/www. Website 1: # the upstream component nginx needs to connect to upstream django { server unix:///home/webserver/exo_dashboard/dashboard/exo.sock; } # configuration of the server server { listen 80; server_name beta.exobot.xyz www.beta.exobot.xyz; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media/ { alias /home/webserver/exo_dashboard/dashboard/media; } location /static/ { alias /home/webserver/exo_dashboard/dashboard/static/; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/webserver/exo_dashboard/dashboard/uwsgi_params; } } Website 2: server { root /home/webserver/website; index index.html index.htm index.nginx-debian.html; server_name exobot.xyz www.exobot.xyz; location / { try_files $uri $uri/ =404; } location = /arc-sw.js { proxy_pass https://arc.io; proxy_ssl_server_name on; } listen [::]:443 ssl; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/exobot.xyz/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/exobot.xyz/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = exobot.xyz) { return 301 … -
how to change color help text using crispy tags
I am trying to use cripsy forms for a django website, everything works fine but as you can see my background isn’t white,but blue so the help text doesn’t stand out How can I change the color of the helper text? -
Unable to make correct migrations in Django
I cannot make correct migrations with one specific fields image_two in my Django Project. I have also configured Django-Rest and all this is connected to AWS. Endpoint is looking alright and I am getting correct url from image_one and image_two. But I don't know how to create a column in database for storage this image URL. Yes, I have read documentation from ImageKIT and they said: ImageSpecFields, on the other hand, are virtual—they add no fields to your database and don’t require a database. This is handy for a lot of reasons, but it means that the path to the image file needs to be programmatically constructed based on the source image and the spec. In ImageKIT there is also ProcessedImageField, but this is not an option for me, because I have to also save in database source image and send it to AWS S3. from django.db import models from imagekit import ImageSpec, register from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from imagekit.utils import get_field_info class ImageTest (models.Model): name = models.CharField(max_length=50, blank=False) added_at = models.DateTimeField(auto_now_add=True) image_one = models.ImageField(null=True, blank=False) new_width = models.PositiveIntegerField(blank=False) new_height = models.PositiveIntegerField(blank=False) image_two = ImageSpecField(source='image_source', id='myapp:imagetest:resizeme',) class ResizeMe(ImageSpec): format = 'JPEG' options = {'quality': 80} @property … -
Django filtering models in Foreign Key
Models.py class AdmissionStudent(models.Model): studentlabel = models.CharField(max_length = 100, null = False, blank = False) def __str__(self): return self.studentlabel class AdmissionRequirement(models.Model): requirementstudent = models.ForeignKey(AdmissionStudent, on_delete = models.CASCADE, null = False, blank = False) requirementparagraph = models.TextField(null = False, blank = False) def __str__(self): return '{} - {}'.format(self.requirementstudent, self.requirementparagraph) Views.py def admission(request): header = AdmissionHeader.objects.first() student = AdmissionStudent.objects.all() requirement = AdmissionRequirement.objects.all() context = { 'header': header, 'student': student, 'requirement': requirement, 'title':'Admissions' } return render(request, 'pages/admission.html', context) Admission.html (template) {% for student in student %} <b>{{ student.studentlabel }}</b><br> {% if {{ student.studentlabel}} == {{requirement.requirementstudent }} %} {% for requirement in requirement %} {{ requirement.requirementparagraph }}<br> {% endfor %} {% endfor %} I know what I did in my template is stupid, but i really don't know how to filter Admission Requirements for enrollment, Below is an example of how I want it to appear: Transferee -1st requirement -2nd requirement -3rd requirement Foreign Student -1st requirement -2nd requirement -etc -
Convert QuerySet into List in Django for ModelMultipleChoiceField
TIMESLOT_LIST = ( (5, '09:00 – 09:30'), (9, '09:30 – 10:00'), (2, '10:00 – 10:30'), ) class AvailabilitiesForm(forms.Form): time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): date = kwargs.pop('date') super(AvailabilitiesForm, self).__init__(*args, **kwargs) #choices = getChoices(letter) self.fields['time_slot'].queryset = Appointment.objects.filter(date = date).values_list('time_slot', flat = True) This displays : I want : How can I use the TIMESLOT_LIST to display the string "9h00 - 9h30" and not 5 ? While passing through, how can I can withdraw the bullet points ? -
How to update item quantity on django ecommerce project
I am trying to update the quantity of my cart when I use click the add to cart button. I have been trying to figure out the logic behind it but cannot seem to get it. I believe under my views.py I am adding an item to the cart but it is not working. Can anyone give me some direction on this? main.Html <button href="{% url 'add_cart'%}" class="btn btn-primary add-cart">Add to Cart</button> urls.py urlpatterns = [ path('add_cart', views.add_cart, name='add_cart') ] Views.py def add_cart(request, slug): product = get_object_or_404(Product, slug=slug) item = Item.objects.create(product=product) order = Order.objects.filter(user=request.user, ordered=False) if order.exists(): order = order[0] if order.items.filter(item_slug=item.slug).exists(): item.quantity += 1 item.save() else: order = Order.objects.create(user=request.user) order.items.add(item) return redirect('main') models.py class Product(models.Model): img = models.CharField(max_length=30) product_name = models.CharField(max_length=250, null=True) price = models.CharField(max_length=250, null=True) description = models.TextField() slug = models.SlugField() def __str__(self): return self.product_name class Shopper(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=250, null=True) email = models.CharField(max_length=250, null=True) def __str__(self): return self.name class Order(models.Model): shopper = models.ForeignKey( Shopper, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) trans_id = models.CharField(max_length=250, null=True) ordered = models.BooleanField(default=False) def __str__(self): return str(self.trans_id) @property def cart_total_items(self): total_items = self.item_set.all() cart_total_items = sum([item.quantity for item in total_items]) return cart_total_items def cart_total(self): total_items = … -
How to float text in the input box in javascript?
I want to text the code I wrote in JavaScript into the input box. However, there is a problem that the input box is not outputting text. The input box I want to print is in html. The content is as follows: <input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원 Is there a problem with my source code? I wonder why the text doesn't appear. Wise developers, please help me solve this problem I'm facing. script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('.item_price').getElementsByClassName("item_price").text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString()); } html " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원\n" + " </div>\n" + **All Sourcecode ** <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = parseInt($(this).find(':selected').data('price')); var hapgae = price + test if (checkValue …