I have a the following view that works ok and displays the results just fine in the template.
def PTR(request):
if request.method == 'POST':
form = PTRForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
results = data_groups.setup_ptr(cd)
t = loader.get_template('ptr_records.html')
c = RequestContext(request, {'results': results})
return HttpResponse(t.render(c))
else:
form = PTRForm()
return render_to_response('ptr_form.html', {'form': form})
However, I'd prefer the results display in a bootstrap modal. I'm sure I can figure it out if I new where to start. Should I do the following.... Add jQuery to the form and have jQuery/javascript handle the post and get the results to put in a modal that is defined on the form itself. That is, the modal won't be displayed until success is returned to the AJAX call?
Yes you should do that, use Ajax to call the server then return the data as json then use jquery and bootstrap to display the modal
Related
I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view:
#login_required
def basket(request):
if request.method == "POST":
selection = json.dumps(request.POST)
print(f"Selection is", selection) # selection comes out OK
context = {"test": "TO DO"}
return render(request, "pizza/confirmation.html", context) # not working
I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why.
Here is my JavaScript snippet:
var jsonStr = JSON.stringify(obj); //obj contains my data
const r = new XMLHttpRequest();
r.open('POST', '/basket');
const data = new FormData();
data.append('selection', jsonStr);
r.onload = () => {
// don't really want any callback and it seems I can only use GET here anyway
};
r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
r.send(data);
return false;
In your basket view function, you always render the template as response. You can pass the parameters to your js snippet via HttpResponse. After request completed and you have response in your js function, you can use window.location.href to redirect the page you want. You can also look this answer to get more information.
I am trying to send a json value to ajax from django class based view and the data i am sending will be appended in html through ajax. but i am not able to send value from back end to front end successfully.
class DetailView(TemplateView):
template_name = 'list.html'
def get_context_data(self,*args, **kwargs):
context = super(DetailView,self).get_context_data()
list_view = GetList().get_data(self.request)
movie_list = list.json()
context['list']= movie_list
print(movie_list)
return context
So this code is sending only template value to the ajax data, when i do the console.log(data) on success call it shows me whole html code of the 'list.html' in both alert and console.log . But it prints all the values in cmd console.
cclass DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return HttpResponse(json.dumps(movie_list))
this code prints all the values on respective html, but doesnt call ajax function.so no values showing in console.log.
this is my ajax call,first i am trying to just see weather i'm successfully getting the values on success call or not.
<script>
$(document).ready(function(){
$.ajax({
method :'GET',
url: '/detail',
success: function(data){
alert(data)
console.log(data)
},
})
})
</script>
So, how can i achieve my desired result? I want to get value in ajax call so i cal show those values in a table which is in a list form
You can use JsonResponse to send json data. (You can see detail in docs here)
like below
from django.http import JsonResponse
class DetailView(TemplateView):
template_name = 'list.html'
def get(self,request):
list_view = GetList().get_data(self.request)
movie_list = list.json()
return JsonResponse(movie_list, status=200)
btw, you have to aware your data type. JsonResponse automatically serialize your data so you don't have to use json() for your data.
I have two headers header.html and headersuccess.html . I user is logged in, I need to change the header.html as headersuccess.html. How can I able to implement that?
My views.py is.. By this I am going to loginsuccess.html.. So, if login is success I need to change header from header.html to hadersuccess.html
def logsuccess(request):
if('loggedIn' in request.session):
id = request.session['uid'];
return render(request,"loginsuccess.html",{'uid':id});
else:
return render(request,"failed.html",{});
I am getting uid using this. I am using html and vue js for displaying.
You can do this in the view:
def logsuccess(request):
if request.user.is_authenticated():
id = request.user.id
return render(request, "loginsuccess.html", {'uid': id})
else:
return render(request, "failed.html", {})
You'll probably also want to read up on PEP-8 to follow Python coding conventions. Good luck!
I'm new to Django and Python so bear with me.
I'm trying to submit a form (in test.html page) And once the form is submitted I want to load a new page(test.html/web1.html) and then the page will display continuous updates on tasks running.
This currently works on a single page, where I submit the form I get the updates on the same page using AJAX. I want to implement this on a new page. Below is my code.
test.js
$('#Submit_button').on('submit',function(event){
event.preventDefault();
console.log("form submitted!")
call_func();
});
function call_func() {
$.ajax({
url : "start_task/", // the endpoint
data:{...,'init':call_func.i}, // call_func.i to iterate 2 times
headers: {Accept: "application/json"},
success : function(json) {
if(call_func.i==0){
call_func.i=1;
call_func();
}
else ...
views.py
def start_task(request):
if request.method == 'POST':
init = request.POST.get('init')
print('init =',init)
if init==0:
return render(request, 'my_app/web1.html')
elif init==1:
# work on updates
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
html
<form action="/test.html/start_task/" method="POST" id="Submit_button">
How do I use AJAX only for the latter part (to update the new page) and just load the page first after submit?
I think you need something like HttpResponseRedirect instead of HttpResponse:
if form.is_valid(): # validation
# Process your data
# ...
return HttpResponseRedirect('/new_page_url/')
FYI - development site, work in progress.
I am using Django on a page with a form. However, I am also using a javascript tab function on this same page which highlights the tab with the correct on-page link / hash.
The default page = http://learntango.webfactional.com/video/35863752#section=comment
The contact-us page = http://learntango.webfactional.com/video/35863752#section=contact
When the form is not valid, the page is returned (good). However, it is the base page which is returned: http://learntango.webfactional.com/video/35863752
After that, the javascript then defaults this to the comment page.
How do I return the same page, with the "contact" on-page link active, so they can see their form errors and realize that the form did not submit?
Thanks!
David
def video(request, url_vimeo_id):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
'This is an e-mail from the website',
cd['message'],
cd.get('email', 'noreply#example.com'),
['dwyliu#gmail.com'],
)
return HttpResponseRedirect('http://www.learntodancetango.com')
return render_to_response('video.html',{'video': video,'next':next, 'form': form}, context_instance=RequestContext(request))
else:
form = ContactForm()
return render_to_response('video.html',{'video': video,'next':next, 'form': form}, context_instance=RequestContext(request))
Set form's action as http://learntango.webfactional.com/video/35863752#section=contact