I need to Auto-fill up the crispy fields so I called the needed data from my database using ajax function as:
views.py
def load_record(request):
PUITS_id = request.GET.get('PUITS')
record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1]
my_record= [str(record[0].PUITS) , str(record[0].MODE), str(record[0].CS)]
print(my_record)
return render(request, 'measure/Surveill_Wells/Add_wellMntr.html', {'record': my_record})
And my HTML file is :
<form method="POST" id="SurveillanceDesPuits_F" data-record-url="{% url 'ajax_load_record' %}">
{% csrf_token %}
<!-- form from views.py-->
<div class="border p-2 mb-3 mt-3 border-secondary">
<div class="form-row">
<div class="form-group col-md-3 mb-0">
{{ form.PUITS|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.CS|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.MODE|as_crispy_field }}
</div>
</div>
</div>
<input class="btn btn-success mb-4" type="submit" value="ADD Record">
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_PUITS").change(function () {
var url = $("#SurveillanceDesPuits_F").attr("data-record-url");
var PUITSId = $(this).val();
$.ajax({
url: url,
data: {
'PUITS': PUITSId
},
success: function (data) {
$("#id_MODE").html(data);
}
});
});
</script>
After selecting an item (PUITS) from the dropdown list, I want to set the value of CS and MODE automatically from the received data.
so in the console, it gives me this error:
File "D:\WikiPED\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 102, in as_crispy_field
raise CrispyError("|as_crispy_field got passed an invalid or inexistent field")
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field
[07/Sep/2021 17:30:05] "GET /ajax/load-record/?PUITS=1 HTTP/1.1" 500 25693
what I missed in this code?
Thanks
I changed the views.py as:
def load_record(request):
PUITS_id = request.GET.get('PUITS')
record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1]
return JsonResponse({'record2': list(record2.values())}, safe=False)
the scripts will be:
<script type="text/javascript">
$.ajax({
type: 'GET' ,
url: url,
data: {'PUITS': PUITSId },
dataType: "json",
success: function (response){
const object = response.record2[0]
$("#id_PUITS").val(object.PUITS_id);
$("#id_DATE_TEST").val(object.DATE_TEST);
$("#id_MODE").val(object.MODE);
$("#id_CS").val(object.CS);
$("#id_SITUATION").val(object.SITUATION);
$("#id_DUSE").val(object.DUSE);
$("#id_PRES_TBG").val(object.PRES_TBG);
$("#id_PRES_CSG").val(object.PRES_CSG);
$("#id_PRES_AVD").val(object.PRES_AVD);
$("#id_RESEAU_GL").val(object.RESEAU_GL);
$("#id_ANNULAIRE_TECH").val(object.ANNULAIRE_TECH);
$("#id_OBSERVATION").val(object.OBSERVATION);
$("#id_Controle_Pression_ENSP").val(object.Controle_Pression_ENSP);
$("#id_Test_Puits").val(object.Test_Puits);
$("#id_Controle_Pression_DP").val(object.Controle_Pression_DP);
},
});
return false;
});
</script>
Related
I am new to django and html. below is my first test web page of a simple online calculator.
I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit".
I saw there might be several different ways to do this work, iframe/AJAX. Since I am new, what is the really simplest way to achieve this goal? BTW, I dont write javascripts.
html:
<form method="POST">
{% csrf_token %}
<div>
<label>num_1:</label>
<input type="text" name="num_1" value="1" placeholder="Enter value" />
</div>
<div>
<label>num_2:</label>
<input type="text" name="num_2" value="2" placeholder="Enter value" />
</div>
<br />
<div>{{ result }}</div>
<button type="submit">Submit</button>
</form>
view.py
def post_list(request):
result = 0
if request.method == "POST":
num1 = request.POST.get('num_1')
num2 = request.POST.get('num_2')
result = int(num1) + int(num2)
print(request.POST)
print(result)
context = {
'result': result
}
return render(request, 'blog/post_list.html', context)
This is a simple example of using Ajax, which I hope will be useful to you.
first you need change post_list view:
view
from django.http import JsonResponse
def post_list(request):
if request.method == "POST":
num1 = request.POST.get('num_1')
num2 = request.POST.get('num_2')
result = int(num1) + int(num2)
return JsonResponse({"result":result})
else:
return render(request, 'blog/post_list.html', context={"result":0})
I use JsonResponse because I just want to get the result data in ajax and display it in the html , for GET request render the html file and for POST request use JsonResponse to return a json like context.
And your html file should to be a look like this:
html
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<form method="POST" id="post-form">
{% csrf_token %}
<div>
<label>num_1:</label>
<input type="text" name="num_1" value="1" placeholder="Enter value" />
</div>
<div>
<label>num_2:</label>
<input type="text" name="num_2" value="2" placeholder="Enter value" />
</div>
<br />
<div id="result" >{{ result }}</div>
<button type="submit" >Submit</button>
</form>
<script>
$(document).ready(
$('#post-form').submit(function(e){
e.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type:"POST",
url: "/your_url/",
data: serializedData,
success: function(data){
$("#result").text(data["result"]);
}
});
})
);
</script>
First I added jQuery cdn and then your html file, except that I added attribute id=post-form to the form and added id=result, then <script> tag was added and jquery function inside the tag was execute when your form Submited(detect event by the id #post-form).
And get the data(num_1, num_2) by serialize method then use Ajax to send POST reqeust to the view function(post_list), in Ajax you just need to pass serializedData and url(also you can use the Django url tag or set it in action form or...), After that we need to send data to the html(means the result data we received from the View).
in success function Ajax you can add html tag to your html file or
replace the some values,...
In Ajax, you must specify your URL to send the data.
for example if you have this url.py
urls.py
from .views import post_list
urlpatterns = [
path("posts_list/", post_list, name="post_list"),
]
In ajax you can add an address like this:
$.ajax({
type:"POST",
url: "/posts_list/",
....
Or
$.ajax({
type:"POST",
url: "{% url 'post_list' %}",
....
And if you have app_name in urls.py you can added url: "{% url 'app_name:post_list' %}",
I've watched countless videos & read through a lot of docs but I am still having trouble integrating a REST API to my HTML website. I'd like to call on the WaitlistAPI once a user clicks on the button on my website. How do I integrate this API to my website? Thanks in advance for your help!
Here is the HTML code:
<section class="waitlist">
<form>
<input type="text" name="email" placeholder="Enter Email" required>
<button>Join Waitlist</button>
</form>
</section>
Hi for integrate your website with https://getwaitlist.com/ you need use Javascript, and for call an API you need Ajax, and identify the value to send, in this case waitlist_email.
Here an example of js:
function post(api_url, data, success_callback, fail_callback) {
$.ajax({
method: 'POST',
url: api_url,
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(response) {
success_callback(response);
},
error: function(response) {
fail_callback(response);
}
});
}
function submit_email_to_waitlist(){
// fetch values from the frontend
var new_signup = document.getElementById('waitlist_email').value; //fetch user signing up on frontend
var current_url = document.URL; //fetch current URL, including potential referral token
const success_callback = function(response) {
// fetching responses
waiter_email = response['registered_email']
waiter_priority = response['current_priority']
total_waiters_currently = response['total_waiters_currently']
referral_link = response['referral_link']
// hiding parts of HTML
$('#waitlist_email').hide()
$('#demo_submit_button').hide()
$('#email_address_text').hide()
// showing parts of HTML
$('#current_text').show()
$('#current_waiter_spot').show()
$('#out_of').show()
$('#all_waiter_spots').show()
$('#demo_referral').show()
// appending HTML information
$('#current_waiter_spot').html(waiter_priority)
$('#all_waiter_spots').html(total_waiters_currently)
$('#referral_link_url').html('Your referral link is:' + referral_link)
$('#info_ref_link').html('Click on the button to copy your referral link (also sent to your email).')
};
const fail_callback = function(response) {
// perform actions based on error codes
response_code = response['status']
if (response_code == 422) {
$('#error_message').html("Invalid value to sign up with.");
} else if (response_code == 400) {
$('#error_message').html("Error!");
}
};
post('https://www.getwaitlist.com/waitlist',
{email: new_signup,
api_key: 'YOUR API KEY',
referral_link: current_url
}, success_callback, fail_callback);
};
and here an example or your html:
<div class="col form-group">
<h5 class="h5 pt-1" id="current_text" >You are currently in spot</h5>
<h5 class="h5 pt-1" id="current_waiter_spot"></h5>
<h5 class="h5 pt-1" id="out_of">of</h5>
<h5 class="h5 pt-1" id="all_waiter_spots"></h5>
<label class="cform-label" for="rf-email" id="email_address_text"> Email address </label>
<input class="cform-control" type="email" id="waitlist_email" placeholder="Your email" >
<button class="btn btn-primary btn-block" type="button" id="demo_submit_button" onclick="submit_email_to_waitlist()" > Try the demo </button>
<p class="font-size-ms text-muted" id="referral_link_url"></p>
<button class="btn btn-primary btn-block" type="button" id="demo_referral" > Copy referral link </button>
<p class="font-size-ms text-muted" id="filler"></p>
<p class="font-size-ms text-muted" id="info_ref_link"></p>
<p class="font-size-ms text-muted" id="error_message"></p>
</div>
Here you can view a good working example: https://getwaitlist.com/templates
I am using Django, jQuery and Ajax. But, I am confused about how I can get the post id in ajax data to use that in views.py. I am adding code here and must read comments in the code so you can understand better what i am actually trying to explain or what problem I am facing. If this question require your little bit more time than answering other questions than please do not skip this question if you know the solution. All i can do for you is that i can up vote you 10 to 15 answers so that your reputation can increase.
I am beginner with JQuery so please explain your answer briefly.
So ,Here down below i have div tag which will provide me post id. if user click on the reply button.
<div id='post_id' post="{{post.id}}">
{% if node.level < 3 %}
<button class='btn btn-success' onclick="myFunction({{node.id}})">Reply</button>
{% endif %}
</div>
Than I have also form for comment.
<form id='commentform' class='commentform' method='POST'>
{% csrf_token %}
{% with allcomments as total_comments %}
<p>{{ total_comments }} comment{{total_comments|pluralize}}</p>
{% endwith %}
<select name='post' class='d-none' id='id_post'>
<option value="{{ post.id }}" selected="{{ post.id }}"></option>
</select>
<label class='small font-weight-bold'>{{comment_form.parent.label}}</label>
{{comment_form.parent}}
<div class='d-flex'>
<img class='avatar_comment align-self-center' src="{% for data in avatar %}{{data.avatar.url}}{%endfor%}">
{{comment_form.body }}
</div>
<div class='d-flex flex-row-reverse'>
<button type='submit' class='newcomment btn btn-primary' value='commentform' id='newcomment'>Submit</button>
</div>
</form>
between script tags I have set an event which is linked with form.
$(document).on('click', '#newcomment, #newcommentinner', function (e) {
e.preventDefault();
var button = $(this).attr("value");
var post_id = document.getElementById('post_id').getAttribute('post'); #Here I am trying to take post id from div tag with id='post_id'.
console.log(post_id,'postid') #In console it is returning me 2 which is right post id.
var placement = "commentform"
if (button == "newcommentform") {
var placement = "newcommentform"
}
$.ajax({
type: 'POST',
url: '{% url "posts:addcomment" pk=post.pk slug=post.slug %}',
data: $("#" + button).serialize() + {'post_id' : post_id},#Here I am trying to take that post id in data so i can use that in views.py. But in views.py it is returning me none And I don't understand why ? Because this is a post_id variable which is returning me 2 in console but in terminal it is returning me none. Please tell me how can i fix it.
cache: false,
success: function (json) {
console.log(json)
$('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \
<div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \
<div>' + json['result2'] + '</div> \
<hr> \
</div>').insertBefore('#' + placement);
$('.commentform').trigger("reset");
formExit()
},
error: function (xhr, errmsg, err) {
}
});
})
If more information is require than tell me. I will update my question with that information.
in console:
in terminal:
it worked for me.
data: $("#" + button).serialize() +"&post_id="+post_id
I'm trying to inject an html template with a django function on it, into another html template. The function rests on an AJAX call for its variables.
My AJAX call seems to be firing correctly (after checking in the Chrome dev tools) but the result is not showing on the html page as it should be.
Here is the AJAX call
//dashboard
$(document).ready(function(){
console.log('Document Ready')
$.ajax({
type: "GET",
url : '/electra/playlist',
dataType: "json",
data: {
'venue': 'venue',
'list': 'list',
},
success: function(data){
$("#playlist").html(data);
console.log(data)
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Here is the html file where the Django function occurs playlist.html
<!--what is the purpose of this fragmented code?-->
<div class="user_playlists">
<ul>
{% for item in playlist %}
<li>
<div>
<h6 class="playlist-name">{{ item.list }}</h6>
<h6 class="venue-name">{{ item.venue }}</h6>
</div>
</li>
{% endfor %}
</ul>
</div>
And here is the portion of the dashboard.html template where the playlist.html function should be injected:
<body>
{% block content %}
<div class="container-fluid" style="padding:15px">
<!--location -->
<div class="row">
<div class="col-sm-3">
<h3 class="list-heading"> Your Playlists </h3>
<div id="playlist">
</div>
</div>
</div>
</div>
{% endblock %}
Please note I have tried with {% include "playlist.html" %} and would like to avoid this if I can, I have another two html templates working in a similar way with out the django function.
Here is the views.py if it helps as well:
#ensure_csrf_cookie
def dashboard(request):
return render(request, 'testingland/dashboard.html')
class user_playlist(ListView):
template_name = 'testingland/playlist.html'
context_object_name = 'playlist'
model = UserVenue
def get_queryset(self):
venue = self.request.GET.get('venue', None)
list = self.request.GET.get('list', None)
return UserVenue.objects.filter(list__user=self.request.user)
You don't need to send json type data. So, just removing the line should work fine:
$.ajax({
type: "GET",
url : '/electra/playlist',
// dataType: "json", ---> Remove this line
data: {
'venue': 'venue',
'list': 'list',
},
success: function(data){
$("#playlist").html(data);
console.log(data)
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Note:- "Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead." - jQuery
I get 403 error due to csrf_token verification failure in spite of token explicit declaration in an ajax call. I for my data dictionary in the same manner in other functions and it works just great.
Here is JS:
$(document).on("click", ".update-cleaning", function(event){
event.preventDefault();
var input_field_name = $(this).attr('name')
var obj_id = $(this).attr('value')
var model_name = $(this).attr('data-model')
var field_name = $(this).attr('data-field')
var value = $("#" + input_field_name + obj_id).val();
if (!value) {
alert('Fill the field!')
}
else {
$.ajax({
url: "{% url 'ajax_update_cleaning' %}",
type: "POST",
data: {'object_id': obj_id, 'model_name': model_name, 'field_name': field_name, 'value': value, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'json',
})
.done(function(response){
console.log(response);
})
}
});
My html form is in a popover which is toggled by a click on <td> and looks like this:
<td class="text-md-center with-popover" name="frequency" value="{{cleaning.id}}">
{{ cleaning.frequency }}
<div id="frequency{{cleaning.id}}" style="display: none">
<form method="POST">
<label for="cleaning_frequency">Frequency: </label>
<input id="cleaning_frequency{{cleaning.id}}" type="number" name="cleaning" value="{{cleaning.frequency}}">
<button type="submit" class="btn btn-success btn-sm update-cleaning" name="cleaning_frequency" data-model="Cleaning" data-field="frequency" value="{{cleaning.id}}"> Change </button>
</form>
</div>
</td>
Could you give me some ideas? Thank you.
In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL, e.g.:
<form method="post">{% csrf_token %}
Read more in the Django Documentation