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>
Related
I am wanting an application to be able to check whether the user that is currently logged in is "test2". I'm using Django and running the following code:
<script>
console.log('{{ request.user }}')
{% if request.user == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</script>
And my console is logging the following:
test2
There was an error.
Why is this? How do I get the application to recognise that "test2" is logged in?
request.user.username
<script>
console.log('{{ request.user.username }}')
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</scrip
This may be because request.user is actully object, but __str__ is giving username attribute of User. So:
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
*Note:- I am assuming test2 is username and it is unique.
Since the logic is in template, it is being evaluated at server side. This means that request.user is not a string, it is a user instance.
The reason why the console.log('{{ request.user }}') prints out the username is when you print, __str__ is called which returns the username.
So you need to check with the correct field, i.e. the user.username.
<script>
console.log('{{ request.user }}')
{% if request.user.username == "test2" %}
console.log('The user that is currently logged in is test2.')
{% else %}
console.log('There was an error.')
{% endif %}
</script>
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
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 :))
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
The problem is that I cannot pass the paymentID variable that the PayPal script needs from PHP to JS. (Either this or the PHP script never runs).
I am following the steps here: https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/advanced-integration/#set-up-the-payment
and I'm stuck on step 4.
I've used the code from this tutorial: http://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html
Here is the HTML:
{% extends 'layout/master.twig' %}
{% block title %} {{ parent() }}PayPal {% endblock title %}
{% block head %}
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
{% endblock %}
{% block header %} Testing PayPal {% endblock header %}
{% block content %}
<div id="paypal-button"></div>
{% endblock content %}
{% block scripts %}
<script>
paypal.Button.render({
env: 'sandbox', // Optional: specify 'production' environment
payment: function(resolve, reject) {
var CREATE_PAYMENT_URL = 'http://patch-request.app/paypal/payment/create';
paypal.request.get(CREATE_PAYMENT_URL)
.then(function(data) {
alert(data);
console.log(data);
resolve(data.paymentID);
})
.catch(function(err) {
alert(data);
console.log(data);
reject(err);
});
},
onAuthorize: function(data) {
// Note: you can display a confirmation page before executing
var EXECUTE_PAYMENT_URL = 'http://patch-request.com/paypal/execute-payment';
paypal.request.post(EXECUTE_PAYMENT_URL,
{ paymentID: data.paymentID, payerID: data.payerID })
.then(function(data) { /* Go to a success page */ })
.catch(function(err) { /* Go to an error page */ });
}
}, '#paypal-button');
</script>
{% endblock scripts %}
And here is the script I'm trying to run:
public function create_payment ()
{
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setSku("123123")// Similar to `item_number` in Classic API
->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
->setSku("321321")// Similar to `item_number` in Classic API
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems([$item1, $item2]);
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
// $baseUrl = getBaseUrl();
$baseUrl = "http://patch-request.app";
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$request = clone $payment;
try
{
$payment->create($this->apiContext); //$payment is a JSON
}
catch (Exception $ex)
{
echo 'Sth went wrong';
}
$approvalUrl = $payment->getApprovalLink();
return json_encode(['paymentID' => $payment->id]);
}
Any ideas?
I've got no idea what templating system you're using but you could try this
{% block head %}
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
// add it here
<script>
window.paymentID = '<?= getPaymentID(); ?>'; // you need to implement this
</script>
{% endblock %}
Now you can access window.paymentID anywhere in you other JS