Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WinError 10061 Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение Django
Знаю, много форумов на эту тему в Инете, но либо я тупой, либо рещения не подошли. Пытаюсь сделать деплой написанного сообщения, используя Channels. Всё бы работало как следует, если бы новое сообщение сохранялось в БД. Для этого я пытался напрямую импортировать модели в cunsomers но там вилетает ошибка. Сейчас я хочу пост запрос кинуть, но не выходит. settings.py: from pathlib import Path import os, sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*v_b!0syzph7hda)gml0rlks2vep8iydlj5r7v+dk$s_6l777u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'Chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ] 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 = 'ShibGraph.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_ROOT, '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 = 'ShibGraph.wsgi.application' ASGI_APPLICATION = 'ShibGraph.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', } } # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases … -
Django - M2M relations on save model
I have a Django Model that I use as Job for exporting the entire list of Users to a csv file. Now I'm trying to do some modifications to this Job to make it possible to export a list of Users filtered by a few criteria such as Gender, DOB, Country, etc. This is my model for the ExportUsersJob: class ExportUsersJob(models.Model): name = models.CharField(max_length=255, verbose_name=_('Name')) from_dob = models.DateField(blank=True, null=True, verbose_name=_('Filter by Date of Birth, from')) to_dob = models.DateField(blank=True, null=True, verbose_name=_('Filter by Date of Birth, to')) gender = models.ForeignKey(Gender, on_delete=models.PROTECT, blank=True, null=True, verbose_name=_('Filter by Gender')) countries = models.ManyToManyField(Country, blank=True, verbose_name=_('Filter by Country')) csv = models.FileField(upload_to=users_export_bucket, blank=True, null=True, verbose_name=_('CSV')) state = models.CharField(max_length=64, default='creating', choices=JOB_STATE_OPTS, verbose_name=_('Job state')) created_at = models.DateTimeField(blank=True, null=True, verbose_name=_('Created at')) completed_at = models.DateTimeField(blank=True, null=True, verbose_name=_('Completed at')) def __str__(self, *args, **kwargs): return self.name def save(self, *args, from_job=False, **kwargs): if from_job: return super(ExportUsersJob, self).save(*args, **kwargs) self.state = 'creating' self.created_at = timezone.now() super(ExportUsersJob, self).save(*args, **kwargs) from_dob = str(self.from_dob) if self.from_dob else None to_dob = str(self.to_dob) if self.to_dob else None gender = self.gender.pk if self.gender else None countries = [c.pk for c in self.countries.all()] # This will query the DB and print the results in a csv file export_users.delay(self.pk, from_dob, to_dob, gender, countries) The … -
django |safe template not working properly
django |safe template not working properly I tried to use a textarea as rich text in django admin, all good, but when I try to show in front with {{ date|safe }} it only shows a maximum height of poximate 200 cm which doesn't allow to show all the text I already read the Django docs article. I do not know what to do. display in front https://i.stack.imgur.com/SzjF5.png code html {% block content %} <div style="height: 1000vh; " > {{ personaje.bio|safe }} </div> {% endblock %} use summernote for this rich text box https://i.stack.imgur.com/stHIT.png I had used it before but I don't know what the problem is -
How to create record when click on button
I'm trying to convert lead to an account in a crm app. From my lead detail template, if i click "Convert" button, it need to add new row in account table with few information from the leads. I tried to pass value using id to view so I can filter the lead object using the ID and then add those values in account table. kindly note that, i have written views code with my limitted knowledge on Django. It maybe completely wrong. I have tried many options and read many post, but i couldnt figure it out. model: class Lead(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) annual_revenue = models.IntegerField(null=True, blank=True) company_name = models.CharField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) city = models.CharField(max_length=30, null=True, blank=True) country = models.CharField(max_length=30, null=True, blank=True) description = models.TextField(max_length=255, null=True, blank=True) class Account(models.Model): account_name = models.CharField(max_length=30, null=True, blank=True) # company name from Lead annual_revenue = models.IntegerField(null=True, blank=True) phone = models.CharField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) Views: class LeadConvert(generic.CreateView): def get_success_url(self): return "/leads" def ConvertLead(self, **kwargs): lead = self.queryset account = Account.objects.create( account_name = lead.company_name, annual_revenue = lead.annual_revenue, website = lead.website ) account.save def get_queryset(self, **kwargs): queryset = Lead.objects.filter[id == id] return queryset urls path('lead/converted/<int:pk>', … -
Is there a way to create a Django migrations not in the last position?
suppose that this is the migrations history to my project: [X] 0001_initial . . . [X] 0010_auto_20211202_0923 [X] 0011_auto_20211202_1050 [X] 0012_auto_20211202_1240 [X] 0013_auto_20211202_1522 [X] 0014_auto_20211202_1534 [X] 0015_auto_20211202_1555 [X] 0016_auto_20211202_1567 . . . [X] 0021_data_migration I would like to create a new migration in the middle of the history, between 000_13 and 000_14. -
How do I get clean data from foreign-key model's field in django?
I have two models class Tennx(models.Model): this_a = models.CharField(max_length=100) And class reed(models.Model): ten = models.ForeignKey(Tennx) tennxname = #get data from this_a How can I get clean data from Tennx model's this_a field? -
Apache2 Ubuntu Default Page after pointing my domain
I deployed my python Django-web app to a Linux Ubuntu server. I used the linode reverse DNS and it worked fine. My website was live on the Linodes reverse dns ip. So I pointed my DNS to the server and now when I go to my domain name it give me the : Apache2 Ubuntu Default Page I eddited my Django settings to this ( I hidded private information for privacy) : ALLOWED_HOSTS = ['www.mydomainname.com', '172.xxx.19.xxx'] and I also updated my : /etc/apache2/sites-available/mysite.conf and I modified the linodes Reverse DNS for my domain name <VirtualHost *:80> ServerName mydomainname.com ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> What I am missing? Any idea ? -
Was such an error observed at log out in Django?
I do not fix That. TypeError: logoutUser() missing 1 required positional argument: 'request' -
what widget we give to URLFIELD in django
what widget we give to URLField in forms django i wanna set placeholer and some class to input link = forms.URLField(widget=forms.????) -
Filtring queryset for a current week using Django and Chart.js
How to filter django queryset for a current week using Django and Chart.js? In my program below, the result obtained only displays the information concerning the event of the last day of the current week. def area_chart_week(request): labels = [] data1 = [] data2 = [] data3 = [] today = datetime.datetime.now() current_year=today.year current_month=today.month current_week = date.today().isocalendar()[1] queryset = Even.objects.filter(date__week=current_week).filter(date__year=current_year).filter(date__month=current_month).values('date').annotate(date_positif=Sum('positif')).annotate(date_negatif=Sum('negatif')).annotate(date_null=Sum('null')).order_by('-date') for rm in queryset: labels.append(rm['date']) data1.append(rm['date_positif']) data2.append(rm['date_negatif']) data3.append(rm['date_null']) return JsonResponse(data={ 'labels': labels, 'data1': data1, 'data2': data2, 'data3': data3, }) -
Django Creating a new post, but it belongs to none
Creating a new checklist, the checklist get created but I have to go inn admin panel to set what task it belongs to. The task is a foreignkey in the checklist. views.py def project_detail(request, slug): ''' Detailed view of given project ''' context = {} project = get_object_or_404(Project, slug=slug) tasks = Task.objects.filter(task_completed=False, project=project) context.update({'project': project}) checklist_form = ChecklistForm(request.POST or None) if request.method == "POST": # Create new Checklist if 'save_new_checklist' in request.POST: if checklist_form.is_valid(): print("\n\n New checklist form is valid") author = Profile.objects.get(user=request.user) new_checklist = checklist_form.save(commit=False) new_checklist.user = author new_checklist.checklist = tasks new_checklist.save() return redirect('project_detail', slug=slug) context.update({ 'tasks': tasks, 'checklist_form': checklist_form, 'title': tasks }) return render(request, 'projects/tasks.html', context) models.py class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() project = models.ForeignKey(Project, blank=True, null=True, related_name='task', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def __str__(self): return self.title class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) description = models.TextField(default="Checklist description") task = models.ForeignKey(Task, blank=True, null=True, related_name='checklist', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, … -
React do not hit Django API on kubernetes
I have a django drf API and a react APP in a cluster kubernetes. My API is not exposed (i cannot expose it because of security conditions). React APP is exposed with an ingress. React need to consume Django API (via axios). But it seems that axios requests are made by browsers so api service is unreachable. Need someone already faced this issue? Thanks in advance! Gauthier -
ReportLab problem with addEntry for Django
I have a problem with addEntry in ReportLab, not adding chapters to table of contents only displays "Placeholder for table of contents 0", I don't know why. This is my first ReportLab test and I started with Django. Chapter generation works, only TableOfContent remains.I have a problem with addEntry in ReportLab, not adding chapters to table of contents only displays "Placeholder for table of contents 0", I don't know why. This is my first ReportLab test and I started with Django. Chapter generation works, only TableOfContent remains. from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer #from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from django.http import HttpResponse, HttpResponseBadRequest #from io import BytesIO from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm, inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex #from reportlab.lib.pagesizes import letter, A5 from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT PAGESIZE = (140 * mm, 216 * mm) BASE_MARGIN = 5 * mm def generatePDF(request,id): pdfmetrics.registerFont(TTFont('Berylium', 'resources/fonts/Berylium/Berylium.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBd', './resources/fonts/Berylium/Beryliumbold.ttf')) pdfmetrics.registerFont(TTFont('BeryliumIt', './resources/fonts/Berylium/BeryliumItalic.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBI', './resources/fonts/Berylium/BeryliumboldItalic.ttf')) registerFontFamily('Berylium', normal='Berylium', bold='BeryliumBd', italic='BeryliumIt', boldItalic='BeryliumBI') PAGE_HEIGHT=defaultPageSize[1] PAGE_WIDTH=defaultPageSize[0] book = Book.objects.get(id=id) Title = book.title pageinfo = book.title Author = … -
Django testing: test fails on create view with post request
I am building test for my views and I am unable to build correct one for generic CreateView. I am following this documentation mostly: https://docs.djangoproject.com/pl/4.0/topics/testing/advanced/#django.test.RequestFactory Does anyone have sollution for this? blog.models class Post(models.Model): title = models.CharField(max_length=128) intro = models.TextField() content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('blog:post-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title blog.views class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'intro', 'content', 'category'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) blog.urls app_name = 'blog' urlpatterns = [ path('post/new/', views.PostCreateView.as_view(), name='post-create'), # some other paths,] blog.tests.test_views class PostViewsTests(TestCase): def setUp(self): self.author = User.objects.create_user( username='abcUser, email='abcuser@mail.com', password='abcpassword') self.category = Category.objects.create(name='New test category') self.new_post = Post.objects.create( title='Lorem Ipsum', intro='Neque porro quisquam est ', content='There is no one who loves pain itself...', author=self.author, category=self.category) self.client = Client() self.factory = RequestFactory() def test_post_create_view_if_adds_new_post(self): data = { 'title': 'Lorem Ipsum2', 'intro': 'Neque porro quisquam...', 'content': 'Neque porro quisquam... - There is no...', 'category': self.category } request = self.factory.post(reverse('blog:post-create'), data=data) request.user = self.author response = views.PostCreateView.as_view()(request) newest_post = Post.objects.order_by('-date').first() self.assertEqual(response.status_code, 200) self.assertEqual(newest_post.title, 'Lorem Ipsum2') test's result: Found 6 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). … -
Asynchronous Amazon Transcribe speech2text display transcripts with Django
I'm trying to build a fullstack web app with AWS Transcribe service and Django and Python. What I want to achieve is something like displaying transcripts from speaker in real time word by word. A demo can be found here: https://www.loom.com/share/f49e8d2b264a4c9b8803a7b0612d103f?t=0 The AWS Transcribe sample code can be found: https://github.com/awslabs/amazon-transcribe-streaming-sdk/blob/develop/examples/simple_mic.py But I'm having trouble displaying the text line by line. What I can achieve so far is I can allow the user to speak for 10 seconds and then display the whole transcript on a web page. See my code below: # Create your views here. def home(request): return render(request, 'aws_transcribe_model/home.html') def startVideoChat(request): t1 = threading.Thread(target=startTranscribing) t1.start() t1.join(10.0) print("\n ------------------------------------ \n") print("transcribing finished") print(CONSTS.transcript) return render(request, 'aws_transcribe_model/startvideochat.html', {'transcript': CONSTS.transcript}) def startTranscribing(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(sample_Amazon_Transcribe_simple_mic.basic_transcribe()) loop.close() I've been looking into things but have not found a solution how to display the text line by line. As you can see in method startVideoChat I can only return once with the html file. Is there a simple way to do this? -
Django can't save a form to specific Model
after messing around with the code for an hour, I have to ask you. So I have a model called Ticket where someone can open a ticket and it will be send to the admin. Now I tried to add a feature so that the user and admin can write messages in this ticket. My try: \\views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) waiting_message = "Mark as 'Waiting'" solved_message = "Mark as 'Solved'" if obj.reopened_counter > 5: solved_message = 'Ticked solved forever' waiting_message = 'Ticked solved forever' button_form = TicketSolved(request.POST) time.sleep(2) if button_form.is_valid: obj.reopened_counter += 1 if obj.reopened_counter > 5: obj.ticket_waiting = True obj.ticket_solved = False if obj.ticket_waiting == False and obj.ticket_solved == True: obj.ticket_waiting = True obj.ticket_solved = False else: obj.ticket_waiting = False obj.ticket_solved = True obj.save() user_form = TicketMessagesForm( request.POST, instance=TicketMessages(#no idea what to do hea# maybe id=id?#)) if user_form.is_valid(): instance = user_form.save(commit=False) # something to save the user message instance.save() return render(request, 'ticket-system.html', {'obj': obj, 'waiting_message': waiting_message, 'solved_message': solved_message, 'button_form': button_form, 'user_form': user_form}) The useless button_form is just because I didnt know how to handle to forms, two Post requests. You can ignore this ticket_waiting/ticket_solved thing. Important is the the TicketMessageForm. This form is just for the … -
Django ModelViewSet It takes a long time to display requests on the screen
I measured how many seconds it takes to prepare the data for the request, 4 seconds came out. In the browser, the request is displayed only after 20 seconds. What could this be related to? views.py class ProductImproveView(ModelViewSet): filterset_class = ProductFilter serializer_class = ProductListingSerializerLightImproved def get_queryset(self): return { 'qs': Product.objects.all()[:30], 'count': Product.objects.all().count() } def list(self, request, processed_queryset=None, *args, **kwargs): start_time = datetime.now() result = self.get_queryset() queryset = result['qs'] count = result['count'] serializer = self.get_serializer(queryset, many=True, context={'request': request}) d = serializer.data g = JsonResponse({ 'count': count, 'next': 'nd', 'results': d }) print(g.content) print(datetime.now() - start_time) # 4 seconds return g urls.py router = DefaultRouter() router.register(r'products-improve', ProductImproveView, basename='products') urlpatterns = [] urlpatterns += router.urls -
Django Model Form Integer as Drop Down
I have a simple Model form in my project as follows: class InviteForm(forms.ModelForm): class Meta: model = Invite fields = ['max_guests', 'rsvp_guests', 'rsvp_attendance'] Max Guests is just an integer and appears for the user to type in. As the value is always small (<10), I would like this to be a dropdown instead with all values 0-max. Is there a way to overwrite an integer input as such? -
Django Form Field Max not Setting from Instance
I am trying to provide my form in Django a dynamic max value based on the model instance it is being passed (such that the user cannot set more guests than the model has stored they are allowed). I do not run into any errors but this max just does not take effect (I am able to put and save what ever in there). Beyond using the instance on init, is there anything else that should be done? My form: class RSVPForm(forms.ModelForm): class Meta: model = Invite fields = ['rsvp_guests'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['rsvp_guests'].widget.attrs.update( {'max': self.instance.max_guests}, ) My view where the instance is passed: def view_rsvp_create(request, id): invite = get_object_or_404(Invite, id=id) form = RSVPForm(request.POST or None, instance=invite) if form.is_valid(): new_invite = form.save(commit=False) new_invite.save() return redirect('view_rsvp_overview', name = invite.event.wedding.subdomain, code = invite.guest.code) data = {'form': form} template='experience/rsvp-create.html' return render(request, template, data) The template: {% load crispy_forms_tags %} <form class="form-horizontal form-material" method="post"> {% csrf_token %} {{ form | crispy }} <div class="form-group"> <div class="form-group text-center m-t-20"> <div class="col-12"> <button class="btn btn-success btn-block btn-lg waves-effect waves-light" type="submit">Add</button> </div> </div> </div> </form> -
Integrate Machine learning model with a webapp using django or flask
Hello , I am trying to make a fake news detector using machine learning. I have trained a model which can detect fake news based on the dataset it is trained on. But now my question is how do I showcase this model in a webapp (made with django or flask) so the end user can use it Please can you help me with this or at least helping me find a resource which can help me solve my problem !! -
Can I trigger Celery task on table update in Django?
For example, I have a model: class SomeModel(model.Model): is_active = BooleanField(default=False) ... Is it possible to trigger Celery task when is_active changes to True? The most important thing here is that I need to trigger it regardless of the way is_active changed, whether it changed via shell, admin panel, api call etc. The DB I use is psql. -
Is there any way to make a manual join using Django ORM?
lets say I have the following models: class ModelA(models.Model): pass class ModelB(ModelA): pass class ModelC(models.Model): model_a = models.ForeignKey(ModelA) class ModelD(models.Model): model_c = models.ForeingKey(ModelC) And I need to filter all the instances of ModelD that have a relation in ModelB. Is there any way to remove the unnecesary joins in the query that the queryset will produce ? ModelD.objects.filter(model_c__model_a__model_b__id__isnull=False) If there's any way to make a filter like this: ModelD.objects.filter(model_c__model_b__id__isnull=False) I know how to make the query on SQL, but for terms of readabilty and code maintenance I would like to know if there's any way to make the manual join or to remove that intermediate join. Thanks in advance for the replies ! -
Django: list view not recognized
I have to do this project of classified ads for Coursera. Essentially every user can post, update and delete advertisements. The problem is that even if the objects are correctly stored (I checked tables and objects via admin and manually with the command line), the ad list doesn't show up and it tells "There are no ads in the database." even though there are ads. I'm looking everywhere but I cannot find the error. Here's the code: ad_list.html: views.py: from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad class AdCreateView(OwnerCreateView): model = Ad fields = ['title', 'text', 'price'] class AdUpdateView(OwnerUpdateView): model = Ad fields = ['title', 'text', 'price'] class AdDeleteView(OwnerDeleteView): model = Ad owner.py: from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin class OwnerListView(ListView): """ Sub-class the ListView to pass the request to the form. """ class OwnerDetailView(DetailView): """ Sub-class the DetailView to pass the request to the form. """ class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current … -
Django reCAPTCHA with multiple forms
I have a DJANGO application where I protect forms with reCAPTCHA v2 invisible. I have no issue protecting 1 form, everything works well and I have been using this feature for quite some time. However, if I have 2 forms on the same page, EACH protected with their own captcha, it doesn't work. Here's what happens: OK: both forms have their individual onSubmit_xxxand onSubmit_yyy function (with a different widget uuid) OK: both forms get their "submit" event properly redirected to the verifyCaptcha_xxx or verifyCaptch_yyy function NOK: after grecaptcha.execute(), ALWAYS the onSubmit_xxx function (of the first form) is executed (with the wrong widget uuid) I am using Django 2.1 with Python 3.5 Any hints? Thanks a lot!! -
How to Call a Javascript function onclick event inside jinja template?
{% for person in teacher %} <tr class="bg-gray-100 border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"></td> <td class="p-0 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> <img src="{{person.customuser.profile_pic.url}}" class="rounded-lg w-32" alt="Avatar" /> </td> <td class="text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap"> <p>{{person.customuser.first_name}} {{person.customuser.last_name}}</p> </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> {% for item in person.subjects.all %} <p>{{item.name}}</p> {% endfor %} </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> <div class="flex items-center justify-center"> <div id="btnView" class="inline-flex shadow-md hover:shadow-lg focus:shadow-lg" role="group"> <button type="button" class="rounded-l inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-blue-700 focus:bg-blue-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Edit</button> <button onclick='viewDetails()' type="button" class=" inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-green-700 focus:bg-green-700 focus:outline-none focus:ring-0 active:bg-green-800 transition duration-150 ease-in-out">View</button> <button type="button" class=" rounded-r inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-red-700 focus:bg-red-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Delete</button> </div> </div> </td> </tr> {% endfor %} I want to call a javascript function viewDetails({{person.id}}) inside onclick event when the user presses the button.I want the value {{person.id}} to be passed as an argument which is coming from the for loop in jinja tag. Is it possible?