How to get id from button modal to django views - javascript

I want to get the id from the modals button to select the id for the context object get id. the sample script is like this:
<button type="button" class="btn btn-primary see-details" data-toggle="modal" data-target="#exampleModalLong" data-id="{{data.id}}">Detail</button>
and I call the "data-id" from the button to javascript
$(".see-details").on('click', function (){
var id = $(this).data('id');
$(".modal-bodys").html(`
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<h1>{{students.name}}</h1>
</div>
</div>
</div>
`)
})
I want to retrieve the id of the javascript variable to put into get id in the context in views.py
from django.shortcuts import render,get_object_or_404
from profil.models import students,data
def index(request):
ID="get data-id from js"
context = {
'data' : data.objects.all(),
'students' : get_object_or_404(students, id=ID)
}
return render(request,'index.html',context)

Related

How to create a button to change a text in my html with data coming from Django's models.py?

I'm starting to work with Django and I'm starting a test to solidify what I've been learning. The idea is a single page, which displays a sentence as soon as the site opens. Below the phrase, there is a button that I would like to change the phrase to some other phrase coming from a variable declared in models.py and which contains several phrases that were registered through Django's admin panel.
This is my models.py file:
from django.db import models
class Base(models.Model):
criado = models.DateField('Criado', auto_now_add=True)
modificado = models.DateField('Atualização', auto_now=True)
ativo = models.BooleanField('Ativo', default=True)
class Meta:
abstract = True
class Frase(Base):
frase = models.CharField('Frase', max_length=100)
dica = models.CharField('Dica', max_length=200, default='-')
class Meta:
verbose_name = 'Frase'
verbose_name_plural = 'Frases'
def __str__(self):
return self.frase
This is my views.py file:
from django.views.generic import TemplateView
from .models import Frase
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['frases'] = Frase.objects.order_by('?').all()
return context
This is my index.html
<div class="container px-4 px-lg-5 h-100">
<div class="row gx-4 gx-lg-5 h-100 align-items-center justify-content-center text-center">
<div class="col-lg-8 align-self-end">
<h1 class="text-white font-weight-bold" id="frase">{{ frases|first }}</h1>
<hr class="divider" />
</div>
<div class="col-lg-8 align-self-baseline">
<a class="btn btn-primary btn-xl" onclick="nova_frase()">Nova frase</a>
</div>
</div>
</div>
(...) <!--rest of the html code-->
<script type="text/javascript">
function nova_frase() {
document.getElementById('frase').innerText = 'a';
}
</script>
"document.getElementById('phrase').innerText = 'a';" was my last test to try to create some change to the page through the button.
I tried using .innerHTML, but with no success either.
I'm having difficulties finding texts to do this task (click the button and change the phrase being displayed by another phrase coming from the variable defined in models.py).
I'm using Python 3.9.5 and Django 3.2.5.
If anyone can help me, I would be very grateful.
You can't directly change the text based on the frontend javascript event. First send all the buttons from Django to frontend template and store it in the javascript list. Then, use the javascript to display it based on the changes.
The another approach would be using Ajax.

Django forms are not receiving form data using ajax call

I am writing a simple AJAX site using a Django back-end where you can create articles. Each article has an edit button, which can be used to modify that pre-existing article on the page. This button pops up an edit form (the issue at hand) in a Bootstrap Modal.
The edit form has only 3 fields: headline, subheading, and a date (for now). Whatever the field inputs are, they are not sent back to Django properly and the is_valid() method returns False every single time. This is what form.errors gives me as output every single time:
<ul class="errorlist"><li>headline<ul class="errorlist">
<li>This field is required.</li>
</ul>
</li>
<li>subheading<ul class="errorlist">
<li>This field is required.</li></ul></li>
<li>date<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
The "This field is required" is likely because the model does not have blank=True, so the form must be sending empty fields.
Below is all my code in question, including the form in HTML, the AJAX call, and the Django form.
views.py:
# Handles editing articles
class ArticleEdit(View):
def post(self, request, id):
editForm = ArticleForm(request.POST)
if editForm.is_valid():
print("Debug: Form is valid")
# No Logic here yet
return JsonResponse({'edited' : 'OK'}, status=200)
else:
print(editForm.errors)
return JsonResponse({'edited' : 'FAIL'}, status=200)
forms.py
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['headline', 'subheading', 'date']
widgets = {
'headline' : forms.TextInput(attrs={'class': 'form-control'}),
'subheading' : forms.TextInput(attrs={'class': 'form-control'}),
'date' : forms.TextInput(attrs={'class': 'form-control'}),
}
articles.html
<!-- Bootstrap Modal -->
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Article</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- Edit Form -->
<form class="form-group" method="post" id="editArticleForm">
{% csrf_token %}
{{ editForm }}
<button type="button" class = "btn btn-outline-success my-3" id="finishEditButton">Finish</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
articles.js
function finishEdit()
{
editData = $('#editArticleForm').serialize();
console.log(editData);
$.ajax
({
url: '/' + currentlyEditing.data('id') + '/edited/',
data: {csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), data: editData, id: currentlyEditing.data('id')},
type: 'post',
success: function(data)
{
if (data.edited == "OK")
{
console.log("EDIT::RESPONSE OK");
}
else
{
console.log("EDIT::RESPONSE FAIL");
}
}
});
I've tried deleting the modal, and having the form as a simple element instead. I've also tried to rewrite my Ajax request but that hasn't worked either. Plus, the serialized data created from the form displays the information typed into the input fields, but it doesn't end up in Django.
In conclusion, my whatever my data is in my form in articles.html is not sent properly to Django, no matter what I type, and I cannot seem to figure out the problem. I would really appreciate some help with this.
Thank you all in advance.

Get value from js and pass it as parameter

I have a table in HTML file:
{% for dimension in dimension_list %}
<tr>
<td>{{dimension.title}}</td>
<td>{{dimension.description}}</td>
<div class="button-group">
<td><button type="button" class="btn-click-del" data-
id="{{dimension.pk}}" id="btn-confirm" ></button></td>
</div>
</tr>
{% endfor %}
So I receive the value data-id (button) and pass it to a model:
$('.btn-click-del').on('click', function () {
var id = ($(this).data('id'));
$("#modal-btn-yes").val(id);
});
In the modal, I need to pass this id as parameter to the function dimension_remove in my yes button
div class="modal-dialog modal-bg modal-dialog-centered">
<button onclick="location.href='{% url 'dimension_remove' pk=dimension.id %}';" type="button" class="btn btn-default" id="modal-btn-yes">Yes</button>
<button type="button" class="btn btn-primary" id="modal-btn-no">No</button>
</div>
I suggest to attach the click event in your JS part instead and attach the id to the data-id to the modal-btn-yes then get it simply and build your URL.
Attach the data-id to the modal-btn-yes button :
$('.btn-click-del').on('click', function() {
$("#modal-btn-yes").data('id', $(this).data('id'));
});
Get the data-id and build the URL :
$('body').on('click', '#modal-btn-yes', function() {
//Here you could get the clicked button "id" like
var id = $(this).data('id');
//location.href= Your link here
});

How to append blade template in panel-body

I created a two panel one for the user's options and the second panel is the transition of the panel. As you can see below I have a group of buttons every-time the user click the buttons the left panel will changed it's content every-time it clicks. But it won't work if I click on the buttons.
I used empty() so it will be empty first the panel-body on my left container after that I will append in the panel-body section
Master page below.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "{{ URL::asset('css/bootstrap.min.css') }}">
<script type = "text/javascript" src = "{{ URL::asset('js/jquery.js') }}"></script>
<script>
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is subjects");
});
});
</script>
</head>
<body>
#include ('layouts.navigation.user')
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class = "panel panel-default">
<div class = "panel-body" style = "height: 300px">
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "curriculum"> Curriculum
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "subjects"> Subjects
</label><br>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class = "panel panel-default">
<div class = "panel-body" id = "rightContainer" style = "height: 300px; overflow-y: scroll;">
//RIGHT CONTAINER
</div>
</div>
</div>
</div>
</div>
OPTIONS:
subjectsOption
curriculumOption
subjectsOption.blade.php
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "subjectList"> Subject List
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "createSubjects"> Create Subjects
</label><br>
<div>
curriculumOption.blade.php
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "curriculumList"> Curriculum List
</label><br>
<label class = "btn btn-primary btn-lg">
<input type = "checkbox" id = "createCurriculum"> Create Curriculum
</label><br>
</div>
I don't understand why you out checkbox in label. I have just remove the checkbox and add id to labels.
Add insert php file data using html()function.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "{{ URL::asset('css/bootstrap.min.css') }}">
<script type = "text/javascript" src = "{{ URL::asset('js/jquery.js') }}"></script>
<script>
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
//$("#rightContainer").empty();
$("#rightContainer").html(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
//$("#rightContainer").empty();
$("#rightContainer").html(data);
alert("This is subjects");
});
});
</script>
</head>
<body>
#include ('layouts.navigation.user')
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class = "panel panel-default">
<div class = "panel-body" style = "height: 300px">
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary btn-lg" id = "curriculum">
Curriculum
</label><br>
<label class = "btn btn-primary btn-lg" id = "subjects">
Subjects
</label><br>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class = "panel panel-default">
<div class = "panel-body" id = "rightContainer" style = "height: 300px; overflow-y: scroll;">
//RIGHT CONTAINER
</div>
</div>
</div>
</div>
</div>
Laravel Blade Template, or PHP file inside the /resources/views inside Laravel framework is not accessible using URL directly, to be precise, everything under /resources folder and even all other folders except /public, are not accessible. Only public folder can be accessed directly by using URL in laravel framework. You must notice that the view inside resources folder can only be returned after come from route -> controller -> view to be simple.
Thus, this part of your code
$(document).on("click", "#curriculum", function ()
{
$.get("curriculumOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
$(document).on("click", "#subjects", function ()
{
$.get("subjectsOption.blade.php", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is subjects");
});
});
is trying to access your server in certain URL. lets take example your domain is test.laravel.dev and you are in root of your domain (in your browser you can see http://test.laravel.dev), and you run these script there. It means that you are trying to do AJAX request to url http://test.laravel.dev/curriculumOption.blade.php and http://test.laravel.dev/subjectOption.blade.php. What will happens? this will try to find route in your routes.php file, looking for "/curriculumOption.blade.php" or "/subjectOption.blade.php" which i am sure it's not exists there. what you can do is, if you still need the blade template to be processed before returning as AJAX response, you can make it like this:
routes.php
Route::get("/curriculumOption","CurriculumOptionController#show");
CurriculumOptionController.php
public function show()
{
//do your things here
return view("curriculumOption");
}
with the curriculumOption.blade.php is under /resources/views folder, and change your ajax request to:
$(document).on("click", "#curriculum", function ()
{
$.get("/curriculumOption", function (data)
{
$("#rightContainer").empty();
$("#rightContainer").append(data);
alert("This is curriculum");
});
});
This will work, please try and ask if have any other problem.
Explanation #1
Due to some security reason and also as a feature for laravel, most of the folders except public cannot be accessed without PHP preprocessor. When you are making a request in browser, the HTTP request is being sent to your browser to the server. in this case, if you make get request, you dont pass any other additional form parameters to server. Server read the request URL from your browser and then there are some server configuration in how are they going to pass the parameter to PHP preprocessor. These configuration is set in .htaccess file for apache HTTP server, nginx configuration for NGINX, and web.config for IIS server. You can notice that the .htaccess file is included in your /public folder of laravel project and the /public folder is the default for your domain, lets say your domain is test.laravel.dev, then test.laravel.dev is equal to /public and test.laravel.dev/index.php is refering to /public/index.php file. The rest that can be put in /public usually are css, javascript, and image files. Templates, Controller, Routes, etc are not accessible from URL. They are being managed by the framework. /resource folder is not accessible for security reason also. The only way is to access it from route or controller. If you dont define what to do with a certain URI, laravel framework will not give a proper response which is most likely erorr. Your /management/curriculumOption.blade.php can't be accessed simply because you dont have a route with
Route::get("/management/curriculumOption.blade.php"/, .....)
even though i dont think you can put .blade.php in the parameters also, but worth to try. There are only 2 options(need citation) to access certain URL to be responded in Laravel:
Define it in routes.php
put it in public folder

Codeigniter route on button click

Hi I am using codeigniter for this project
I have a button element as below
<div class=" pull-right" id="container">
<button class="btn btn-info">
<a style="text-decoration:none;color:white" href="">Guide</a>
</button>
</div>
This button element is part of a div which is one of the results from the search. When I click on the button, how do i pass the information of the div to the controller I want? The information I want to pass is just the element id of the div which is "container".
Try do like that
<button class="btn btn-info">
<a style="text-decoration:none;color:white" href="control/method/value">Guide</a>
</button>
In your class can do like that
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Control extends CI_Controller {
public function method($value) {
// Your value is in $value;
}
}
[Update]
Getting the parent ID element dynamically
<div class=" pull-right" id="container">
<button class="btn btn-info" onclick="window.location='/controller/method/' + this.parentNode.id;">
<a style="text-decoration:none;color:white">Guide</a>
</button>
</div>
Using jQuery:
$('.btn').click(function () {
$.ajax({
type : "POST",
url : 'controller/method',
data: {id : $(this).parent().attr('id')},
success : function(data) {}
});
});
In your controller:
$id = $this->input->post('id', TRUE);

Categories

Resources