Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot Edit Form in Javascript With Django
I'm trying to edit a form on this site with Django, and save the edits using Javascript (but not mandating a page refresh). When the user clicks 'edit' on the page, nothing happens. No console errors. I think the issue is in the Javascript function edit_post. I'm new to using Javascript with Django. Any help is appreciated. Relevant urls.py path('edit_post/<str:id>', views.edit_post, name="edit_post"), #before was pk not id path('edit_post/', views.edit_post), path("profile/<str:username>", views.profile, name="profile"), Javascript function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; // everything above this works and opens up the form for editing edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch(`/edit_post/${id}`, { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = post.trim(); }); } Relevant html <span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br> <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}" style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea> <button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}" onclick="edit_handeler(this)" >Edit</button> <br><br> views.py def edit_post(request, id): post = Post.objects.get(id=id) form = PostForm(instance=post) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return JsonResponse({}, status=201) else: … -
Add a second attribute/category column to Django administrator GUI
I'm learning Django right now and I made this class called Clowns. On the Django Admin page I made two test objects. I made four attributes(dunno what they're called lol) for clowns. They are title, description, identification, and hobbies. See below: title = models.CharField(max_length=20) description = models.TextField() identification = models.CharField(default='-', max_length=5) hobbies= models.TextField() To make the "CLOWN" column you see in the image I added this to the clown class: def __str__(self): return self.title I seem to only be able to do this with one attribute/category, in this case it's title. How do I make another column for another attribute, say id? -
relation "users_user_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "users_use
I have created Custom User Model in Django as follows, When I got Admin and click on User and then a particular user it gives me error : relation "users_user_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "users_use... Thanks for solving it in advance! from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin import uuid class UserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Email Requierd!") if not username: raise ValueError("Username required!") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): userid = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perm(self, app_label): return True class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=85) last_name = models.CharField(max_length=85) recovery_email = models.EmailField(blank=True) img = models.ImageField(default='aavtar.png', upload_to='media') def __str__(self): return … -
Does using a foreign key as a column in the django admin interface create a new database query for each row?
I have a model relationship that looks like the following: class Author(Model): first_name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) I want an admin interface like this: class BookAdmin(ModelAdmin): list_display = ('title', 'author_name') def author_name(self, obj): return obj.author.name Does this create a new query for each row, or is django smart about using a join here? What if the relation is 2 or more levels deep instead of just 1? Using python 3.8, django 3.1, and Postgres 12. -
Flutter and Django, notification I need some north
I'm starting a project, my Django app communicates and receives data from an API, it might send notifications to the users when it receive something, I also wanna build a mobile app that receive these notifications, can someone indicate me what content should I look for? Is what I need something like web socket connection? -
Send the value of a disabled select in a form with a hidden input
I have a Django form, one of the parts is populated like this: <select {% if 'ba1' in widget.name or 'bs1' in widget.name or 'pm2' in widget.name %} disabled {% endif %} id="{{ widget.attrs.id }}" name="{{ widget.name }}" {% if widget.attrs.disabled %}disabled{% endif %} {% if widget.required %}required{% endif %} class="form-control form-control-sm {% if widget.errors %} is-invalid{% else %} is-valid{% endif %}" aria-describedby="{{ widget.id }}-help"> {% for value, label in widget.attrs.choices %} {% if value in widget.value %} <option value="{{ value }}" selected>{{ label }}</option> {% else %} <option value="{{ value }}" data="{{widget.value}}">{{ label }}</option> {% endif %} {% endfor %} </select> As it is a disabled field for ba1, bs1 and pm2 cases, that information will not be sent in the POST request. So what I have done is, through a hidden input, send the selected value of the disabled select. Unfortunately the value is always 0 instead of the correct value. I'm doing something wrong. Somebody could help me?. For example if the selected value is 2, or 3 or 4, it doesn't matter, the hidden input says that the selected value is 0, which is not correct. Hidden input code (not working, always value = 0) {% … -
Can I build a basic website to access my resume but slowly customize it using python to learn and showcase my skills?
I"m not entirely certain what I'm trying to do is doable. I want a ready made website that I can make live fairly quick but later modify it with python code. I have basic python knowledge and used it, as well as SQL regularly as a BSA at a past job. I also have some experience with HTML, though I would need a heavy brush up to actually build a website. We focused more on flash at the time. (15 years ago or so). I want a basic templated website that I can make live with very little customization and gradually learn and modify it with python. If I'm understanding correctly, you can't run python in html, but you can run html in Django. I read about Django Templates but not entirely certain this will be ready to go without some serious python webbev knowledge. Is it possible to have Django framework run an html templated website? Or are Django templated websites easy to customize and make live? -
Why doesn't it return an HttpResponse even though render returns?
My html template and urlpatterns are checked OK, but it just doesn't response anything and saying like this The view search.views.search_list didn't return an HttpResponse object. It returned None instead. So what's wrong? If I return HttpResponse('hello world'), it still just tell me returning nothing? def search_list(request): #return render(request, '/', locals()) start_time = time.time() searched = True keywords = request.GET.get('q') print(keywords) message = '' if not keywords: return redirect('/') #words = keywords.split('') word = keywords post_list = Poem.objects.filter(Q(author_name__contains=word) | Q(model_name__contains=word) | Q(poem_name__contains=word) | Q(dynasty__contains=word) | Q(content__contains=word)) print(post_list) try: old_word = SearchHotspot.object.get(word=word) except: new_word = SearchHotspot() new_word.word = word new_word.count += 1 new_word.save() else: old_word.count += 1 old_word.save() limit = 10 paginator = Paginator(post_list, limit) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) end_time = time.time() load_time = end_time - start_time title = keywords + "- 众里寻他千百度" content = "蓦然回首,那人却在灯火阑珊处。" return render(request, 'search/result.html', locals()) -
AttributeError: object has no attribute 'decode' when using Selenium and Django
I have a Django crawler that stores all URLs in the database from a site and I'm trying to get Selenium to scrape the content of each of the URLs but I'm getting this error object has no attribute 'decode' here is the code snippet: tasks.py ... @shared_task def crawler(): options = webdriver.ChromeOptions() options.add_argument(" - incognito") browser = webdriver.Chrome( executable_path='./scraper/chromedriver', chrome_options=options ) urls = urlList.objects.all() for url in urls: if 'cl/terreno/venta' in urlparse(url).path: print(url) elif 'cl/sitio/venta' in urlparse(url).path: print(url) browser.get(url) timeout = 10 nombre = browser.find_element_by_xpath("//h1[@class='subtitulos fb_title']") descripcion = browser.find_element_by_xpath("//div[@class='descrip']/p[2]") aspectos_generales = browser.find_element_by_xpath("//div[@class='aspectos']") region = browser.find_element_by_xpath("//span[@class='_tag_style']") lugar = browser.find_element_by_xpath("//span[@class='_tag_style'][2]") precio = browser.find_element_by_xpath("//span[@class='val fb_value']") print("Nombre: {} \n" "Descripcion: {} \n" "Aspectos generales: {} \n" "Region: {} \n" "Lugar: {} \n" "Precio: {} \n" .format(nombre.text, descripcion.text, aspectos_generales.text, region.text, lugar.text, precio.text )) -
Permission error when writing files in django + ubuntu + apache
Following is the error message I receive when I save x.mp3 via django : Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'x.mp3' -
Django Show Distinct Values in List
I'm trying to create a table that shows only the unique values based on a specific column. The following code does not present any errors, but does not show the unique values as intended - any ideas where the mistake is? Why wouldn't this do the trick? return self.name.distinct('name') Example, I have 3 rows for Rob in my table because he has 3 addresses, but I am creating a list in my app that shows Rob, John, and Clayton and I only want Rob to show up once. views.py from django.http import HttpResponse from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Book class BookList(ListView): model = Book class BookCreate(CreateView): model = Book fields = ['name', 'address', 'birthdate', 'deathdate', 'description'] success_url = reverse_lazy('books_cbv:book_list') class BookUpdate(UpdateView): model = Book fields = ['name', 'address', 'birthdate', 'deathdate', 'description'] success_url = reverse_lazy('books_cbv:book_list') class BookDelete(DeleteView): model = Book success_url = reverse_lazy('books_cbv:book_list') models.py from django.db import models from django.urls import reverse class Book(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200, default='none') birthdate = models.CharField(max_length=200, default='none') deathdate = models.CharField(max_length=200, default='none') description = models.CharField(max_length=1000, default='none') def __str__(self): return self.name.distinct('name') def get_absolute_url(self): return reverse('books_cbv:book_edit', kwargs={'pk': self.pk}) book_list.html {% extends "base.html" %} {% … -
Creating a .java popup for Django Project
Please note - this is (to the best of my knowledge) not a duplicate question; there have been similar questions in the past but they involve applets and other features which no longer exist. I have a working .java file named SignaturePad.java that creates a pop-up screen (JFrame) allowing a user to draw their signature and save it as a png in my a folder in my src. I need it to be called by an HTML button in a Django based website. I have tried 2 things: Using <button onclick> to call JavaScript which calls the Java <button onclick = "MyFunction()">Sign!</button> <p id='demo'></p> <script> MyFunction(){ var opened = function(){ var Main = Java.type(SignaturePad); Main.runJava(); }; document.getElementById("demo").innerHTML = "Signature Recieved"; } </script> This was inspired by this video showing how to call Java from JS and this article showing how to use a HTML button to call a script. There seems to be an issue in even reaching MyFunction(), as I put a syntax error inside it and pressed the sign button, and no error was reported. Using Django/HTML POST Forms which calls Java <--! IN post_detail.html !--> <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Sign!</button> </form> # in views.py … -
Django Block Title Shows In Page Content
I was trying to add a title for one of my Django HTML templates. The title of the website changes but it also shows up as text on the page content. How do I fix this and why does this happen? base.html {% block head %} <head> <title>{% block title %}{% endblock %}</title> </head> {% endblock %} page.html {% extends "base.html" %} {% block head %} {% block title %}Some Title{% endblock %} {% endblock %} -
calling a class below of another class
I'm working on a django project with rest_framework and I have a problem with serializers. Here is my code: class CategorySerializer(serializers.ModelSerializer): featured_product = ProductSerializer(read_only=True) class Meta: model = Category fields = [ 'title', 'featured_product', ] class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(read_only=True) class Meta: model = Product fields = [ 'title', 'price', 'category', ] as you see, at ProductSerializer Im using CategorySerializer, and also at CategorySerializer I need to use ProductSerializer. if I run the code I get NameError: name 'ProductSerializer' is not defined. First try:I tried to write them in two different files and import them at top of both files but I got Circular Import errorSecond try:I defined an empty class with name of ProductSerializer class at the top of my code but it didn't worked. -
Can't index parsed JSON string from backend
My frontend's supposed to take in a JSON string from the backend and use it, but when I try to index it after using JSON.parse(), it returns undefined. I checked, and it isn't inside an array either; it's just a JSON object literal. In case any of you aren't familiar with TypeScript, the exclamation points are a TS thing, and removing them doesn't change the results I've been getting. Here's what the console's been showing me: console.log(document.getElementById('guestUserCredentials')!.textContent!) "{\"EMAIL\": \"guest_user@foo.com\", \"PASSWORD\": \"foobar\"}" console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!)) {"EMAIL": "guest_user@foo.com", "PASSWORD": "foobar"} console.log(JSON.parse(document.getElementById('guestUserCredentials')!.textContent!)["EMAIL"]) undefined Maybe it has something to do with the way my Django backend is encoding the JSON string? How do I check for that and fix it, if that's the case? I'm passing it to my React/TS frontend like this: settings.py ... GUEST_USER_CREDENTIALS = { 'EMAIL': os.environ.get('GUEST_EMAIL'), 'PASSWORD': os.environ.get('GUEST_PASSWORD'), } ... views.py import json from django.conf import settings from django.shortcuts import render def index(request, *args, **kwargs): print(settings.GUEST_USER_CREDENTIALS) print(json.dumps(settings.GUEST_USER_CREDENTIALS)) return render(request, 'index.html', context={ 'GUEST_USER_CREDENTIALS': json.dumps(settings.GUEST_USER_CREDENTIALS), }) index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='icon' href='{% static "frontend/favicon.ico" %}' type='image/x-icon' /> <title>foo</title> </head> <body> <div id='root'> <!-- React goes here. --> </div> </body> {{ GUEST_USER_CREDENTIALS|json_script:"guestUserCredentials" }} … -
Django How to make form fit HTML input field
I have a small question. Here is my "Register page": But when i add my form to the login for example, i get this: I want to know how can i make that form box fit that html input field? I dont know if I have to resize it in the forms.py or if there was a way for it to always bind up the input size that is in the html file. This is the HTML: {% load static %} <!DOCTYPE html> {% csrf_token %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>IPV QS Tool Registration</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <link rel="stylesheet" href="registration.css" /> <link rel="stylesheet" type="text/css" href="{% static 'css/style_register.css' %}" /> </head> <body> <form method="POST" action=""> <label> <p class="label-txt">ENTER YOUR AMAZON EMAIL</p> <input type="email" class="input" required /> <div class="line-box"></div> <div class="line"></div> </div> </label> <label> <p class="label-txt">ENTER YOUR AMAZON LOGIN</p> {{form.username}} <div class="line-box"> <div class="line"></div> </div> </label> <label> <p class="label-txt">CREATE A PASSWORD</p> <input type="password" class="input password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required /> <div class="line-box"> <div class="line"></div> </div> </label> <button type="submit">Submit</button> </form> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" … -
How to send live (socket like connection) data to a Node Frontend from my Django app
Ok so I have a Django app deployed in Digital ocean and the front end is currently being updated so its ran locally through npm start. My app receives specific input and computes some complex calculations that varies from a request to another however, in my app I have a percentage that gets printed out in a loop that goes like (10%,20%,30%,..) and every percent is a print statement and i would love to know how can I communicate that with the front end since requests work in a fashion of post and get and so on so is there any way of doing it ? I thought about socket connection but I failed hardly as I couldn't implement that -
It is possible to GROUP BY multiple columns separately and aggregate each one of them by other column with django ORM?
I know how to GROUP BY and aggregate: >>> from expenses.models import Expense >>> from django.db.models import Sum >>> qs = Expense.objects.order_by().values("is_fixed").annotate(is_fixed_total=Sum("price")) >>> qs <ExpenseQueryset [{'is_fixed': False, 'is_fixed_total': Decimal('1121.74000000000')}, {'is_fixed': True, 'is_fixed_total': Decimal('813.880000000000')}]> However, If I want to do the same for other two columns, it only returns the last: >>> qs = ( ... Expense.objects.order_by() ... .values("is_fixed") ... .annotate(is_fixed_total=Sum("price")) ... .values("source") ... .annotate(source_total=Sum("price")) ... .values("category") ... .annotate(category_total=Sum("price")) ... ) >>> qs <ExpenseQueryset [{'category': 'FOOD', 'category_total': Decimal('33.9000000000000')}, {'category': 'GIFT', 'category_total': Decimal('628')}, {'category': 'HOUSE', 'category_total': Decimal('813.880000000000')}, {'category': 'OTHER', 'category_total': Decimal('307')}, {'category': 'RECREATION', 'category_total': Decimal('100')}, {'category': 'SUPERMARKET', 'category_total': Decimal('52.8400000000000')}]> It is possible to accomplish what I want with only one query instead of three? -
Django: How to pass variables from view to a template
I'm having trouble passing a variable from view to an html file. This is what I did so far: My root directory (where the manage.py file is) contains the following folders: myapp myproject templates myproject/urls.py looks like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] myproject/settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, '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', ], }, }, ] myapp/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] templates/index.html: <p>Hello {{ name }}</p> When running the server locally, the only thing it shows is "Hello" without the name. What's wrong? -
Limit Paginator range as to not display all pages
I just implemented a paginator but I don't want to have tons of tabs for each page. I would like it to display five pages and adjust as the user changes pages. view def home(request): p = Paginator(Post.objects.all(), 2) page = request.GET.get('page') post = p.get_page(page) nums = "a" * post.paginator.num_pages context = { 'post':post, 'nums':nums} return render(request, 'blog/home.html', context) template <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if post.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ post.previous_page_number }}">Previous</a></li> {% endif %} {% for l in nums %} <li class="page-item"><a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }}</a></li> {% endfor %} {% if post.has_next %} <li class="page-item"><a class="page-link" href="?page={{ post.next_page_number }}">Next</a></li> {% endif %} </ul> </nav> I followed this stack post but I just cant seem to get it working properly {% for l in nums.paginator.page_range %} {% if l <= nums.number|add:5 and l >= nums.number|add:-5 %} <li class="page-item"><a class="page-link" href="?page={{ forloop.counter }}">{{ forloop.counter }}</a></li> {% endif %} {% endfor %} -
how to set django model field value to automatically calculate a value based on values of other field in the different model
I am trying to figure out how I can make a django field model to automatically populate by summing values of another model's fields. For Example, if I have a model with 2 fields (first, second) and I want to automatically sum them and input them in a other model. enter image description here -
Oauth2-Error 400: redirect_uri_mismatch Django Application Drive API
I actually want to create a web app for downloading and uploading files from Google Drive.But 'Error 400: redirect_uri_mismatch' this error occurs when I work with Google Drive API. I followed Python Quickstart.I have tried this many times but could not solve it. I will benefit if someone helps a little. #quickstart.py from __future__ import print_function import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials SCOPES = ['https://www.googleapis.com/auth/drive'] # If modifying these scopes, delete the file token.json. """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'client_secret_739947871599-3gcc50dnshrspe5g51cvunuar2u9efks.apps.googleusercontent.com.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('drive', 'v3', credentials=creds) # … -
Dynamic Formset, how to update them?
I have this dynamic formset where I add and delete a form by buttons. Every time I add or delete a form I increment or decrement TOTAL_FORMS. It works if I always delete the last element added, but if I delete the first or any one before the last Django doesn't save the form. I know the problem is because each form takes an increasing number and when I delete a form that is not the last this sequence is broken. My question is how to solve this, is it possible to make this change on the backend or just on the frontend? And how to do it? formset This function I use to clone a form and increment TOTAL_FORMS: $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#addRow').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); This function I use to delete the form: function exclude(btn) { divId = $(btn).parent().parent(); $(divId).remove(); var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) - 1); $('#id_form-INITIAL_FORMS').val(parseInt(form_idx) - 1); } Thank you guys! -
Why is this (Django) 'filter' function not working?
I need help to figure out why the filtering doesn't work. It worked until I decided to add pagination using Django official docs and code comes from here.) I tested the query results in Django shell (following the steps in the docs ) and tweaked the code. The pagination itself displays, but instead of 5 items on each page (as specified in the line paginator = Paginator(gem_list, 5), all the items are displayed--and the same on every page. So I'm baffled as to whether the problem is with the filter part, or with the template. #views.py def gem_list(request): # gem_list = Rhyme.objects.filter(is_gem=True) rhyme_list = Rhyme.objects.all() objects= list(rhyme_list) #converting the queryset to a list gem_list = objects.filter(is_gem=True) paginator = Paginator(gem_list, 5) page = request.GET.get('page', 1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) page_range = paginator.get_elided_page_range(number=page) try: page_obj = paginator.get_page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'page_obj': page_obj, 'gem_list' : gem_list, 'paginator' : paginator, 'page' : page, } return render(request, 'rhymes/gem_list.html', context) #template: <div class="container"> {% for gem in gem_list %} <p class="rhyme_list"> <a href="{{ gem.get_absolute_url }}">{{gem}}</a></p> {% endfor %} <ul class="pagination justify-content-center flex-wrap mt-3 mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First</a></li> <li class="page-item"><a … -
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\" …