Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement method from Model to form
I have in my models.py method of Model: class Book(model.models): ... def generate_tag(self): return f'{self.inspection.series_of_tags}-{str(self.tag_number).zfill(7)}' I want to implement this method in my form when I push on update view it generate new tag: class TagForm(core.ModelForm): def save(self, commit=True): instance = super().save(commit=False) if self.cleaned_data['tag_number']: instance = Book.generate_tag(self.instance) if commit: instance.save() return instance class Meta: model = Book fields = ( 'tag_number', ) my views.py class BookUpdateView(BookViewMixin, core.UpdateView): form_class = TagForm template_name = 'book.html' I want that when I click update view - my field 'tag number' will give method from model 'generate_tag' when I save my Form!What I am doing wrong in my code? -
Need help creating search view and how to apply in the HTML page from DB that I created - Django
I am building a website with DJANGO where people put words and association how to remember the word. I built the part of inserting the word. I am now stuck in the part of implementing the word search and extracting the information from the DB. def Search_word(request): search = request.POST.get("search", False) if search in Words.English_word: return HttpResponseRedirect("/polls/") else: return HttpResponseRedirect("/polls/") -
Problems with using built-in postgres database with Django
I'm trying to use built-in postgres database with django according to the instruction: https://docs.djangoproject.com/en/3.2/ref/databases/#postgresql-notes When running the server I get the error: django.db.utils.OperationalError: fe_sendauth: no password supplied How should I define the database credentials in this case (I'm expecting that the build-in database is just created at server startup, thus I could give any...)? I've also been trying to use postgres database running in a docker container. I got the same error though I think I was using the correct credentials: docker pull postgres docker run -e POSTGRES_PASSWORD=pw -e POSTGRES_USER=pg -d postgres and my django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pg', 'USER': 'pg', 'PASSWORD': 'pw', 'HOST': '127.0.0.1', 'PORT': '5432', 'TEST': { 'NAME': 'mytestdatabase', } } } python manage.py runserver 8030 ... conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "pg" -
Django, Foreign key not getting filled with session data
im trying to fill my foreignkey (employer) with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: class JobCreate(CreateView): model = Job form = JobCreateForm() form_class = JobCreateForm context = {} success_url = reverse_lazy('jobsview') def POST(self,request): if request.method == 'POST': form = JobCreateForm(request.POST) if form.is_valid(): job = form.save(commit=False) job.employer = request.user job.save() context = {} return render(request, 'jobs/jobs.html',context) else: context = {} return render(request, 'jobs/job_form.html',context) Model: class Job(models.Model): employer = models.ForeignKey(User, related_name='employer', on_delete=CASCADE,blank=True) employees = models.ManyToManyField(User, related_name='employees2user',null=True,blank=True) title = models.CharField(max_length=200,) description = models.CharField(max_length=200,null=True,blank=True) category_id = models.ManyToManyField(Category,blank=True) skill_id = models.ManyToManyField(Skill,blank=True) approved = models.BooleanField(default=False) # img = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): # Default value return self.title HTML: {% extends "jobs/layout.html" %} {% block content %} <h3> Job</h3> <div class="container"> <div class="jobform"> <form action="" method="POST"> {%csrf_token%} {% for field in form %} <label for="{{field.id_for_label}}">{{field.html_name}}</label> {{field}} {% endfor %} <p>Ctrl in houden om meerder te selecteren</p> <button type="submit" class="btn btn-dark btn-space">Submit</button> </form> </div> </div> {%endblock%} -
Getting error when trying run test “RuntimeError” Database access not allowed
I have some celery tasks running in my project. I want to write some tests for tasks using pytest factories. But each time i pass a task to my test i give me error Getting error when trying run test “RuntimeError” Database access not allowed. Here is code example def send_orders(): for order in Order.objects.all(): order.send() order.sent = True class OrderFactory(....): amount = 100 sent = False def test_send_orders(order): send_orders() assert order.sent -
While using Redirect in django , Login required decorator is not working
view.py @login_required def Loginup(request): if request.method == 'POST': regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' email = request.POST.get('email') password = request.POST.get('password') bad_chars = "!#$%^&*()[]{'}-+?_=,<>/" parameters = [email, password] filtered_parameters = [] for i in parameters: a = ''.join(c for c in i if c not in bad_chars) filtered_parameters.append(a) checking = Client.objects.all().filter(Email=filtered_parameters[0]) checking1 = authenticate(request, Email=email, Password=password) pop = ([i for i in checking.iterator()]) for enc in checking: value = D256(filtered_parameters[1], enc.Password) if value != False: for check in checking: request.session['id'] = check.id request.session['email'] = check.Email # REDIRECT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> response = redirect('/home/%s' % encrypt(check.id)) set_cookie(response, check.Name, check.Password) response.set_cookie( 'echo-AI', [check.Email, check.Password]) return response else: messages.success(request, 'check the details') return redirect('login/') return render(request, 'login.html') setting.py: LOGIN_URL = 'supers:login' url.py(app): from django.urls import path from supers import views app_name = 'supers' urlpatterns = [ path('', views.Index, name='index'), path('signup/', views.Signup, name='signup'), path('login/', views.Loginup,name='login'), path('home/<str:id>',views.Home,name='home'),] url before useing @login required: http://127.0.0.1:8000/home/Z0FBQUFBQmhFWFJBRVdnLWxUNHRKeFNhaWZPYi1oN3hQUVF5cE5CSTRIbTdMZkdUcXFlbFNYeFl0alB3ZGtvSFVKcDVDRnQ0UkRCdWxrMkFSVGxYUG5FVWF1V2t3MU5JdEE9PQ== url after useing @login required: http://127.0.0.1:8000/login/?login/=/home/Z0FBQUFBQmhFWFBNM2JWUXhIdzRwTWdWcDVUYUZMZ191WGg3OG5OUE9YaEFOaDdLeF9zR1FEODYtM3p0Zlh0VjlobWoyMmlycmphY0lXdDdGNDRYUEZtMVhkOHA1TXowc0E9PQ%253D%253D so i tried a example project : (its woring while using render) def Login(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') print('User1:::::::::::::::::::::::::::::::', email) print('User2:::::::::::::::::::::::::::::::', password) data = Client.objects.filter(Email=email, Password=password) if data: return render(request, 'home.html') return render(request, 'login.html') return render(request, 'login.html') @login_required def Home(request): return render(request, 'home.html') @csrf_exempt def Logout(request): … -
Same datetime being saved in different Drf endpoint calls
I'm using datetime.now() and somehow the same date and time up to the second is being saved on my postgre db on different api calls. This would occur for around 5+ times a few minutes apart before changing to another date. What could be causing this? I have this up on a remote Dev server with nginx and uwsgi. For now, i'm saving the record then getting the updated_at value (which is always correct). I'm using the following settings. I've also tried timezone.now(). In addition to the problem above, i've noticed that the datetime i get is a hours early (datetime.now()) or minutes early (timezone.now()). On my local machine, this problem doesn't seem to occur. Any help would be appreciated. Thanks! LANGUAGE_CODE = 'en-us' USE_I18N = False USE_L10N = False USE_TZ = True TIME_ZONE = 'Asia/Manila' -
how to add non existing language to my django website - invalid token in plural form
i'm trying to add (kurdish) language to my django app , but settings.LANGUAGES doesnt support kurdish (ku) code , i also tried to use rosetta ( ROSETTA_LANGUAGES ) which have kurdish in their languages website list , but it also not show in my template <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> languages </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <li> <a class="dropdown-item" href="/{{lang.code}}/"> {{lang.name_local}}</a> </li> {% endfor %} </ul> </li> and this is my settings.py from django.conf import global_settings import django.conf.locale from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ku' #ROSETTA_LANGUAGES = ( # ('en',_('english')), # ('ar',_('arabic')), # ('ku',_('kurdish')) #) LANGUAGES = ( ('en',_('english')), ('ar',_('arabic')), ('ku',_('kurdish')) ) ROSETTA_WSGI_AUTO_RELOAD = True EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku","kurdish"] LOCALE_PATHS = ( os.path.join(BASE_DIR,'locale/'), ) is there something else i have to add to the settings please ? thanks in advance .. -
Django migration passed but field did not get deleted
I have a django application in production, last week I wanted to delete a field from my user model, review_rate, to replace it by a M2M relation with another table. The resulting migration is: # Generated by Django 2.2.1 on 2021-07-20 16:41 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0080_auto_20210708_1539'), ] operations = [ migrations.SeparateDatabaseAndState(state_operations=[ migrations.CreateModel( name='Rate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'api_project_reviewers', }, ), migrations.RemoveField( model_name='user', name='review_rate', ), migrations.AlterField( model_name='project', name='reviewers', field=models.ManyToManyField(related_name='review_project', through='api.Rate', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='rate', name='project', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Project'), ), migrations.AddField( model_name='rate', name='user', field=models.ForeignKey(limit_choices_to={'reviewer': True}, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]) ] It works fine locally. When I deploy it, I can see that my migration exists and pass with the showmigrations command, however, when I want to add a user I get this exception: null value in column "review_rate" violates not-null constrain. If I go to my container, choose any user and try to get review_rate on it I get this error as expected: AttributeError: 'User' object has no attribute 'review_rate' SO the review_rate field does not seem to be deleted as it should, BUT my new rate field exists.. Could someone explain how to … -
How to combine two Model fields to get a common json data in DJANGO?
I'm new to DJANGO , I am trying to combine three models to get a common listing. What i have done is it will get JSON result for each models from database based on the URL given. Eg: Model1 having fields like id,name,date Model2 having fields like id,name,date Now im getting result for these two models are like for Model1 `{ "id": "1", "name": "test", "date": "9-Aug-2021" }` similarly Model2 also. I'm done this with rest-api for Django. Now i want to combine these two models to get a common result. How can we do this in django. -
How to get data from dynamic html table in django.?
I have table with 3 columns and rows will be added dynamically depending on of subjects count. 1column is label and others 2 are input fields. How would I get table data after post, into views.py function ? Html table <form method="POST" action= "{% url 'save_report' %}"> {% csrf_token %} <table id="myTable"> <tr> <th> SUBJECTS </th> <th> Full Marks</th> <th> Marks OBTAINED</th> </tr> {% for subject in subjects %} <tr> <td> <label type="text" id="a" name="a"> {{subject.subject_name}}</label></td> <td> <input type="number" id="b" name="b"/></td> <td> <input type="number" id="c" name="c"/></td> </tr> {% endfor %} <button type="submit" onclick= "{% url 'message_page' %}" name="save" id="save">save </button> My views.py def save_report(request): if request.method=="POST": Full_marks= request.POST.get("b") Print(Full_marks) #check Obtained= request.POST.get("c") Print(Obtained) #check else: Do Stuff Here in save_report() function in views.py I'm getting only last entered value of the input field. I'm trying to save table inputs into database as it is. Any guidance is appreciated. Please.. -
how to convert format of my .pdf file to .txt in Django
I am working on a Django web-application, where I want to convert .pdf and .docx files to .txt . I wrote a save() function where I want to get the file and then convert it into .txt format . But it is giving me the error that : FileNotFoundError at /post/new/ [Errno 2] No such file or directory: 'Python String.pdf' my models.py is : from django.db import models from django.contrib.auth.models import User from django.urls import reverse import PyPDF2 import os # Create your models here. class FileUpload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def save(self, *args, **kwargs): if self.file: pdffileobj = open(str(self.file.name), 'rb') # this is where i want to get the file but it give me the error pdfreader = PyPDF2.PdfFileReader(pdffileobj) x = pdfreader.numPages pageobj = pdfreader.getPage(x + 1) text = pageobj.extractText() file1 = open(self.file.name.txt, "a") file1.writelines(text) super(FileUpload, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home') The conclusion is I want to convert my .pdf to .txt before saving it . Thank you -
Getting error while try to login in django admin database
after running the server when I try to login Django admin page I'm getting this error "unable to open database file". here is the important part from my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / "db.sqlite3"), } } How to solve this problem? -
How to put Original File to Django
I am using Reactjs as FrontEnd, Django as Backend. I am trying to push image as original file by using Antd but it doesnt work all of remain fields are posted but image is not. It return null, sometimes return error 404 this is my state: const [state, dispatch] = React.useReducer(newAvatar, { status: 'idle', clear: false, message: null, fileImg: [], users: '', initialValues: { username:'', //user.username, email:'', // user.email, name:'',// user.name, phone:'',// user.phone, birthday:'',// user.birthday, gender:'', //user.gender, address:'', //user.address, image:'',// user.userImage, } }) const [form] = Form.useForm() const history = useHistory() const authenticate = useAuthenticate() const userid =user.id; and this is my onfinish const onFinish = async values => { let formData = new FormData() for (const key in values) { formData.append(key, values[key] ?? '') } formData.append('userId', user.id) formData.append('name',values.name) formData.append('username',values.username) formData.append('phone',values.phone) formData.append('birthday',values.birthday) formData.append('gender',values.gender) formData.append('address',values.address) formData.append('email',values.email) // if(values.image!= null) { // formData.append('userImage',values.image) // } // state.fileImg.forEach((file, i) => formData.append(`images${i}`, file)) try { await axios.patch(`/api/users/${userid}/`, formData, { headers: { Authorization: `Bearer ${cookies['gp_token']}` } }) .then(res => { console.log(res.data) authenticate({user: res.data, token: cookies['gp_token']}) }) form.resetFields() dispatch({ type: 'upload_success' }) } catch (error) { dispatch({ type: 'upload_fail' }) } finally { window.scrollTo(0, 0) modal.destroy() } } please support me thank all of you a … -
Change Column Name on html table created via pandas
I created a panda dataframe from django models. A table was created. I want to rename the column names which are in th tag. How can I do it? Here is what come. Image is in the link. https://ibb.co/s1VxRF2 @login_required def totaldonation(request): payments = Payment.objects.all().values() df = pd.DataFrame(payments) dada = { "df": df.to_html(index=False, classes='table').replace('border="1"','border="0"') -
how break a celery task inside task
I an using celery with django.inside a forloop , each turn a value sets in db for a relationship lawyers=Lawyer.objects.filter(consultation_status=True) for idx,lawyer in enumerate(lawyers): if(consultation.lawyer): break change_offered_lawyer.apply_async((id,lawyer.id),countdown=idx*60) each turn in the loop inside task i check the condition and my goal is if the condition terminated then break all those tasks. @app.task def change_offered_lawyer(consulation_id,consulator_id): consulation=ConsultationOrder.objects.get(id=consulation_id) consulator=Lawyer.objects.get(id=consulator_id) if(consultation.lawyer): #break all tasks consultation.offered_lawyer=consulator consultation.save() -
Page not found error when clicked on the image url coming in the get api in Django
I have a simple get api built using Django Rest Framework. It is getting all the food items from the model, Menu. It consists of an image field. The api response is successful and I am getting an image URL in the image field, but when I click on that url, the image is not shown in the new tab. I have done a few projects and as far as I remember, it should show the image on the new tab. Due to this, the image is not shown in the frontend which is done in Reactjs. The backend in served in Heroku for now. The url is similar as follows: https://example.herokuapp.com/api/menus The api response in local is as follows: And when I click on the both image and image_url, it shows the follows: I added image_url just to see if it works, but it didnt work as well. My model: class Menus(models.Model): category = models.CharField(max_length=50,choices=CATEGORY,default='main courses') food_name = models.CharField(max_length=100,blank=True, null=True) image = models.ImageField(upload_to='media/pictures',null=True) rating = models.FloatField(blank=True, null=True) description = RichTextField(blank=True, null=True) price = models.FloatField(blank=True, null=True) My serializers: class MenusSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') def get_image_url(self, obj): request = self.context.get('request') image_url = obj.image.url return request.build_absolute_uri(image_url) class Meta: model = Menus fields … -
The current path, products/new/, didn't match any of these - Page Not Found
I just installed python 2.2.20 and now when running a Django project I get a page not found error. I'm not sure why I'm getting this error when I try to navigate to products/new -
django - choices from __init__ are not loading in the form
I am using __init__ to build my form choices from parameters passed from the view. It looks like my choices are built correctly when I do print(choices), but the form is not loading any choices. There isn't even a widget for it showing. I do not get any errors. I've used similar code in other views which worked, which is one reason why this one is really confusing me. I did see that print("ok") never gets printed to the shell, while print("else") does get printed view def newobjtoassess(request, assess_pk): user = request.user assessment = Assessment.objects.get(pk=assess_pk) course_pk = assessment.course.pk context['assessment'] = assessment form = ObjToAssessmentForm(user=user, course_pk=course_pk) if request.method == 'POST': print("ok") form = ObjToAssessmentForm(request.POST, user=user, course_pk=course_pk) if form.is_valid(): f = form.cleaned_data objective = f.get('objective') assessment.objectives.add(objective) assessment.save() return HttpResponseRedirect(reverse('gradebook:assessupdate', args=[assess_pk])) else: context['form'] = form return render(request, "gradebook/newobjtoassess.html", context) else: print("else") form = ObjToAssessmentForm(user=user, course_pk=course_pk) return render(request, "gradebook/newobjtoassess.html", context) form class ObjToAssessmentForm(forms.Form): objective = forms.ChoiceField(label='Learning Objective', choices=[]) def __init__(self, *args, **kwargs): user = kwargs.pop('user') my_course = kwargs.pop('course_pk') super(ObjToAssessmentForm, self).__init__(*args, **kwargs) choices=[(o.id, str(o)) for o in Objective.objects.filter(user=user, course=my_course)] print(choices) self.fields['objective'] = forms.ChoiceField(choices=choices) template {% extends 'base-g.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div … -
How to verify a client side certificate in django?
I am new to django and working on my first project. The requirement I have infront of me is of mutual authentication for client and server. I am not able to figure out how to verify the client side certificate. It is generated using openssl and we don't have a domain yet. I am using Windows OS and django3.2.5. Will I have to setup Nginx for it? Or can it be done without it? Because I think I cannot setup Nginx on Windows without docker or Linux VM. Any help will be greatly appreciated. Thank You in advance. -
url to fetch with parameter for django view
I'm facing a problem with my javascript code when trying to use AJAX instead of href link. I need to hit a django url that looks like this (Django 2.2): path('one-time/<str:product_url>/', OneTimeProductView.as_view(), name='one_time_product') the origial code in the django template was: <a href="{% url 'one_time_product' product %}">{{product}}</a> I now want to use ajax call to make the whole process opened inside of a modal. In my javascript code my fetch function looks like this: function handleAccess(){ var url = "{% url 'one_time_product' product %}" ; fetch(url, { method: "POST", headers: { "X-CSRFToken": '{{csrf_token}}', "Accept": "application/json", "Content-Type": "application/json" } }) .then (response => { response.json(); }) .then (data => { console.log(data); }) }; I know i'm missing something related to the params in the url variable but I just don't know how to add it properly so that i fit the url path. This is the error that I get when I hit the button NoReverseMatch at /one-time/ Reverse for 'one_time_product' with no arguments not found. 1 pattern(s) tried: ['one\-time\/(?P<product_url>[^/]+)\/$'] How should I write the url in the fetch function ? I will appreciate and anyone can point me into the right direction here. Thanks -
Ids incremented twice during import-export (Django)
I am using Django-import-export library, I am facing problem while uploading data in json/csv file. when I upload data file via django-admin, id field increases twice? how to solve this problem? thanks -
TemplateDoesNotExist at / boards/home.html
I'm creating my first site with Django and following a tutorial. Tutorial here. The trouble I'm having is when attempting to load the site using the standard http://127.0.0.1:8000/, I get the error TemplateDoesNotExist at / boards/home.html Django says it's trying to follow this path: "C:\Users\myuser\Desktop\Development\myproject\myproject\boards\templates\boards\home.html (Source does not exist)" When I put that path directly into my file explorer it loads the file with no issues. Here is my urls.py: from django.urls import path from boards import views urlpatterns = [ path('', views.home, name='home'), path('admin/', admin.site.urls), ] And my views.py: from .models import Board def home(request): boards = Board.objects.all() return render(request, 'boards/home.html', {'boards': boards}) And settings.py has 'boards' (the name of the app) under the INSTALLED_APPS heading. My file structure is like so: I hope somebody can help. Just ask if I've missed anything. -
Can't get a true if conditional to trigger in Django Template
I'm trying to stylize my different blog post tags by running an if conditional that simply checks for the name of the tag and executes the style I want for that specific tag. It appears the condition should check True, but only the code under the else clause is being executed. In the example below, my "News" tag should have the class badge badge-primary, but instead it's falling under the else and applying badge badge-secondary. I've tried upper and lower case. I've also tried with and without the counter, which is there for other purposes. Still, no luck. Template: {% for tag in object.tags.all %} {% if forloop.counter|divisibleby:"2" %} {% if tag == "News" %} <li> <span class="badge badge-primary">{{ tag }}</span> </li> {% else %} <li> <span class="badge badge-secondary">{{ tag }}</span> </li> {% endif %} {% endif %} {% endfor %} When replacing: {% if tag == "News" %} With: {% if tag in object.tags.all %} It works, and the tag will populate the first span class as it should. I believe this tells me that the syntax I'm using is correct. For some reason my == conditional isn't being seen True, even though it should be. To check things … -
how to store recent data and after that when i call function again then the previous and recent data addition of both gets store
here what i want to do is when i search something add that thing in my list then that data shown in the 'myTable1' add after that when I enter some numbers in its coresponding input then that data is store in veriable and after that output is shown in next page in next page also if i select some data and its value and add this and last values and then show the output on this new list. And in my code can fetch data in first time but in second time it is not adding the last list only showing the newest one. plz help me and also explian this why this is happening. thanks in advance. <body> <div class="container"> <div class="tabble"> <div class="col"> <div> <label class="ac_trigger" for="ac1"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search For Food Names.." title="Type in a name"> &nbsp;<i class="fa fa-search"></i> </label> </div> <br> <div class="ac_container" id="div1"> <table id="myTable"> <tr class="header" id="heading" style="display: none;"> <th style="width:80%;">Name</th> <th style="width:20%;padding: 4px;">Select</th> </tr> {% for a in foodlist2 %} <tr style="display: none;"> <td>{{a|title}}</td><td style="text-align:center"><input id="btn" type="button" value="Add" name="{{a}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td> <td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td> </tr> {% endfor %} </table> </div> <div class="ac_container"> <table id="myTable1"> …