Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to pass initial data Modelformset in form wizard for editing
I can use the modelformset in form wizard normally, and am editing a the existing data, but not able to pass the data using get_form_instance. forms.py: class BaseHostFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseHostFormSet, self).__init__(*args, **kwargs) self.queryset = Host.objects.none() HostFormSet = modelformset_factory( model=Host, form=HostForm, extra=1, formset=BaseHostFormSet ) class HostForm(forms.ModelForm): class Meta: model = Host fields = ['name','ip','os','method','description'] widgets ={ 'name': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'ip': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'os': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'method': forms.Select(attrs={'class': 'form-control','style': 'width:400px;'}), 'description':forms.Textarea(attrs={'class': 'form-control','style': 'width:400px;'}) } urls.py path('create/demo',views.FormWizardView.as_view([HostFormSet,DemoForm,CredFormSet]),name='create_demo'), path('edit/demo/<int:dm_id>',views.FormWizardView.as_view([HostFormSet,DemoForm,CredFormSet]),name='edit_demo'), views.py def get_form_initial(self, step): if 'dm_id' in self.kwargs: return {} return self.initial_dict.get(step, {}) def get_form_instance(self, step): if not self.instance_dict: if 'dm_id' in self.kwargs and step=='0': print("get_form_instance_step0") dm_id = self.kwargs['dm_id'] demo=Demo.objects.get(id=dm_id) host_dict= (demo.host_set.all()[0]) # I can see host object normally here print(host_dict) return host_dict return self.instance_dict.get(step, None) According to the doc: https://django-formtools.readthedocs.io/en/latest/wizard.html I should be able to initialize the step data using get_form_instance, In step 0, I got only the empty values and default values in the model instead of the returned object value. Please help, thanks in advance. -
get() returned more than one HorseEquipment -- it returned 3! in Django RESTApi
I want to make a REST Api GET View in Django using serializers and raw query like this: class HorseEquipmentView(APIView): lookup_url_kwarg = 'horse' def get (self, request, format = None): horse = 1 if horse != None: equipment = HorseEquipment.objects.raw('SELECT H.horse_id, E.name FROM horse_equipment H JOIN equipment E ON H.equipment_id = E.id WHERE H.horse_id =' + str(horse)) serializer = HorseEquipmentSerializer(equipment, many = True) return Response(serializer.data) else: return Response(status = status.HTTP_400_BAD_REQUEST) but on my localhost is returning error "get() returned more than one HorseEquipment -- it returned 3!". What can I change to make it work? -
How to import current login user in to form by form.py Django
I want to automatically add the name of a logged in user to the form but i don't know how to import this varaible to the form FILES >>>> forms.py class CommentForm(forms.ModelForm): class Meta: model = ArticleComment fields = ('user_name', 'body') widgets = { 'user_name': forms.HiddenInput(attrs={'value': username }), 'body': forms.Textarea(attrs={'class': 'form-control'}) } models.py class ArticleComment(models.Model): post = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE) user_name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.user_name) def get_absolute_url(self): return reverse('article', args=(str(self.id))) views.py class AddCommentView(CreateView): model = ArticleComment form_class = CommentForm template_name = 'add_comment.html' # fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['category_id'] return super().form_valid(form) success_url = reverse_lazy('index') -
How can I return a downloadable file Django
I am currently working on a project where I generate both a csv file and a config file. I would like to know if there is a way to have a href in my template that would trigger a download of those files to the user? -
GitHub Actions - Build Docker Image From Latest Branch
I'm new to dev ops and am trying to figure out how to create an automated pipeline that is triggered when our team pushes to the staging branch of GitHub. Right now, I've almost got everything, in that, when we push to staging, we ssh into our server, pull the build, stop the running container, and then start a new one. My only issue right now is that I'm not exactly sure how to pull the docker image from a specific branch on GitHub. I want to do the equivalent of git pull and then restart the docker container. Right now, I've got: - name: Pull new image run: ssh staging 'sudo docker pull ${{ secrets.AWS_ECR_REGISTRY }}/simple-django:latest' - name: Stop running container run: ssh staging 'cd code_folder; sudo docker-compose down -v --remove-orphans' - name: Start new container run: ssh staging 'cd code_folder; sudo docker-compose -f docker-compose.prod.yml up -d --build' but I'm not sure exactly where ${{ secrets.AWS_ECR_REGISTRY }}/simple-django:latest is/what it corresponds to. Does this pull from some sort of GitHub branch? Or do I have to be able to log in as an admin to the AWS server to check out what this corresponds to. Thanks -
Django, React: Static Files with Elastic Beanstalk + S3
I have a standard Django project structure with a React app: main_app settings.py asgi.py etc... tickets models.py views.py etc... react-frontend public/ src/ etc... In react-frontend in the main template index.html, I am loading my static files like so: <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8" /> <link rel="icon" href="{% static 'favicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="{% static 'favicon.svg %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Main App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> When this page appears on my production server, the {% static file/directory %} is loaded fine. However, the JavaScript chunks that npm run build creates is not; they're not loaded with the static path to the S3 bucket, instead being loaded with the standard /static/path/to.js. Is there a way I can have my JavaScript that's added in through npm run build be set to my S3 bucket just like I would with {% static dir/file %}? -
Error while creating an application for Blockchain
I've installed Python 3.6 and Django 2.2.6 used the following code to install virtual environment. ''' pip install virtualenv''' '''virtualenv venv''' '''venv\Scripts\activate ''' After that, I've installed django 2.2.6 and trying create a project and application for blockchain ''' pip install django==2.2.6''' '''django-admin startproject PyChain''' '''cd PyChain''' '''python manage.py createapp blockchain ''' I'm getting the error "No module name : django" -
Django Rest Framework Returns old Data after post_save Signal
I have game,genre and producer tables. User creates new games through admin panel. After user creates a new game i need to do something but i have a problem. After new game has been created django sends signal and runs game_changed method. Problem is when i send get request to /api/game/ (Django rest framework endpoint) after i got signal of new game has been created response doesn't have this new model. More interesting is first i get count of game table through Game.objects.count i get 3 (correct) after that i send get request to game endpoint and response has 2 games. What causes this? Models: class Game(models.Model): name=models.CharField(max_length=50) producer=models.ForeignKey("Producer",on_delete=models.CASCADE) genres=models.ManyToManyField("Genre") def __str__(self): return self.name class Producer(models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name class Genre(models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name Signals: from django.db.models import signals from django.dispatch import receiver from .models import Game @receiver(signals.post_save,sender=Game) def game_changed(sender,**kwargs): print(Game.objects.count())#Returns 3 import requests url="http://localhost:8000/api/game/" response=requests.get(url) print(response.json())# returns 2 games instead of 3 Views: from rest_framework.viewsets import ReadOnlyModelViewSet from .serializers import GenreSerializer,GameSerializer,ProducerSerializer from .models import Genre,Game,Producer class GenreViewSet(ReadOnlyModelViewSet): queryset=Genre.objects.all() serializer_class=GenreSerializer search_fields=("name",) class GameViewSet(ReadOnlyModelViewSet): queryset=Game.objects.all() serializer_class=GameSerializer filterset_fields=("genres","producer") search_fields=("name",) class ProducerViewSet(ReadOnlyModelViewSet): queryset=Producer.objects.all() serializer_class=ProducerSerializer search_fields=("name",) -
Will subprocess.call wait for the entire shell command&function to be finished?
I have a subprocess thats using the call function to run some data collection function. When I run it without shell it will get stuck within a loop and never complete its task. With shell=True it completes its task and doesn't get stuck. Is this because it just waits on the shell command to execute or is the entire function that its supposed to run being run properly? subprocess.call(['python3', f'some_help_function.py', f'--domain=http://localhost:8000'], shell=True) -
{"detail":"CSRF Failed: CSRF token missing or incorrect."} in DRF
I'm getting {"detail":"CSRF Failed: CSRF token missing or incorrect."} error while trying to post a change password API. I'm using postman and please let me know if any more details are needed in the comment section. Thanks in advance. Serializers.py class PasswordChangeSerializer(serializers.Serializer): password = serializers.CharField(max_length=128) Views.py class PasswordChange(APIView): permission_classes = (IsAuthenticated,) serializer_class = PasswordChangeSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = request.user password = serializer.data['password'] user.set_password(password) user.save() content = {'success': _('Password changed.')} return Response(content, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django Rest Framework - Filter by relationship hyperlink
I hope you are well. This is my first personal project with DRF and I had the following problem. I have two models: class Area(models.Model): name = models.CharField(max_length=100) ... and class SubArea(models.Model): area = models.ForeignKey("Area", on_delete=models.CASCADE, verbose_name='Area relacionada', related_name='subareas') name = models.CharField(max_length=100) ... I was able to do something similar to what I need using HyperlinkedRelatedField class SubareaSerializer(serializers.ModelSerializer): contents = ContentSerializer(many=True, read_only=True) quizzes = QuizSerializerAux(many=True, read_only=True) class Meta: model = SubArea fields = ['id', 'name', 'description', 'quizzes', 'contents'] class AreaSerializer(serializers.HyperlinkedModelSerializer): subareas = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='subarea-detail', ) class Meta: model = Area fields = ['url','id', 'name', 'description', 'subareas',] But this is what I get using the endpoint api/area/: { "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/", "id": 1, "name": "Area 1 de teste", "description": "Area 1 de teste - descrição", "subareas": [ "http://127.0.0.1:8000/rest-auth/quiz/subarea/1/", "http://127.0.0.1:8000/rest-auth/quiz/subarea/2/" ] }, I get a list with several links to Subareas, however I need only 1 link that lists all Subareas related to this Area, for example: /api/area/1/subarea endpoint that would list all subareas in area id = 1 { "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/", "id": 1, "name": "Area 1 de teste", "description": "Area 1 de teste - descrição", "subareas": [ "http://127.0.0.1:8000/rest-auth/quiz/area/1/subarea" ] }, how can i do this using the DRF? these are … -
No reverse match "error during template rendering"
Reverse for 'all_products' not found. 'all_products' is not a valid view function or pattern name. <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url "store:all_products" %}">All</a></li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected" {% endif %}> <a class="dropdown-item" href="{{ c.get_absolute_url }}">{{ c.name|title }}</a> </li> {% endfor %} </ul> here is my my def in views.py : def all_products(request): products = Product.products.all() return render(request, 'store/home.html', {'products': products}) my urls.py: from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.all_products, name = 'all products'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ] -
How to make Django show hint's in case password doesn't meet requirements during registration?
Can anyone please tell me how to make Django actually display hints\messages\errors or whatever in case during registration process user's password doesn't meet standart requirements? Because now it is just absolutely silent about that. Here's my form class Registration(UserCreationForm): class Meta: model = User fields = ['username', ] and here's my view def register(request): if request.method == 'POST': form = Registration(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('upload') else: form = Registration() return render(request, 'testapp/temp1.html', {'form': form}) Thank you in advance! -
Reverse comments list in descending order to get the last n (2) objects in django template
I've searched a lot and couldn't find anything to reverse the comment's list in descending order so that I can get the last two comments of each post in the template. Here is my model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py: posts = Post.objects.all().order_by("date_posted").reverse() return render(request, "cs50gram/explore.html", {"posts": posts}) template.html: {% for post in posts %} {% for comment in post.comments.all|slice:":2" reversed %} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The problem here is that it slices first and then reverse.. What have I tried? How to reverse a for loop in a Django template and then slice the result Using the solution presented in the answer, it didn't work for some reason. This is exactly how I tried it in my code. {% for post in posts %} {% for comment in post.comments.all.reverse|slice:":2"%} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The output is that it only slice it without reversing. Any help in reversing the comment's list in descending order and getting the last n (2) comments of … -
OuterRef not looking into outer query
I have the following model schema (only putting here the important variables): class Department(models.Model): name = models.CharField(max_length = 64) class User(AbstractUser): departments = models.ManyToManyField(Department, related_name = 'users', blank = True) date_left = models.DateTimeField(null = True, blank = True) ## date_joined = This is set by default on AbstractUser class Office(models.Model): department = models.ForeignKey(Department, related_name = 'offices', on_delete = models.CASCADE) class Invoice(models.Model): office = models.ForeignKey(Office, related_name = 'invoices', on_delete = models.CASCADE) date = models.DateField(null = True, blank = True) ## nr_workers = The annotation i'm trying to create below And i want to retrieve, for every Invoice date, the number of active users. For example, invoice.date = '2021-04-01' -> nr_workers should be equal to the number of users from that invoice.office.department who joined before 2021-04-01 and, either left after that date, or never left at all. What i've tried so far: from django.db.models import Max, Min, Q, F, Subquery, OuterRef, Value, Count qs = Invoice.objects.all() qs = qs.annotate( dep_pk = F('office__department__pk') ) ## Works fine until here qs.annotate( nr_workers = Count( Subquery( User.objects.filter( departments__pk__in = [OuterRef('dep_pk')] ).values('pk') ) ) ) ## Error - "Cannot resolve keyword 'dep_pk' into field. Choices are: ..." The OuterRef('dep_pk') it's not looking into the qs (it's … -
How to get another related result in a django model
Let's say I have this model in django: class DeviceSensorChange(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE, db_index=True) sensor = models.ForeignKey(DeviceDigitalSensor, on_delete=models.CASCADE, db_index=True, related_name='sensorchanges') time = models.DateTimeField(auto_now_add=True) value = models.BooleanField(default=False) it describes how and when some "sensors" changes in time (a history of binary buttons: on and off). Then there is a ListView filtered by device or by sensor or by time. I want to add another column in the view, that shows the elapsed time since the last change of the same sensor in the same device: it means I should to go back in the table looking for the same device, same sensor, get the time and make the subtraction. Where is the right place to do that? I must not change the model and the information is needed just in the view to help the user, no need to store it. Is it possbile to add a elapsed() function in the model? Or this is something that has to be done in the template? Or in the ListView itself? -
Failing to load static CSS from Django on Azure
I followed this tutorial from DigitalOcean and have this in my settings.py. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') However, after deploying my app, I find that the CSS file's request is canceled as seen in Chrome tools. I still get this error even after running: $ python manage.py collectstatic which gives me files in staticfiles directory for admin and app. Note that I can run all this on localhost with no issue. I tried the suggestion in this answer by switching from /static/ to static/ but ran into the same issue. Given that I want to retain this structure of static files in their respective app directories and don't have CSS files that are not tied to any app, I can't use STATICFILES_DIRS as the documentation says. Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files. -
Pass a GET parameter from HTML and receive in Django View
I'm trying to pass a start date and end date from my html href to my views.py But I can't get the data related the passed date Example: {{ date }} = 2021-05-13 {{ date1 }}= 2021-05-14 HTML: <a href="{% url 'pba_defect_xls' %}? date = {{ date }}, date1 = {{ date1 }}" class="btn btn-success" style="float:right;">Export Excel</a> View: def pba_defect_xls(request): if request.method == 'GET': date = request.GET.get('date') date1 = request.GET.get('date1') print(date) print(date1) URLS: path('pba_defect_xls', pba_defect_xls, name="pba_defect_xls"), Howerver it's printing: date = None, date1 = None The correct output should be: date = 2021-05-13, date1 = 2021-05-14 The aim of this code is retrieve the date to export to excel by xlwt in django Any ideal about this issue? -
How do I solve a Django NoReverseMatch Error?
How do I solve a Django NoReverseMatch Error? When I visit basic_list, I get the error "Reverse for 'manage_account' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['manage_account/(?P[0-9]+)/$']" but all the other links are working. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', {'warning': "Invalid login"}) else: return render(request, 'myapp/login.html') def view_basic_list(request): wine_objects = Wine.objects.all() return render(request, 'myapp/basic_list.html', {'Wines':wine_objects}) def manage_account(request, pk): a = get_object_or_404(Account, pk=pk) return render(request, 'myapp/manage_account.html', {'a': a}) basic_list.html {% extends 'myapp/base.html' %} {% load static %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <table class="table table-striped"> <thead> <th scope="col"> Name </th> <th … -
JsonField in Django for MySQL
I currently use django 3.2 and MySQL as database, I want use MySql Json Field. For this reason use django-mysql third party package in my project. After create model got this Warning: (django_mysql.W004) django_mysql.models.JSONField is deprecated. HINT: Use django.db.models.JSONField or django-jsonfield-backport instead. If i use django.db.models.JSONField as json field, django use specific MySQL's JsonField ? Dose any effect on preformance? Which one has best performance on database? -
How to change the URL structure of already Google Indexed Django Website?
I have a Website built in Django. The blogs posts of my website have the url https://saralgyaan.com/posts/. But due to extensive posting on Facebook, it banned the url https://saralgyaan.com/posts/ (I still can post https://saralgyaan.com on Facebook). So, I was wondering, if I could remove the posts from my URL, I would be able to share my posts on Facebook. I need to change the URL structure to this effect. But my website is already indexed on Google and I get organic search landing on almost 10 pages, so I don't want to disrupt that. I was wondering If somehow I could use the RedirectView to redirect https://saralgyaan.com/ to https://saralgyaan.com/posts/. Is it possible? Will Facebook allow me to post or it will detect the redirect URL and again stop me from posting it. My urls.py of application is from django.urls import path, re_path from .views import( posts_search, posts_create, posts_detail, posts_edit, posts_delete, show_category, tag_posts, posts_publish, category_create ) urlpatterns = [ path('', posts_search, name='search'), path('create/', posts_create, name='create'), path('category/', category_create, name='category_create'), re_path(r'^category/(?P<hierarchy>.+)/$', show_category, name='category'), # path('category/<slug>/', show_category, name='category'), path('<slug>/', posts_detail, name='detail'), path('<slug>/edit/', posts_edit, name='edit'), path('<slug>/publish/', posts_publish, name='publish'), path('<slug>/delete/', posts_delete, name='delete'), path('tags/<tag>/', tag_posts, name='tag_posts') ] And the urls.py of the project is urlpatterns = [ … -
ValueError at /profile/ ModelForm has no model class specified. Error django
Iam coding in django and trying to figure how to update profile of a user in my app Please help me Iam trying to learn how to code and this is a big barrier for me to learn here's models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) image = models.ImageField(default='default.jpg',upload_to="profile_pics") def __str__(self): return f'{self.user.username} Profile' here's my views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get("username") messages.success(request, f'Yor account has been created! You are now able to login') return redirect('/login') else: form = UserRegisterForm() return render(request, 'users/register.html',{'form': form}) @login_required def profile(request): u_form = UserUpdateForm(instance = request.user) p_form = ProfileUpdateForm(instance= request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) Iam getting error at 'u_form':u_form, and This is my forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1','password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = … -
What is the best way to conditionally set the choices of a `serializers.ChoiceField` based on the value given to another field
Let's assume I have a choice field named chart. If the user inputs 'line' for the chart field, the following operations should be accepted: min, max, avg, and sum. If the user inputs 'pie' for the chart field, the following operations should be accepted: count and top-count. from rest_framework import serializers CHARTS = ['line', 'pie'] CHART_OPERATIONS = { 'line': ['min', 'max', 'avg', 'sum'], 'pie': ['count', 'top_count'], } class ChartDataSerializer(serializers.Serializer): chart = serializers.ChoiceField(choices=CHARTS) # operation = serializers.ChoiceField(choices=CHART_OPERATIONS[chart]) -
How to access heroku config vars using javascript in order to pass to Square Payment?
I am trying to add Square's Web Payment SDK to my site. I am using latest python, Django and hosting on Heroku. I need to access the APPLICATION_ID and LOCATION_ID which will be stored in Heroku Config Vars. These are required in order to display the card payment form on my site. I know javascript cannot access them and the only solution I have seen requires setting up a templatetag and having the input="hidden" in the HTML. How to access environment variable from html or js in Django Square provides the following code to include in my HTML however, I cannot simply replace APPLICATION_ID with its value in the text as it must be kept secret and I dont want it in the DOM. <body> <form id="payment-form"> <div id="card-container"></div> <button id="card-button" type="button">Pay</button> </form> <!-- Configure the Web Payments SDK and Card payment method --> <script type="text/javascript"> async function main() { const payments = Square.payments(APPLICATION_ID, LOCATION_ID); const card = await payments.card(); await card.attach('#card-container'); async function eventHandler(event) { event.preventDefault(); try { const result = await card.tokenize(); if (result.status === 'OK') { console.log(`Payment token is ${result.token}`); } } catch (e) { console.error(e); } }; const cardButton = document.getElementById('card-button'); cardButton.addEventListener('click', eventHandler); } main(); </script> … -
Variables reset when render a piece of html
i´m very new using django and in programming itself and i'm having some trouble rendering properly my templates. I managed to create a live search from my oracle DB using Ajax and JQuery. Currently i'm trying to add the names that my live search brings into an array and then pass it to the back end and do some more stuff with it but each time i search a new name, my array is emptied. Also if my livesearch brings more than one result, each time i try to add it to my array, it creates a new one instead of adding it This are my templates: base.html <!DOCTYPE html> <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"> <script></script> <title></title> </head> <body> {% block content %} {% endblock %} </body> {% load static %} <script src="{% static "jquery/jquery.js" %}"></script> <script src="{% static "jquery/plugins/jquery.cookie.js" %}"></script> <script> $(document).ready(function () { $("#livesearch").on('input', function (e) { e.preventDefault(); search_text = $("#livesearch").val() // console.log(search_text) $.ajax({ method: 'post', url: 'livesearch/', data: { text: search_text }, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken')); }, success: function (res) { $("#results").html(res); console.log(res) } }) }) $("#agregar_usuario").click(function (e) { e.preventDefault(); let user_picked = $("#users option:selected").text(); var users_to_be_added …