How to refresh the page when custom plugin is saved? - python

I have created a website using Django cms. When I save the custom plugin the template is not rendered. But it is rendered when I refresh the page.
So, how to refresh the page while saving the django cms custom plugin or any other way to render the template when the plugin is saved. But the content is saved in the admin side. I am not able to see the content in the template.

You would want to use ajax here. This is a very vague code on how you should go about it. but hope it helps.
<script type="application/javascript">
$(document).ready(function() {
$('.save-plugin-button-id').click(function (e) {
e.preventDefault();
$.ajax({
url: url_which_saves_plugin,
method: 'GET',
data:{},#add data required if any or leave blank
success: function(data){
#You might want to stylize your data here.
$("#update-content-div-id").append(JSON.stringify(data));
}
})
})
})
</script>

Related

Load new pages via Ajax without refreshing the whole nav bar Django

I'm new to Django and I'm building my own website. I have written a base.html page that contains the main body, CSS, js, fonts, and the navbar that all the pages of my site will have. The navbar is on another HTML file, navbar.html
Now, as soon as the CSS/js/fonts/navbar included in the base.html will be loaded on every page and won't change, is there a way with Ajax to load only the actual content of the page that change seamless without seeing the whole page refresh?
For instance, the part of the page that visually changes everytime is inside a <section class="home"></section> tag
When using JQuery, it is quite simple:
<script>
function load_page(url) {
$.ajax({
url: url,
success: function (data) {
$('#nav_id').html('');
data.nav_items.forEach(item => {
$('#nav_id').append($('<div>').onclick(load_page(item.url)).text(item.title));
}
},
error: function () {
alert('Could not load data');
}
});
}
</script>
And in your url you can define this as /nav/str:slug/ which leads to a view like this:
def nav_ajax(request, slug):
if slug == 'a':
return JsonResponse({
'navitem1': {
'title': 'A',
'url': reverse('your_nav_url_name', kwargs={'slug':'a'}),
},
# other menu items
)
else:
return JsonResponse({}) # default menu items

Django:how to render template and send context to template with ajax?

(sorry for my bad English)
Hello. I know partly how ajax is used with Django. but I have some problems. Some of them are: how to render a template with ajax? How to send Django to template with ajax? I searched the internet but I couldn't find exactly what I wanted.
I would be glad if you could also recommend a detailed resource on the use of ajax and Django. (free:( ).please help me guy.thanks now.
First you have to create instances in your Django's views.py file which returns the data you wanna display in template.
Then you need to create an ajax function inside the template. Here is a basic ajax function that can be modified to your needs:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
}
</script>
What it does is reach out to the source of data in your case it will probably be the instances in views.py. "readyState == 4" tells you the data load is complete, while "this.status == 200" tells you if the request is successful.
The question on how to display the data depends on you and the type of data.

Django: AJAX and path params

I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.
Say we have an url with a path param that maps to a particular view:
url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'))
And then the post.html includes a script that performs an AJAX request to fetch the post as JSON:
post.html
<script src="{{ STATIC_URL }}/js/post.js"></script>
<div id="post-container"></div>
This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner.
post.js
$.ajax({
url: '/post/??post_id??',
contentType: 'application/json'
})
.done(function(post_data) {
togglePlugin(post_data);
});
My main concern is how to figure out what post_id is from the js file in order to make the appropriate call.
How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax.
To get urls from your template you should use {% url %} template tag, for that you should add a name to your url:
url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'), name='my_name)
then in your can template call that url in this way {% url 'my_name' object.pk %} see this for more.
when you work with different file for your js, and you want to pass django variables, you should declare a <script> before import the js file, and there declare your variable:
<srcipt>var foo={{django_var}}</script>
<script src="{{ STATIC_URL }}/js/post.js"></script>
and then use the variable foo in the js.
You can pass a post_id variable to django template.
However if you don't want it to "hurt", put your .js code (script) in you html file, rendered by django. So you can use django template tags.
For example:
var url = "/post/{{post_id}}";
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
some_field: field_data,
some_other_field: field_data
},
success: function(data) {
do_something();
},
error: function(data) {
do_somethin();
}
});

In Django view,How to save array which pass from template via Ajax, to database?

I create array in JavaScript and send it via Ajax to my view and I can get it in view.Now I want to save it to my database(mysql) but I get "internal error" from Ajax.I think Ajax when post data to view and Django want to connect MySQL database, connection by ajax was abroted.
this is my template Ajax:
var postUrl = "http://localhost:8000/student/{{id}}/student_add_course/";
$('form[name="myForm"]').submit(function(){
$.ajax({
url:postUrl,
type: "POST",
// stock is somthing like this.stock=[[1,12],[2,14],...]
data: {'stock': stock, 'counter':i,csrfmiddlewaretoken: '{{ csrf_token }}'},
error:function (xhr, textStatus, thrownError){
alert(thrownError);},
})
});
this is view:
def student_add_course(request,student_id):
if request.method=='GET':
context={'id':student_id , 'form':AddCourseForStudentForm()}
request.session['ListOfCourses']=[]
return render(request, 'student/AddCourseForStudentForm.html',context)
elif request.is_ajax():
listOFcourses=course_passes.objects.order_by('-id')
id =listOFcourses[0].id
counter=int(request.POST.get('counter'))
for i in range(0,counter):
selected_course=request.POST.getlist('stock[%d][]'%i)
//course_passes is my table.
// evrey thing is good until here but when I want to save it,I get error.
#a.save()
return render(request, 'student/add_course.html')
What is my code problem and How should I solve it?
Is there better way to do this?
I'm sorry for my bad English.
Edit:
Finally I understand my problem is in MySQL side. The value which I want to insert is not correct and I change
a=course_passes(id+1,int(selected_course[0]),int(selected_course[1]),int(student_id))
to
find_user=user.objects.get(user_code=student_id,task=2)
a=course_passes(id+1,selected_course[0],selected_course[1],find_user.id)
thanks for your comment.

Using the Django URL Tag in an AJAX Call

There are LOTS of post and pages discussing the use of Django and AJAX, and I've read hundreds over the past day or so looking for the answer to this question. A quick overview:
May of the examples show a hard-coded URL like this:
$.post("/projects/create/", {"name" : name}, function(data) {...
or some use the URL template tag, but with no parameters:
$.post("{% url create_project %}", {"name" : name}, function(data) {...
However, I'd like to include a Django-style parameter in a URL. Here's my url definition:
url(r'ajax/entity_name/(?P<pk>\w+)/$',EntityAjaxView.as_view(),name='entity_name'),
Yes, I'm using a class based view, and it is based on DetailView. This view looks by default for a pk value to be provided in the URL, and in a normal template I would use:
{% url entity_name id_number %}
to provide a link. In my code, I want to grab the value entered in an input box for the pk value. Here is a snippet of my JavaScript (which doesn't work):
var id_number = $('#id_endowmententity_set-' + rownum + '-id_number').val()
$.ajax({
type: "GET",
url: '{% url entity_name id_number %}',
So, my question is, can I use the URL template tag with a value from an input box?
(I know that I could use POST instead of GET and pass the id_number in the POST data, but that won't work well with the DetailView.)
Django is a server-side application. Javascript is client-side. Django templates get rendered on the server, so {% url entity_name id_number %} is evaluated on the server side, and then it's value is returned to the client. Just because of this, it's impossible for you to combine Django templates with javascript. However there are couple of things you can do to solve your problem.
Since you are making an ajax call, and the ajax call depends on some user input, usually the best route for the client to send any type of user input to the server is by either using querystring (thing after ? in the URL) or by sending a POST data. So the simplest thing is to change your your url not to include the pk in the url, but for the view to get that as part of GET or POST data.
url(r'ajax/entity_name/$', EntityAjaxView.as_view(), name='entity_name'),
and the view (sorry I'm not familiar with class based views):
def entity_name(request):
pk = request.GET.get('pk')
...
That seems to me to be the most elegant solution. If however you absolutely need to construct the url on the client side, you can generate a template url on the server side and then replace whatever parts you need on the client side to get the full url. This however requires more maintenance and therefore is more error prone. Simple js example of this approach:
var id_number = $('#id_endowmententity_set-' + rownum + '-id_number').val(),
url = '{% url entity_name 0 %}'.replace('0', id_number);
$.ajax({
type: "GET",
url: url,
...
});
It is possible to set an Ajax url on the element you are selecting using an attribute and it will behave like Django urls. Importantly, you can even access the url in Javascript file. I use it a lot
HTML
<div class="card-body" id="js-products" data-url="{% url 'chart-data' %}">
<div class="chart-area">
<canvas id="testChart"></canvas>
</div>
</div>
Note: the data-url attribute set on parent div
JAVASCRIPT
$(document).ready(function () {
var endpoint = $("#js-products").attr("data-url");
var defaultData = [];
var labels = []
$.ajax({
method: 'GET',
url: endpoint,
success: function (data) {
labels = data.labels
defaultData = data.data_default
setChart()
},
error: function (error_data) {
console.log(error_data)
}
})
function setChart() {
var ctx = document.getElementById('testChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: labels,
datasets: [{
label: 'Monthly Performance',
data: defaultData,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
});
DJANGO VIEWS
Am using django rest framework class view but you can use either of function or class based view
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
labels = ['Products', 'User', 'May']
data_default = [SeedProduct.objects.all().count(),
User.objects.all().count(), 4]
data = {
'labels': labels,
'data_default': data_default,
}
return Response(data)
DJANGO URLS:
import the view class from views
path('api/chart/data', views.ChartData.as_view(), name="chart-data"),
It's pretty time consuming to go round trip to a server just to fetch a URL. The best strategy to keep URLs dry and avoid this is to generate javascript that emulates Django's native url reverse function and then serve that code statically with the rest of your client side JS.
django-render-static does just that.
This worked for me.
my URL was:
path('myurl/<str:type>', views.myfunction, name='myfunction')
my views.py file:
def myfunction(request,type):
return render(request, "payment.html", context)
In my template, I solved the issue by:
<button type="button" class="btn"
onclick="myfunction('forward');">My Button Name
</button>
<script>
function myfunction(type){
let url = "{% url 'appName:myfunction' 'ok' %}".replace('ok', type);
$.ajax({
method: 'POST',
url: url,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}'
}
});
}
</script>

Categories