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>
Related
I am trying to retrieve below field values in nunjucks following below template
Json data -
{
"user": {
"custom": [
{
"payload": "{ f_name=user, l_name=name, source=facebook, contact=email }"
}
]
}
}
Nunjucks Template -
{% set u = user %}
{% set data = u['custom'][0]['payload'] %}
Hello {{ data }}
This returns the below output
Hello { f_name=user, l_name=name, source=facebook, contact=email }
However, I would like to get the individual elements from the {{data}}
How can I fetch the f_name, l_name, source, contact fields from the above json data.
Please note the payload is a string and not a json object
You don't show us how user is pulling your JSON data into nunjucks, so I'll just spill out my take on this. Take advantage of the JavaScript split method, and the template engine loops and filters to give you the results you need.
I'm assuming there is more to your JSON data. If so, here is a short guide to help pull your 4 string items out of payload.
The JSON Data:
//sample JSON Data
const sampleData = [{
"user": {
"custom": [{
"payload": "{ f_name=user, l_name=name, source=facebook, contact=email }"
}]
}
}];
module.exports = sampleData;
The View:
{% for string in mSampleData %} //mSampleData is similar to your "user" template object.
{% for mval in string['user']['custom'] %}
{% set mstring = mval['payload'].replace('{', '').replace('}', '') %}
{% set marray = mstring.split(",") %}
{% set fname = marray[0].replace('f_name=', '') %}
{% set lname = marray[1].replace('l_name=','') %}
{% set source = marray[2].replace('source=','') %}
{% set contact = marray[3].replace('contact=','') %}
<p>{{fname}}</p>
<p>{{lname}}</p>
<p>{{source}}</p>
<p>{{contact}}</p>
{% endfor %}
{% endfor %}
The results:
user
name
facebook
email
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>
I am a little bit stuck on my Symfony code.
Let me explain,
I have a todo-list table in my database containing :
An ID called : id
A name field called : todo
And 3 others fields that don't matter : "completed", "created_at", "updated_at".
Before going further : here is my codes,
The concerned Controller :
/**
* #Route("/todos/delete/{id}", name="todo.delete", methods={"POST"})
* #param Todo $todo
* #param ObjectManager $manager
* #param Request $request
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function delete(Todo $todo, ObjectManager $manager, Request $request)
{
$manager->remove($todo);
$manager->flush();
if ( $request->isXmlHttpRequest()) {
return $this->redirectToRoute('todo.home', [
'id' => $todo->getId()
]);
}
throw $this->createNotFoundException('The todo couldn\'t be deleted');
}
The view :
{% extends 'base.html.twig' %}
{% block title %}Todos{% endblock %}
{% block content %}
<br>
<form action="{{ path('todo.create') }}" method="post">
<input type="hidden" name="token" value="{{ csrf_token('todo-create') }}"/>
<label for="todo">Todo</label>
<input type="text" id="todo" name="todo" class="form-control input-group-lg" placeholder="Create a new todo">
</form><br>
{% for todo in todos %}
{{ todo.todo }}
Update
x
{% if todo.completed %}
Completed !
{% else %}
Mark as completed
{% endif %}
<hr>
{% endfor %}
{% endblock %}
We focus on :
x
The JavaScript :
$(document).ready(function () {
$('.js-delete-todo').on('click', function (e) {
e.preventDefault();
var url = $(this).attr('href');
delTodo(url);
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
$('#id').remove();
}).fail(function () {
alert('Could not be deleted');
});
}
});
});
Actually,
Everything seems to work : it does a POST ajax request, and delete the row in my table in my database.
The only issue is that I have to hit F5 to see it.
How can I make it work without reloading the page nor hitting the F5 hotkey?
In your symfony code you should return JSON format like here.
Wrap your todo in container like this
{% for todo in todos %}
<div id="todo-{{todo.id}}">
// your todo staff here
</div>
{% endfor %}
Then change your javascript to
function delTodo(url) {
$.ajax({
type: "POST",
url: url
}).done(function (data) {
var id = JSON.parse(data).id;
$('#todo-' + id).remove();
}).fail(function ()
alert('Could not be deleted');
});
}
I have a function in Django that I need to create a confirmation popup for the user... The function contains lots of conditions, I need to create this popup without a huge change in the code. It took a lot of time, I found "return confirm" for the button .. but I can't change the design of the popup.
The function is :
def start(request):
user = request.user
ctx = {
'id-1': request.GET.get('id-1'),
'start_order': StartOrder.objects.filter(
user=user, status='ru'),
}
initial = {
'email': user.email or '',
'password': user.password or '',
}
The initial form should be appear before the confirmation popup
if request.method == 'GET':
ctx['form'] = Form(initial=initial)
ctx['can_create'] = user.can_create()
return render(request, 'orders.html', ctx)
After the confirmation popup:
if request.GET.has_key('id-1'):
test = get_object_or_404(Test, id=request.GET.get('id-1'))
form = Form(request.POST, request=request)
if form.is_valid():
if not user.can_create_order():
return Http404()
ctx['form'] = Form(initial=initial)
ctx['can_create'] = user.can_create_order()
user.email = request.POST.get('email')
user.password = request.POST.get('password')
user.save()
if request.GET.has_key('id-1'):
send_order(test)
ctx['started'] = True
return render(request, 'orders.html', ctx)
orders.html:
{% if id-1 %}
<form class="user-form " method='post'>
{% csrf_token %}
<div class="errors">
{{form.non_field_errors}}
</div>
<div class="form-group">
{% for field in form %}
{{field}}
{{field.errors}}
{% endfor %}
</div>
The button where should the popup appears after click:
<input type='submit' value='Start Automated Order' onclick="return confirm('Are you sure you want to continue?');">
</form>
{% else %}
{% endif %}
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