Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django python request start point - tracing a request from start to finish
This is with related to django in general. I am trying to debug this weird issue in django 2.2/python 3.7. If i set DEBUG=True, i am getting response for all my urls. But if i set DEBUG=True, all urls are throwing 404. I have tried all the existing django solutions like setting ALLOWED_HOSTS etc. But nothing is working. So just wanted to trace the request from start to finish. For example when we enter the url in browser and hit enter what will django do? Which views and methods will be called till a final response is rendered on screen. -
How to Add Chat Between Users in My Django Web Application?
i developing an simple bloger with django now i need to create chat between users in My site -
restore backup of django models reference each other using pg _restore
Faced a problem while restoring pg_restore data, I have two models in django: class Project(models.Model): previewScreenId = models.ForeignKey("Screen", related_name='project_preview', on_delete=models.SET_NULL, default=None, null=True, blank=True) class Screen(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) When restoring data, pg_restore throws an error that the secondary key data is not present in the linked table. Thus, I am stumped and have no idea how I can restore the database. I've tried using arguments like --data-only or -t content_screen, but that doesn't help. pg_restore: while PROCESSING TOC: pg_restore: from TOC entry 3550; 0 17205 TABLE DATA content_screen sergey pg_restore: error: COPY failed for table "content_screen": ERROR: insert or update on table "content_screen" violates foreign key constraint "content_screen_project_id_b836412d_fk_content_project_id" DETAIL: Key (project_id)=(5427) is not present in table "content_project". pg_restore: warning: errors ignored on restore: 1 -
Hiding milliseconds from timezone.now() (In HTML)
I am building a BlogApp and I am implementing a feature of expiring post so the post will hide in 2 days, So I am showing user the remaining time in post. Remaining time is showing perfectly BUT It is also showing milliseconds (which i I am trying to hide) The Output is like :- 2 days, 23:43:33.271449 views.py from django.utils import timezone from datetime import timedelta def blogpost_detail(request,blogpost_id): blog = get_objects_or_404(BlogPost,pk=blogpost_id) remaining_time = blog.blog_date_added - timezone.now() + timedelta(days=2) context = {'remaining_time':remaining_time,'blog':blog} return render(request, 'blogpost_detail.html', context} What i am trying to show as output :- I am trying to show like :- 2 days 23 Hours Remaining What have i tried :- I tried Python/Django timestamp including milliseconds Post's Answer by dividing 1000 but when i divide timezone by 1000 like timezone.now()/1000 then it is keep showing unsupported operand type(s) for /: 'datetime.datetime' and 'int' Then i tried hiding milliseconds from template by using time:"h:i a" like {{ blog|time:"h:i a" }} But it is showing nothing as output. Any help would be much Appreciated. Thank You in Advance -
django: how to update models
I want the update a model in django this is a model in models.py: class Article(models.Model): CATEGOTY = ( ('programming', 'programming'), ('other', 'other') ) title = models.CharField(max_length=100, null=False) content = models.TextField(null=False) category = models.CharField(max_length=100, choices=CATEGOTY, null=False) creation = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title for example i want to add slug in this model like this: slug = models.SlugField(max_length=100, null=False) but when i display py manage.py makemigrations; this is shown to me: Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py what should I enter if I select option 1? if i type datetime.date.today() It gives me an error that says: TypeError: function missing required argument 'year' (pos 1) -
Django Dev Server - sleep(N) in Middleware makes requests sleep multiple N seconds
Working on a middleware that slows down dev server response time. To simplify it I've created a very simple example that measures get_response time and then sleeps so the whole request cycle takes approximately 2 seconds. The problem is that when there are multiple requests sent at once, some of them sleep 2xN time (not just a little bit longer, it's multiplicated). I assume it's because of limits of Django's dev server concurrency. Is it possible to make it work? class SnailMiddleware: """ Middleware that throttle responses """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request: HttpRequest): start = now() response = self.get_response(request) elapsed_time = (now() - start).total_seconds() time.sleep(2 - elapsed_time) return response These are the times: Do you know where is the problem and how to make it work? -
How do you mock an object in a list?
I have the following function: signature_request = client.send_signature_request_embedded_with_template( client_id=self.CLIENT_ID, template_id=self.template_id, title=self.title, subject=self.email_subject, message=self.message, signers=self.signers, custom_fields=self.custom_fields ) signature_id = signature_request.signatures[0].signature_id I cannot for the life of me mock the signature_id value in my test. I know that I am properly mocking the correct target because I am successfully mocking another return value from this signature_request object. Any help would be highly appreciated! I have tried the following: send_request_mocked.return_value.signatures.return_value= [PropertyMock(signature_id='signature_id')] send_request_mocked.return_value.signatures.return_value= [Mock(signature_id='signature_id')] etc. -
Django pythonanywhere JS not running
I've made a tally counter at http://fr0gs.pythonanywhere.com/tools/tally-count I've made buttons and script tags, but interestingly, the button's JS execute and the script tag's doesn't!! -
Create a many-to-many item in-line from a django form
I have to two models Directors and JobProject. A JobProject can have multiple directors through a many-to-many relationship. Currently, when I create a new JobProject I choose from the directors I have saved who the director will be. However, I am trying understand how can I code a form/view for creating a JobProject where I can also create a director in-line (in case I don't have the director already saved in the DB). In the admin there is a way to click on green + and open a pop-up, but the same process might not work for my use-case so I was hoping there was a way to create a form that allow users to: Start entering a JobProject details. If the director already exist in the DB - Great If the director doesn't exist, allow users to enter the details of a new director object (probably using Java?) in-line Users go ahead and finish entering JobProject details. Users click save and the BE first save the new director and then save the new project with director pointing at the newly created director. I basically have 1,2,4,5 figured out but I can't understand how to do 3. Any help? These … -
How to remove all permissions from a user in Django Guardian?
I'm trying to reset my user permissions to assign new objects permissions to my user. how to achieve that ? For Example: having 3 chained models School & Grade & StudentRecord Models.py: class School(models.Model): name = models.CharField(_("Name"),max_length=50) # other fields ... def __str__(self): return self.name class Grade(models.Model): code_name = models.CharField(_("Name"),max_length=50) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') # other fields ... def __str__(self): return self.code_name class StudentRecord(models.Model): code_name = models.CharField(_("Name"),max_length=50) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="student_records") # other fields ... def __str__(self): return self.code_name When I give a User as a Manager the perms (add,change,view,delete) for all objects of models which belong to specific school that User manage. If I need to change the Manager (User). I need to reset all permissions and reassign for all related objects of this specific school. How To Acheive This Approach? any support will be appreciated. -
Unit test for Django Update form
I do not understand how to manage updates on forms and related unit tests and I would really appreciate some advises =) I have a Company model, and related very simple CompanyForm: class CompanyForm(forms.ModelForm): company_name = forms.CharField(label="Société", disabled=True) class Meta: model = Company exclude = [] The view is very simple too: @user_passes_test(lambda u: u.is_superuser or u.usercomp.is_admin) def adm_options(request, comp_slug): ''' Manage Company options ''' company = Company.get_company(comp_slug) comp_form = CompanyForm(request.POST or None, instance=company) if request.method == "POST": if comp_form.is_valid(): comp_form.save() return render(request, "polls/adm_options.html", locals()) This view works fine, I can update information (it's actually not used for creation, which is done thanks to the Django Admin panel). Unfortunately, I'm not able to build unit tests that will ensure update works! I tried 2 ways, but none of them worked. My first try was the following: class TestOptions(TestCase): def setUp(self): self.company = create_dummy_company("Société de test") self.user_staff = create_dummy_user(self.company, "staff", admin=True) self.client.force_login(self.user_staff.user) def test_adm_options_update(self): # Load company options page url = reverse("polls:adm_options", args=[self.company.comp_slug]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, "0123456789") self.assertEqual(self.company.siret, "0123456789") # Options update response = self.client.post( reverse("polls:adm_options", args=[self.company.comp_slug]), {"siret": "987654321"} ) self.assertEqual(response.status_code, 200) self.assertContains(response, "987654321") self.assertNotContains(response, "0123456789") self.assertEqual(self.company.siret, "987654321") In this case, everything is OK but the latest assertion. … -
django picture save SuspiciousFileOperation
{SuspiciousFileOperation}The joined path (\.\con) is located outside of the base path component (C:\ig_db\media) The filename I try to save is 'con.soluciones' once changed to 'consoluciones' I don't get this error. Filename can be with "." in windows. -
Python/Django app where urllib is blocked on Azure
I am very new to Azure, so please go easy on me here. I recently deployed a Python/Django app onto Azure. In the app, I use the Python library urllib to retrieve a file on the internet via its URL. I know the code is correct because the app works locally, but when I deploy it on Azure, the request is met by a 403 error which crashes the app: urllib.error.HTTPError: HTTP Error 403: Forbidden Reading around, it seems that Azure blocks urllib requests. So, I created a custom Web App Firewall (WAF) policy where I disabled all firewall rules, and miraculously the app started working! This is obviously not a permanent solution, so I'm asking if someone can help with one of the following, any of which should solve my issue: Can someone tell me specifically which rule, from this Pastebin list, is the one blocking urllib requests? I can't find any documentation or description, beyond the short label, that explain what they do? Is there a way I can create a WAF exclusion for urllib requests? Is there an alternative to using urllib that doesn't run into Azure firewall issues? Once again, I am very new to how … -
Razor pay order_id and payment signature empty
I am trying to integrate Razor pay in my Django App, but the problem is on POST request my order id and verification signature, both are empty, I tried to search resources but I am having trouble understanding where is the issue lies, guess where I am wrong in this, i have also implemented both GET and POST to the gateway on the same page, also I am only making a place order entry when i am getting a response from Razor Pay <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "{{my_key}}", // Enter the Key ID generated from the Dashboard "amount": parseInt("{{request.session.order.cart_total}}")*100, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", // "order_id": "{{order_id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "callback_url": "{{call_back_url}}", "prefill": { "name": "{{request.session.user.first_name}}", "email": "{{request.session.order.contact_info.email}}", "contact": "{{request.session.order.contact_info.mob_no}}" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script> my model @csrf_exempt def checkout(request): #process order zipcode= request.session['order']['delivery_info']['zip_code'] quantity= request.session['order']['order_details'][0]['quantity'] total_price = request.session['order']['cart_total'] shipping_details = … -
How to change a list conaining Longitude/Latitude to a list containing Latitude/Longitude - Django?
I searched for hours on the internet to find a solution but without success. The polygons are displayed on the map but not in their actual position because the longitude is diplayed as latitude and the latitude as longitude. Please, is there a solution to change the position of latitude and longitude in the list? Please, see printed result below. models.py: from django.contrib.gis.db import models from django.contrib.auth.models import User from django.contrib.gis.db.models import PointField, MultiPointField, MultiPolygonField class BurnedArea(models.Model): firedate = models.DateField() country = models.CharField(max_length=80) place_name = models.IntegerField() province = models.CharField(max_length=80) yearseason = models.FloatField() geom = MultiPolygonField(srid=4326) visible = models.BooleanField(default=False) @property def lat_lng(self): return list(getattr(self.geom, 'coords', [] ) [::-1] ) print(self.lat_lng) def __str__(self): return str(self.place_name) views.py: def viewer(request): resultba = [] pol2 = 0,0 areas = BurnedArea.objects.all() for ba in areas: balon = str(ba.lat_lng) pol = balon.replace("(", "[") pol2 = pol.replace(")", "]") print(pol2) resultba.append({'pol2':pol2}) context = { 'resultba':resultba, { return render(request, 'app_web/viewer.html', context) printed result : [[[[8.6065550282249, 36.8027181091122], [8.60768086453233, 36.8020611860536], [8.60746659932254, 36.8016392882169], [8.60734205760659, 36.8011823076919], [8.60600897419624, 36.8016267925537], [8.6064362319159, 36.8019699263144], [8.6065550282249, 36.8027181091122]],]] but I want to have it like this : [[[[36.8027181091122, 8.6065550282249], [36.8020611860536, 8.60768086453233], [36.8016392882169,8.60746659932254], [36.8011823076919, 8.60734205760659], [36.8016267925537, 8.60600897419624], [36.8019699263144, 8.6064362319159], [36.8027181091122, 8.6065550282249]],]] viewer.html: <section class="mapid" id="mapid" ></section> <script> {% for area in … -
how to create django model from json response
Im creating a django app which show some btc prices that I get then from a external api, my problem comes when the app is gonna load it need to always make a call to the api to show me data so it takes very long time for the app to load or even when i want to make some changes on the website the app needs to make a call to the api wait for the response so after that it can show me a data, My goal at this time it will be to save that json response into a Django model so the app wouldn't have to be calling the api all the time so the website will load faster. so my questions is which one it will be the best way to archive that? or how can i even try to do that? Views.py def index(request): form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect("index") tasks = Task.objects.all() context = { "task_form": form, "tasks": tasks, "precio_uk": get_price_uk(), "average_uk": get_average_price_uk(), "precio_ves": get_price_ves(), "average_ves": get_average_price_ves(), } return render(request, 'index.html', context) urls.py urlpatterns = [ path('',views.index,name="index"), path("update/<int:pk>", views.update_task, name="update_task"), path("deleted/<int:pk>/", views.delete_task, name="delete_task"), path('multi',views.multiplication, … -
Problem with Telegram webhook on production server
I'm developing Telegram bot based on pyTelegramBotAPI and Django. There is initial code: import json import time from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import telebot from django.conf import settings if settings.DEBUG: WEBHOOK_HOST = 'https://zzzz.ngrok.io' bot = telebot.TeleBot('zzzz') else: bot = telebot.TeleBot('zzzz') WEBHOOK_HOST = 'https://example.com' WEBHOOK_URL = '/telegram_webhook/' @bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to( message, "Привет! Кажется, мы еще незнакомы. Твой номер: "+str(message.chat.id) ) @bot.message_handler(func=lambda message: True, content_types=['text']) def echo_message(message): bot.reply_to(message, message.text) @csrf_exempt def webhook(request): print(request.body.decode('utf-8')) update = telebot.types.Update.de_json(json.loads(request.body.decode('utf-8'))) bot.process_new_updates([update]) return JsonResponse({'message': 'OK'}, status=200) bot.remove_webhook() time.sleep(1) bot.set_webhook( url = WEBHOOK_HOST + WEBHOOK_URL, ) When I running code locally with ngrok it works well, but when I run it on production server, bot just dont answer on messages. https://api.telegram.org/botZZZZ/getWebhookInfo returns {"ok":true,"result":{"url":"https://example.com/telegram_webhook/","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"194.0.0.0"}} But if I curl production enpoint with request: curl --tlsv1.2 -v -k -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{ "update_id":10000, "message":{ "date":1441645532, "chat":{ "last_name":"Test Lastname", "id":1111111, "first_name":"Test", "username":"Test" }, "message_id":1365, "from":{ "last_name":"Test Lastname", "id":1111111, "first_name":"Test", "username":"Test" }, "text":"/start" } }', "https://example.com/telegram_webhook/" I will receive some answers from telegram bot and error: Traceback (most recent call last): File "/usr/lib/python3.8/json/decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 20 column 2 (char 332) Now I … -
How Django authentication flow works? [a particular case]
I am reading some code found on the Internet, and trying to make sense of it. I don't understand how authentication works here. Here is the code snippets. the root URLConf urlpatterns = [ path('admin/', admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")) ] Then if we look at authentication.urls, we will see this: urlpatterns = [ path('login/', login_view, name="login"), path('register/', register_user, name="register"), path("logout/", LogoutView.as_view(), name="logout") ] Somehow it ends at 'login/' and login_view handles it. I don't understand why? Ok, then if we open login_view: def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) we can see that in case of successful authentication, it redirects to "/", which as I understand it, should create a loop. Because, when you go to http://localhost:8000 the first " ", include("authentication.urls")) will match it. And it all starts again. When and why "", include("app.urls") will match? When "", include("authentication.urls") matches, where does 'login/' come from? Redirecting to "/" in login_view() … -
statement failing under try
I'm absolutely baffled by this issue and was wondering if you could help out. This code works in my dev environment, but when I push it to my production server, the statement under 'try' fails and, despite this, the system doesn't even attempt the statement under 'except'. I've probably written 10,000 try/except statements and I've never seen anything like this. try: user_profile = Profile.objects.get(user=kwargs['instance']) except: user_profile = Profile.objects.create(user=kwargs['instance'], busemail=kwargs['instance'].email) Under what circumstances would the system not attempt to execute the except statement? Thanks! -
Typeahead Bloodhound Autocomplete using prefetch + remote when source is a dict from Django
Bloodhound variable for Typeahead that's working nicely: var egDjangoVar = new Bloodhound({ queryTokenizer: Bloodhound.tokenizers.whitespace, datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), remote: { url: '/ajax/eg/%QUERY.json', wildcard: '%QUERY', filter: filterdata } }); We added dict parsing function filter: filterdata because Django requires JSON to be sent as a dict for security: function filterdata(data){ return $.map(data.results, function(results,index){ return results.value; }) } All works beautifully. We now want Prefetch functionality and have added: prefetch: { url: '/ajax/prefetch.json', wildcard: '%QUERY', filter: filterdata }, This doesn't work, despite '/ajax/prefetch.json' serving expected dict. We think it may be due to dataTokenizer issues discussed in this answer, but we don't understand why the tokenizer should differ between remote and prefetch sources, and the suggested datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value)}; didn't work when adding it as an argument of prefetch. We've found that __/ajax/prefetch.json__data in local storage is saved with dict keys matching values like {"datums":{"Apple":"Apple","Banana":"Banana","Orange":"Orange"},"trie":{"i":[],"c":{}}}, whereas the remote data directly viewed is like {"results": [{"value": "Apple"}, {"value": "Banana"}, {"value": "Orange"}]}. Is this unexpected? I'm new to front end / JS, so please forgive me if this is a stupid question. What are we doing wrong? -
Shared models between two projects and ForeignKey to unused model that exists only in one of them
I have two Django projects that communicate with each other. The first one contains model A and B that has a ForeignKey to A. The first project sends and receives serialized B objects from the second project. I want the second project to contain just B, but it needs the value of that ForeignKey. These models are defined as follows: class A(models.Model): ... class B(models.Model): fk = models.ForeignKey(to='A', on_delete=models.PROTECT) ... The problem is that ForeignKey to A in model B requires model A to be defined in the second project. Its objects also have to exist so that the database is consistent and there are no problems, e.g., in the admin panel. In the end, I'd like to treat the fk field as a full-fledged ForeignKey in the first project and as some kind of read-only generic identifier in the second one. I would like to have the same code base for the model in both projects to ensure databases in the two projects stay synchronized. How can I achieve this in a clean way? -
Django AWS S3 Media Files Issue
I’ve faced an issue while implementing S3 storage with Django application. Uploading the images through the Django admin panel to the S3 media folder works fine. However, I cannot retrieve the images from the S3 media folder (that is public) because of NotImplementedError: This backend doesn't support absolute paths. Please consider my files. Thank you for your support and attention. settings.py from pathlib import Path from dotenv import dotenv_values import os import dj_database_url config = dotenv_values('.env') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'tu!q^j1ft%s2ohw%+p=@bjb%1l7wm!3_8%(7so^rxm)+rsj9d6' DEBUG = True LOGIN_REDIRECT_URL = 'dashboard' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # AWS S3 'storages', # Apps 'app_profiles', 'app_catalog', 'app_purchases', 'app_api', ] 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', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' AUTH_USER_MODEL = 'app_profiles.CustomUser' # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': config['DB_NAME'], # 'USER': config['DB_USER'], # 'PASSWORD': config['DB_PASS'], # 'HOST': config['DB_HOST'], # 'PORT': config['DB_PORT'], # } # } DATABASES = {'default': dj_database_url.config(default='postgres://ecommerce:Django_ecommerce123@localhost/ecommerce')} AUTH_PASSWORD_VALIDATORS = [ … -
Do I need the Django "sites" framework to build a sitemap for a single-site django project?
According to the Django sitemap framework docs, to be able to use the sitemaps framework, you need to: Make sure you’ve installed the sites framework. However, the "sites" framework docs say this about the "sites" framework: Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way. The way I see it is that the two docs are contradicting each other. Sitemaps docs say "sites" should be used, and "sites" docs say to use "sites" only for multi-site projects. So, my question is do I need "sites" for my single-site project? By single-site I mean I have one single domain and I will not be having duplicated content. -
python requests image upload fails to drf
import json import requests user_f = open('categories.json',) users = json.load(user_f) media_api = 'http://127.0.0.1:8000/api/categories/' files=[ ('category_image', ("Traditional-Art.png", open("Traditional-Art.png",'rb'),'image/jpeg')) ] json = { "category_name": "cat", "category_description": "desc", "user": 16 } headers = { "Accept": 'application/json, text/plain, */*', "enctype":"multipart/form-data" } response = requests.request("POST", media_api, headers=headers, data=json, files=files) print(response.json()) Here, i am trying to upload image to django rest-framework and getting below error `{u'category_image': [u'Upload a valid image. The file you uploaded was either not an image or a corrupted image.']}` this works when image is jpg format but, not working in png . Am i missing anything or do i need to modify something ? Please take a look -
how to use variable in function name?
I want to create function as per number of entries in table. <script> console.log({{count_id.id}}) for (let i = 1; i =< {{count_id.id}}; i++) { num = i function attendance_present + num() { document.querySelector('#present').textContent = "Present" document.querySelector('#present').classList.remove("btn-outline-danger") document.querySelector('#present').classList.remove("btn-outline-warning") document.querySelector('#present').classList.add("btn-outline-primary") } function attendance_absent + num() { document.querySelector('#present').textContent = "Absent" document.querySelector('#present').classList.remove("btn-outline-primary") document.querySelector('#present').classList.remove("btn-outline-warning") document.querySelector('#present').classList.add("btn-outline-danger") } function attendance_half_day + num() { document.querySelector('#present').textContent = "Half-day" document.querySelector('#present').classList.remove("btn-outline-primary") document.querySelector('#present').classList.remove("btn-outline-danger") document.querySelector('#present').classList.add("btn-outline-warning") } } </script> the {{count_id.id}} coming from views in django.