Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ImportError: cannot import name 'python_2_unicode_compatible'
I'm building a website and I was trying to create a custom user-to-user messaging system so I installed django-messages and maybe a few other things, and suddenly when I tried to run my server I get the following error : Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\mertz\AppData\Local\Programs\Python\Python38\lib\site-packages\django_messages\models.py", line 9, in <module> from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' … -
UpdateView of multiple forms renders sub-form twice
Using crispy-forms. I am using a formset to manage two forms in one submission - an Animal form and a Dog form. They are linked with an animal_id as PK and FK respectively. The CreateView works OK - I get an AnimalForm and a DogForm. I submit, the animal and dog db tables are updated correctly. The UpdateView is causing problems - I of course want to load the existing instance, but when I do that I get one instance of AnimalForm and two of DogForm. One of the DogForms is populated with existing data, the second is empty. When I don't pass an instance into the Update, I get zero renders of the DogForm. The AnimalForm is always OK. models.py class Animal(models.Model): zoo = models.ForeignKey(Zoo, on_delete=CASCADE) animal_id = models.AutoField(primary_key=True) animal_name = models.CharField( max_length=100, verbose_name='Animal Name') class Dog(models.Model): dog_id = models.IntegerField(primary_key=True) animal_id = models.ForeignKey(Animal, on_delete=models.CASCADE) collar_type = models.CharField( max_length=100, null=True, verbose_name='Related CD File') forms.py class AnimalForm(ModelForm): class Meta: model = Animal fields = [ ‘animal_name’] def __init__(self, *args, **kwargs): super(AnimalForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.layout = Layout( Div(Field(‘animal_name’))) class DogForm(ModelForm): class Meta: model = Dog exclude = () DogFormSet = inlineformset_factory( Animal, Dog, form=RavenMetadataForm, fields=[collar_type], extra=1, … -
AttributeError: type object 'Categories' has no attribute 'user_id__isnull' in Django
When i use a queryset in django, i get this error: AttributeError: type object 'Categories' has no attribute 'user_id__isnull' The Categories model has a foreign key on the User model named user. When i use the queryset: _Categories.objects.filter(Q(Categories.user_id__isnull==True ) | Q(user=user))_, I essentially want to do something like this: SELECT * FROM Categories WHERE user_id==NULL | user.id==user.id _(the currently logged in User_ forms.py: from .models import Task, Categories from django import forms from django.forms import ModelForm from django.db.models import Q class TaskForm(ModelForm): task_title = forms.CharField(max_length=100) task_description = forms.CharField(widget=forms.Textarea) due_date = forms.DateTimeField() is_completed = forms.BooleanField() #categories = forms.ModelChoiceField(empty_label="---None---") class Meta: model = Task fields = ['task_title', 'task_description', 'due_date', 'is_completed', 'categories', 'parent'] def __init__(self, user, *args, **kwargs): # Get all the categories from the database for that specifc user super(TaskForm, self).__init__(*args, **kwargs) self.fields['categories'].queryset = Categories.objects.filter(Q(Categories.user_id__isnull==True ) | Q(user=user)) models.py: from django.db import models from django.db.models import Q from users.models import CustomUser from django.urls import reverse from django.contrib.auth import get_user_model class Categories(models.Model): category_type = models.CharField(max_length=50) user = models.ForeignKey(CustomUser, null = True, on_delete=models.CASCADE) def __str__(self): return '%s ' % (self.category_type) def get_absolute_url(self): return reverse('task_list') class Task(models.Model): task_title = models.CharField(max_length=100) task_description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) user = models.ForeignKey(get_user_model(), … -
ModuleNotFoundError: No module named 'tensorflow_core.keras' in Django
I am working opencv and tensorflow with django but I got stucked in this error and I'm not able not fix it. Here are the libraries that I have imported from tensorflow import keras from keras.models import Sequential from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.models import Model from keras.layers.normalization import BatchNormalization from keras.layers.pooling import MaxPooling2D, AveragePooling2D from keras.layers.merge import Concatenate from keras.layers.core import Lambda, Flatten, Dense from keras.initializers import glorot_uniform from keras.engine.topology import Layer from keras import backend as K K.set_image_data_format('channels_first') import cv2 import os import numpy as np from numpy import genfromtxt import pandas as pd import tensorflow as tf -
How to return all data in database as Json?
How to return all data in database as Json? Views.py: class HeroSerializer(serializers.ModelSerializer): class Meta: model = Hero fields = ['Hero_id', 'race', 'age', 'class_'] extra_kwargs = { 'race': { 'required': False, 'allow_null':True }, 'age': { 'required': False, 'allow_null':True }, 'class_': { 'required': False, 'allow_null':True } } def HHH(): h=Hero.objects.all() serializer= HeroSerializer(h) return JsonResponse(serializer.data) But it returns me an error: Got AttributeError when attempting to get a value for field Hero_id on serializer HeroSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'Hero_id'. Any ideas? -
What is difference of customization user model between AbstractBaseUser and AbstractUser
I want to extend and customize built-in django user model. The main reason of customization is that i want to do email field as unique identifier of all users and also i need to add some extrafields to every user. While reading docs i found several solutions to achieve my goal. One of them require inherite from AbstractBaseUser class CustomUser(AbstractBaseUser): pass And another solution require to inherite from AbstractUser class CustomUser(AbstractUser): pass But i didn't understood what is difference of inheritance between AbstractBaseUser and AbstractUser -
Enable user to schedule email
I'm creating a service where a user can send an email at a specified date and time in django,however the problem is how do submit the email form based on the specified time? I have put both date and time fields which the user will use to send the email but cant make the form submit on that specific date. Code: views def send_email(request): if request.method == 'GET': form = EmailScheduleForm() else: form = EmailScheduleForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] recipient_list = form.cleaned_data['recipient_list'] message = form.cleaned_data['message'] from_email = form.cleaned_data['from_email'] date_to_send = form.cleaned_data['date_to_send'] time_to_send = form.cleaned_data['time_to_send'] try: send_time = datetime.datetime(int(date_to_send),int(time_to_send)) time.sleep(send_time.timestamp() - time.time()) send_mail(subject,message,from_email, [recipient_list]) print('email sent') except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('send_email') return render(request, "send_email.html", {'form': form}) #models class EmailSchedule(models.Model): from_email = models.EmailField(max_length=100) recipient_list = models.EmailField(max_length=100) subject = models.CharField(max_length=100) message = models.TextField() date_to_send = models.DateField(default='2012-09-04') time_to_send = models.TimeField( auto_now_add=False, default='06:00Z') date_created = models.DateTimeField(auto_now=True) How can i achieve this based on user input for date_to_send and time_to_send? -
Django migrations by Kubernetes Job and persistent Volume Claim
Is the best approach to make migrations and migrate models using a Job and a Persistent Volume Claim on Kubernetes Django deployed app? -
Django not recognising module import/ app folder
I am following a tutorial to learn some django. I have followed the tutorial and I get the following error: NameError: name'blog' is not defined when i try to run django_project/urls.py. My code is exactly the same as the tutorial- the source code can be found here. My directory structure is as follows: I am running Python 3.7 with Django 1.11.21 in the same directory as the manage.py file. I also have __init__.py in both the blog and django_project folder. I am using a linux VM. What am i doing wrong? -
Cannot resolve keyword 'tag' into field
I am following the book 'Django 2 by example', and when it comes to implementing the tagging system for blog posts I encounter this error: the error is caused when I click on the first-post tag shown here here is models.py from django.contrib.auth.models import User from django.db import models from django.utils import timezone from django.urls import reverse from taggit.managers import TaggableManager class PublishManager(models.Manager): def get_queryset(self): return super(PublishManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') object = models.Manager() # The default manager. published = PublishManager() # My custom manager tags = TaggableManager() # Imported from the library 'taggit' class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse( 'blog:post_detail', args=[ self.publish.year, self.publish.month, self.publish.day, self.slug, ] ) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) list.html {% extends 'base.html' %} {% block content %} <h1>My … -
Django - How do I solve the problem of adding members?
I'm using django-groups-manager. There is a member section. I get an error while recording. I'm missing or making mistakes. Where could it be? TypeError at /accounts/register/ Member() got an unexpected keyword argument 'name' views.py from groups_manager.models import Group, GroupType, Member def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save() new_group_name = form.cleaned_data['new_group_name'] new_group, created = Group.objects.update_or_create(name=new_group_name) user.groups.add(AGroup.objects.get(name=new_group_name)) member = form.cleaned_data['member'] member = Member.objects.create(name=member) user.save() password = form.cleaned_data.get('password1') new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('home') return render(request, 'accounts/form.html', {'form': form, 'title': 'Üye Ol'}) This line problematic: member = Member.objects.create(name=member) -
Django celery group is not executing task even after receiving it when the number of tasks are more than number of cores
I have a main_task (say, G1) which is supposed to execute multiple tasks in parallel (Say T1 to T9 tasks). Worker receives G1 and starts executing it. G1 sends T1 to T9 (9 tasks) to the worker and worker has received all 9 tasks. Worker executes tasks T1 to T8 (first 8 tasks) successfully. Task T9 is received by the worker but does not execute it. After 30 minutes of timeout, G1 (main_task) raises TimeOutError and stops executing. That's when the worker starts executing the task T9. Any help to resolve this would be appreciated. Thanks. django-celery==3.2.2 Python 3.6 def bla(something): # do something @shared_task def main_task(): process_start_time = datetime.datetime.now() job_list = [] for i in i_list: job_list.append(bla.s(i)) job = group(job_list) result = job.apply_async() while result.waiting(): print('waiting..') time.sleep(5) if (datetime.datetime.now() - process_start_time).seconds >= 1800: # 30 minutes timeout return TimeOutError if result.ready(): # do something -
How to imprt django-taggit tag in django-import-export
I can't import django taggit tags using django-import-export. This error is when vlaue is entered. Line number: 1 - invalid literal for int() with base 10: 'def' Also, this error is when value is blank. Line number: 2 - Cannot add <QuerySet []> (<class 'django.db.models.query.QuerySet'>). Expected <class 'django.db.models.base.ModelBase'> or str. xlsx table models.py from django.db import models from django.urls import reverse from taggit.managers import TaggableManager class KnowHow(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(blank=True) file = models.FileField(blank=True,upload_to='explicit_knowhows') free_tags = TaggableManager(blank=True) def __str__(self): return self.title admin.py from django.contrib import admin from import_export import resources from import_export import fields from import_export.admin import ImportExportModelAdmin from .models import KnowHow # Register your models here. class KnowHowResource(resources.ModelResource): class Meta: model = KnowHow exclude = 'id' import_id_fields = ('title', ) @admin.register(KnowHow) class knowHowAdmin(ImportExportModelAdmin): resource_class = KnowHowResource -
Running Keras LSTM Model In Django Returns 'thread._local' object has no attribute 'value'
I am trying to integrate my Keras neural network, otherwise working perfectly, into my Django application. When I run python manage.py runserver, I get 'thread._local' object has no attribute 'value'. Views.py: def index(request): form = forms.InputForm() args = {'form': form} if request.method == "POST": print("checking") form = forms.InputForm(request.POST) if form.is_valid(): print(classify(str(form.cleaned_data['textInput']))) return render(request, 'main_app/UI.html', args) forms.py: from django import forms class InputForm(forms.Form): textInput = forms.CharField(widget=forms.TextInput, label='Enter text for analysis ') def clean(self): all_clean_data = super(InputForm, self).clean() textInput = all_clean_data['textInput'] HTML form code: <div class="container"> <div class="jumbotron"> <form method="POST"> {{ form.as_p }} {% csrf_token %} <input type="submit" class="btn btn-info" value="Click To Analyse"> </form> </div> </div> How do I advance? -
Django error: 'WSGIRequest' object has no attribute 'post' for comments
I'm new to django and I'm working on a blog app and trying to enable comments for posts. When I write comments from admin page everthing works fine, but as a user I get following error: 'WSGIRequest' object has no attribute 'post'. Searching similar problems I see that mostly people switch request.Post for request.POST but I do not have that in my code, I wrote view for comment as a class not as def comment(request)… How do I solve this problem? code from views.py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.user = self.request.user form.instance.post = self.request.post return super().form_valid(form) code from models.py: class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return 'Comment of user {}: {}'.format(self.user, self.content) code from urls.py: path('post/comment/', CommentCreateView.as_view(), name='post-comment'), code from comment_form.html: {% extends "recepti/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New comment</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} -
/bin/bash: line 89: docker: command not found GITLAB CI/CD ISSUE
I am trying to push my code on Gitlab using Gitlab CI/CD but it constantly fails on the push stage giving me the below error. My project: hhttps://gitlab.com/monixm/last-propulsion-project. Any ideas as to what's causing this? Issue taken from the push stage: 1 Running with gitlab-runner 12.6.0-rc1 (ec299e72) 2 on docker-auto-scale 72989761 3 Using Docker executor with image ruby:2.5 ... 00:36 4 Pulling docker image ruby:2.5 ... 5 Using docker image sha256:54cb86b0bcdc353e103e9dd1bff69fcd01e3235420ed17cbf5efac22010b373e for ruby:2.5 ... 7 Running on runner-72989761-project-16138356-concurrent-0 via runner-72989761-srm-1578059087-b5d7ed4b... 00:05 9 $ eval "$CI_PRE_CLONE_SCRIPT" 00:01 10 Fetching changes with git depth set to 50... 11 Initialized empty Git repository in /builds/monixm/last-propulsion-project/.git/ 12 Created fresh repository. 13 From https://gitlab.com/monixm/last-propulsion-project 14 * [new ref] refs/pipelines/106842100 -> refs/pipelines/106842100 15 * [new branch] master -> origin/master 16 Checking out 54a35cd8 as master... 17 Skipping Git submodules setup 21 $ docker login -u "gitlab-ci-token" -p "$CI_BUILD_TOKEN" "$CI_REGISTRY" 00:01 22 /bin/bash: line 89: docker: command not found 26 ERROR: Job failed: exit code 1 -
Customizing django rest auth password reset link to be sent to mobile number
I have not written any code yet.. But I just want an idea of how to go about it. django-rest-auth -
Import (cannot import name 'ResolveInfo' from 'graphql') error when using newest graphene and graphene-django version
I am having some issues with my django app since updating my dependencies. Here is my requirements.txt: aniso8601==8.0.0 asgiref==3.2.3 Django==3.0.2 django-cors-headers==3.2.0 django-filter==2.2.0 django-graphql-jwt==0.3.0 djangorestframework==3.11.0 djangorestframework-jwt==1.11.0 graphene==2.1.8 graphene-django==2.8.0 graphene-django-extras==0.4.8 graphql-core==3.0.1 graphql-relay==3.0.0 pip-upgrade-outdated==1.5 pipupgrade==1.5.2 promise==2.3 PyJWT==1.7.1 python-dateutil==2.8.1 pytz==2019.3 Rx==3.0.1 singledispatch==3.4.0.3 six==1.13.0 sqlparse==0.3.0 I am getting ImportError: cannot import name 'ResolveInfo' from 'graphql' (E:\Ben\GitHub-Repos\dojo-manager\env\lib\site-packages\graphql\__init__.py) I am aware of https://github.com/graphql-python/graphene-django/issues/737 and https://github.com/graphql-python/graphene/issues/546 , none of which seem to solve it in my case. Any help greatly appreciated. -
How to Modify the default Django user table
How to Modify the default Django user table and the custom user table should consist of the 'first name','last name', 'gender', 'Email(Primary Key)', 'phone number' fields. How to do this? forms.py class UserForm(ModelForm): class Meta(): model= User fields = 'First_name','Last_name','Gender', 'email','Phone_number' -
How can save the return path without HTTP_REFERRER?
I have a function based view that I only use to update a session: def admin_privileges(request): // toggle request.session['is_admin'] return Typically I use this to toggle a session variable between True and False. E.g. in a template: <a href="{% url 'admin_privileges' %}">Toggle admin privileges</a> How can I pass a variable and amend return in admin_privileges to return the user to the original view it was requested from? I don't want to use anything on the front end, and I can't use HTTP_REFERRER as it's not always set. I thought of passing something via the URL from the referring view? -
Create a weekly timesheet with Django?
I'm trying to create a weekly timesheet in Django that displays each day of the week with an input field, something similar to this: https://imgur.com/k05kofY I have created a Timesheet model as such: class Timesheet(models.Model): user = models.ForeignKey("authapp.User", related_name="timesheets", on_delete=models.CASCADE) date = models.DateField() duration = models.DecimalField(max_digits=3, decimal_places=1) project = models.ForeignKey(Project, on_delete=models.CASCADE) My question is - how would I dynamically create a form for each week (as the screenshot above)? And how would I properly link each input value to the correct date? -
What is best practice for passing variables via GET?
I am passing a variable in my URL: mydomain.com/app/?next_page=my_page I can get this variable in a view with: def mypage(request): var = request.GET['next_page'] Is it best practice to also change the URL to require next_page? Something along the lines of: path('app/?nextpage=<str>', mypage, name='my_page') What's best practice? If so, what's the correct syntax for this (I know the example is incorrect)? -
Django: Building dynamic Q queries for related tables
I'm trying to filter objects on a table, based on related objects, but having trouble doing so. I have a table Run: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() Each Run object has related table RunValue: class RunValue(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) run_parameter = models.CharField(max_length=50) value = models.FloatField(default=0) In RunValue we store detailed characteristics of a run, called a run_parameter. Things such as, voltage, temperature, pressure, etc. For simplicity's sake, let's assume the fields I want to filter on are "Min. Temperature" and "Max. Temperature". So for example: Run 1: Run Values: run_parameter: "Min. Temperature", value: 430 run_parameter: "Max. Temperature", value: 436 Run 2: Run Values: run_parameter: "Min. Temperature", value: 627 run_parameter: "Max. Temperature", value: 671 Run 3: Run Values: run_parameter: "Min. Temperature", value: 642 run_parameter: "Max. Temperature", value: 694 Run 4: Run Values: run_parameter: "Min. Temperature", value: 412 run_parameter: "Max. Temperature", value: 534 (RunValue.value are floats, but let's keep it to ints for simplicity). I have a two inputs in my page where the user enters min and max (for temperatures). It can be either or, so it's an open ended filter, for example: Min. temperature = 400 Max. temperature = 500 That set of filters should only … -
Python 3.7.3 / Django 3: 'ascii' codec can't encode character '\xe8' in position 17: ordinal not in range(128)
I am running a simple parsing script on Django 3.0.1 and Python 3.7.3 def update (request): try: data = json.loads(api_response.content) output.append (data) dic_data = { "symbol": data['symbol'] , "latestPrice": data['latestPrice'] , "companyName": data['companyName'], "week52High": data['week52High'] , "week52Low": data['week52Low'] , "ytdChange": data['ytdChange'] , "latestTime": data['latestTime'], "changePercent": data['changePercent'] , } for i in dic_data: setattr(local_stock, i, dic_data[i]) print (dic_data[i]) local_stock.save() except Exception as e: api = "%%% DB save Error %%%" print(e) return redirect ("stocks:get_stock") locally on Mac OS X 10.15.1 Python 3.7.5 all works fine without any issue. On the live server (Debian 10) I get (for all stocks with special characters e.g. Esté Lauder) 'ascii' codec can't encode character '\xe8' in position 17: ordinal not in range(128) I did review previous answers (mostly related to old version of Python) and it doesn't seem to have to do with my Python encoding >>> sys.getdefaultencoding() 'utf-8' my locale on the remote server LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" both local and remote version use the same database so it is not related to that either. -
How to make dynamic table using Javascript?
I am trying to create a dynamic html table and i've not been able to do it yet. i will give what ive done and this is the code <table id="myTable"> <tr id="tr"> <th>Students Name</th> <th>Average</th> </tr> {% for student in teacherStudents %} <tr id="tr2"> <td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td> </tr> {% endfor %} </table> <button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus;&nbsp;Insert New Cell</button> <button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">&times;&nbsp;Undo Recent Action</button> <script> var count=0; function doTheInsert() { let header=$.find("tr[id='tr']")[0]; header.append("<th data-id='header'><input type='date'></th>"); let rows=$.find("tr[id='tr2']"); for (let i=0; i<rows.length; i++) { rows[i].append("<td data-id='row'><input type='text'/></td>"); } } </script> what i want is if the teacher click the button it will add textbox under the date, depending on the number of students how many textboxes to add for example i click twice the button Insert New Cell this is the result I want, (i will make static result to clarify what i want) what result ive got