Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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\" … -
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