automatic refreshing <div> with django - javascript

I have a form that when it is posted the content of console.html gets changed. for refreshing the page I used the following code but this does not refresh console.html
javascript
function autorefresh() {
// auto refresh page after 1 second
setInterval('refreshPage()', 1000);
}
function refreshPage() {
var container = document.getElementById("console");
container.innerHTML= '<object type="text/html" data="../../templates/snippets/console.html" ></object>';
//this line is to watch the result in console , you can remove it later
console.log("Refreshed");
}
index.html
<script>autorefresh()</script>
<div id="console" >
{% include 'snippets/console.html' %}
</div>
view.py
def index(request):
if request.method == "GET":
return render(request, 'index.html')
if request.method == "POST": # If the form has been submitted...
form=InputForm(request)
form.do_function()
return render(request, 'index.html')

I rewrote html with the help of jquery:
<script type="text/javascript" src="{% static "js/jquery.js" %}"></script>
<script>
function autorefresh() {
// auto refresh page after 1 second
setInterval('refreshPage()', 1000);
}
function refreshPage() {
$.ajax({
url: '{% url 'console' %}',
success: function(data) {
$('#console').html(data);
}
});
}
</script>
.
.
.
<script>autorefresh()</script>
<div id="console" ></div>
view.py
def console(request):
data=
return render(request, 'snippets/console.html',{"data": data})
console.html
{% for line in data %}
{{ line }}
{% endfor %}
and finally add console to urls.
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('console', views.console, name='console'),
]
I hope you don't spend a day finding the solution :))

Related

How to create if statement on a redirect to change Django model

I am trying to create a if statement in my Django view that detects when I am redirected to my complete order url. I want to do this because I would like to change my Django model Order 'complete' field to true. My redirect is coming from a javascript function in my paypal intergration.
checkout.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h1>Checkout</h1>
<div class='container'>
<div class='row'>
<div class='col-6'>
<form action="" method='post' id='payement-form'>
{% csrf_token %}
<!-- {{ form|crispy }} -->
<div class='col-12' id='paypal-button-container'></div>
</form>
<script
src="https://www.paypal.com/sdk/js?client-id="> // Required. Replace YOUR_CLIENT_ID with your sandbox client ID.
</script>
<script>
function redirect() {
var url = "{% url 'complete-order' %}"
window.location.href = url
}
paypal.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function (data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function (details) {
// This function is the redirect
redirect()
alert('Transaction completed by ' + details.payer.name.given_name);
});
}
}).render('#paypal-button-container');
</script>
</div>
{% endblock content %}
views.py
#login_required(login_url='login')
def checkout(request):
order = Order.objects.get(user=request.user, complete=False)
context = {
'order': order
}
return render(request, 'videogames/checkout.html', context)
#login_required(login_url='login')
def paymentComplete(request):
order = Order.objects.get(user=request.user, complete=True)
context = {
'order': order
}
return render(request, 'videogames/complete.html', context)
There are many ways that should be selected according to your project.
before redirection, in the view , call a link with Ajax to change the status
#login_required(login_url='login')
def paymentSetComplete(request):
order = Order.objects.get(id=request.payment_id=,user=request.user, complete=False)
order.complete=True
order.save() # or update directly
return
Change the status when the request to load the complate page was sent to django
I do not know what measures you have taken to secure and prevent the fake purchases
But know that users can repeat requests that come to the server

Anybody see the problem? #Bootoast script

Trying to get Bootoast to work on my website, where I try to pass a message. You can see the code below. Using Django-bootstrap for front-end.
BASE.HTML
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.css">
<script>
function toast(message, type) {
bootoast.toast({
position: 'bottom-center',
message,
type,
});
}
{% if messages %}
{% for message in messages %}
toast('{{ message }}', '{{ message.tags }}')
{% endfor %}
{% endif %}
</script>
VIEWS.PY
#login_required(login_url="/sign-in/?next=/customer/")
def profile_page(request):
user_form = forms.BasicUserForm(instance=request.user)
customer_form = forms.BasicCustomerForm(instance=request.user.customer)
if request.method == "POST":
user_form = forms.BasicUserForm(request.POST, instance=request.user)
customer_form = forms.BasicCustomerForm(request.POST, request.FILES, instance=request.user.customer)
if user_form.is_valid() and customer_form.is_valid():
user_form.save()
customer_form.save()
messages.success(request, 'Your profile has been updated')
return redirect(reverse('customer:profile'))
return render(request, 'customer/profile.html', {
"user_form": user_form,
"customer_form": customer_form
})
So the error I'm getting is this:
(index):197 Uncaught ReferenceError: bootoast is not defined
I'm blind or isn't this defined?
<script srs="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>
Should have been
<script src="https://unpkg.com/bootoast#1.0.1/dist/bootoast.min.js"></script>

How to fix matchong query does not exist error?

I have been working on a like system using django and ajax, this like system is very similar to instagram's one. After finishing with the code I started to get a Post matching query does not exist error which has been a pain. I dont see the wrong in my code but I think the problem is on the views.py file because the traceback is triggering a line there. How can i fix this error?
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
user = models.ForeignKey(User, on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
def __str__(self):
return str(self.id)
views.py (upload view uploades the form, home displays the uploaded form, like_post is the view in charged of liking and unliking posts and home_serialized os the one that contains the json so that the page doesnt reload when the like button is clicked)
def upload(request):
print("toro")
if request.method == 'POST':
print("caballo")
form = PostForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('home')
print('succesfully uploded')
else:
form = PostForm()
print('didnt upload')
return render(request, 'home.html', {'form': form})
def home(request):
contents = Post.objects.all()
args = {
'contents': contents,
}
return render(request, 'home.html', args)
def like_post(request):
user = request.user
if request.method == 'POST':
pk = request.POST.get('post_pk')
post_obj = Post.objects.get(pk=pk)
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
return HttpResponse()
def home_serialized(request):
data = list(Post.objects.values())
return JsonResponse(data, safe=False)
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload', views.upload, name='upload'),
path('like/', views.like_post, name='like-post'),
path('serialized/', views.home_serialized, name='serialized-view'),
]
home.html
<form method='post' action="{% url 'upload' %}">
{% csrf_token %}
<input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
<button class="submit-button" type="submit">Save</button>
</form>
{% for content in contents %}
{% if content %}
<ul class="list-group">
<li class="list-group-item">{{ content.text }}</li>
<form action="{% url 'like-post' %}" class='like-form' method="POST" id={{content.id}}>
{% csrf_token %}
<input type='hidden' name="post_ok" value="{{ content.ok }}">
<button class='like-btn{{ content.id }}'>
{% if request.user in content.liked.all %}
Unlike
{% else %}
Like
{% endif %}
</button>
</form>
<strong>{{ content.liked.all.count }}</strong>
</ul>
{% endif %}
{% endfor %}
<script type='text/javascript'>
$(document).ready(function(){
$('.like-form').submit(function(e){
e.preventDefault()
console.log('works')
const post_id = $(this).attr('id')
console.log(this)
console.log(post_id)
const likeText = $(`.like-btn${post_id}`).text()
console.log(likeText)
const trim = $.trim(likeText)
console.log(trim)
const url = $('.like-form').attr('action')
console.log(url)
$.ajax({
type: 'POST',
url: url,
data : {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_pk': post_id,
},
success: function(error){
console.log('success')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/serialized/',
success: function(response){
console.log(response)
$.each(response, function(index, element){
console.log(index)
console.log(element.content)
if (post_id == element.id) {
if(trim == 'Like') {
console.log('unlike')
$(`.like-btn${post_id}`).html('Unlike')
} else if (trim == 'Unlike') {
console.log('like')
$(`.like-btn${post_id}`).html('Like')
} else {
console.log('ups')
}
}
})
},
error: function(error){
console.log('error')
}
})
},
error: function(error){
console.log('error', error)
}
})
})
});
</script>
traceback
Traceback (most recent call last):
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\MaríaPaola\projects\nwpc\like\views.py", line 65, in like_post
post_obj = Post.objects.get(pk=pk).exists()
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\MaríaPaola\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get
raise self.model.DoesNotExist(
like.models.Post.DoesNotExist: Post matching query does not exist.
I'm not sure what it says in the traceback. If you could provide that, maybe it'll make more sense. But I assume it's because of the like post_obj = Post.objects.get(pk=pk) in
def like_post(request) function.
Post with the given primary key does not exist. What you can do is to check if the pk exists.
if Post.objects.filter(pk=pk).exists():
# it exist
or you can do a try except method
try:
post_obj = Post.objects.get(pk=pk)
if user in post_obj.liked.all():
post_obj.liked.remove(user)
else:
post_obj.liked.add(user)
except:
# what happens if post does not exist

Symfony 3 Infinite Scrolling Ajax

I'm trying to make an infinite Scrolling in Ajax.
I really don't know what is missing.
Html Index:
<div class="container">
<!-- Menu -->
{% include '::announce/menu.html.twig' %}
{% for announce in announces|slice(0, 4) %}
<!-- Announce Preview -->
{% include '::announce/' ~ game ~ '/preview.html.twig' %}
{% endfor %}
</div>
<div id="content"> loop content </div>
<nav id="pagination">
<p>Page 2</p>
</nav>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('js/jquery-ias.min.js') }}"></script>
{% endblock %}
My controller index:
public function indexAction(Request $request, $game)
{
$em = $this->getDoctrine()->getManager();
$announces $em->getRepository('PlatformBundle:Announce')->byGame($game);
return $this->render('announce/index.html.twig', array(
'announces' => $announces,
'game' => $game
));
}
With this i have my index page with 4 announce
Now i show you my code for scrolling and adding more announce
Ajax File:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('announce_page', {'id': '2', 'game': game}) }}",
dataType: "json",
cache: false,
success: function (response) {
$("#content").append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
And this is the controller for page:
public function pageAction(Request $request, $game)
{
$em = $this->getDoctrine()->getManager();
$announces = $em->getRepository('PlatformBundle:Announce')->byGame($game);
$list = $this->renderView('announce/result.html.twig', array(
'announces' => $announces,
'game' => $game
));
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Last code, it's the html content for ajax (result.html.twig)
{% for announce in announces|slice(4, 4) %}
<!-- Affichage Annonce -->
{% include '::announce/' ~ game ~ '/preview.html.twig' %}
{% endfor %}
For resume, i have my index with 4 announce, when i scroll in bottom, i have a positive ajax request without error. But nothing appear after the 4 announce.
If i go to announce page 2 directly with pagination, i can see 4 other announce. So my routing is working but something don't works in ajax code i think.
Any idea? :)
Thanks

Submit button for a formset doesn't work when generated by ajax [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have a formset to update my models and I display forms from my formset based on the search query. I have an ajax keyup function to send post requests so I can generate search_results.html that I then pass to in search.html.
Now, if I generate the forms dynamically the submit button does not work. If I ditch the search and pass the content of search_results.html to search.html directly it does work.
I have two views, SearchReportView which supposed to be the main one, and SearchReports to handle generating the report. I guess I might just merge them at this point - it doesn't solve my problem though.
Also I had this working before when I used multiple forms but I had to switch to a formset.
body of search.html
<div class="container">
<div class="navbar">
<div class="navbarItem">
<img src="{% static 'back.png' %}" width="20px" height="12px" \>Back
</div>
</div>
<div>
<h3>Search:</h3>
{% csrf_token %}
<input type="text" id="search" name="search" />
<span class="button-checkbox">
<button id="mybutton" type="button" class="btn" data-color="primary">Recent</button>
<input type="checkbox" class="hidden" name="reports_checkbox" checked />
</span>
</div>
<div class="normalText" id="search-results"></div>
</div>
search_results.html
{% if reports_and_formset %}
<form action="/TP/auto/report/search/" method="post" enctype="multipart/form-data"> {% csrf_token %}
{{ formset.management_form }}
{% for x, form in reports_and_formset %}
<button type="submit" class="button" >Submit</button>
{{ form.checking_user }}
{{ form.comment }}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endfor %}
</form>
{% else %}
<tr> <td> <center>
No results found.
</center></td></tr>
{% endif %}
views.py
class SearchReportView(FormView):
def post(self, request, *args, **kwargs):
# form = ReportCommentForm(initial={'comment': ''})
# context = {'form': form}
if 'form-TOTAL_FORMS' in request.POST:
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(request.POST, queryset=single_day_enb_reports)
formset.save()
return HttpResponseRedirect('/TP/auto/report/search/report_search/')
# #requires_csrf_token
def get(self, request, *args, **kwargs):
return render(request, 'app/search.html')
class SearchReports(View):
def get(self, request, *args, **kwargs):
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm, max_num=single_day_enb_reports.count())
formset = report_form_set(queryset=single_day_enb_reports)
single_day_enb_reports_and_formset = zip(single_day_enb_reports, formset)
# context = {'single_day_enb_reports': single_day_enb_reports, 'formset': formset}
context = {'reports_and_formset': single_day_enb_reports_and_formset, 'formset': formset}
return render(request, 'app/search_results.html', context, context_instance=RequestContext(request))
#classmethod
def calculate_dates(self): #not important
def post(self, request, *args, **kwargs):
if 'form-TOTAL_FORMS' in request.POST:
single_day_enb_reports = SingleDayEnbReport.objects.all()
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(request.POST, queryset=single_day_enb_reports)
# if formset.is_valid():
formset.save()
return HttpResponseRedirect('/TP/auto/report/search/report_search/')
if 'button_state' in request.POST:
search_text = request.POST['search_text']
button_state = request.POST['button_state']
if button_state == 'false':
button_state = False
else:
button_state = True
if button_state:
now, fit_date = self.calculate_dates()
single_day_enb_reports = SingleDayEnbReport.objects.all().filter(
Q(last_modification_date__range=[fit_date, now]) & (
Q(alarms__contains=search_text)|
Q(enb__contains=search_text)|
Q(creation_date__date__contains=search_text) |
Q(last_modification_date__date__contains=search_text)|
Q(comment__contains=search_text)|
Q(checking_user__name__contains=search_text)))
else:
single_day_enb_reports = SingleDayEnbReport.objects.all().filter(
Q(alarms__contains=search_text)|
Q(enb__contains=search_text)|
Q(creation_date__date__contains=search_text) |
Q(last_modification_date__date__contains=search_text)|
Q(comment__contains=search_text)|
Q(checking_user__name__contains=search_text))
report_form_set = modelformset_factory(SingleDayEnbReport, form=ReportCommentForm,
max_num=single_day_enb_reports.count())
formset = report_form_set(queryset=single_day_enb_reports)
single_day_enb_reports_and_formset = zip(single_day_enb_reports, formset)
context = {'reports_and_formset': single_day_enb_reports_and_formset, 'formset': formset}
return render_to_response('app/search_results.html', context, context_instance=RequestContext(request))
ajax.js
$('#search').keyup(function(){
delay(function(){
if($('input[name=reports_checkbox]:checked').val()) button_state = true
else button_state = false
$.ajax({
type: "POST",
url: "/TP/auto/report/search/report_search/",
data: {
'button_state' : button_state,
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
}, 500 );
});
});
function searchSuccess(data, textStatus, jqXHR){
//generated data is put into search-results <div>field in search.html
$('#search-results').html(data);
}
Please change your this line
$('#search').keyup(function(){
with
$(document).on('keyup','#search', function(){

Categories

Resources