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
Related
I have a model:
lifecycle_status_choice = (
('Lead', 'Lead'),
('Opportunity', 'Opportunity'),
('Customer', 'Customer'),
)
bill_status_choice = (
('Paid','Paid'),
('Pending','Pending'),
('Partially Paid','Partially Paid'),
)
class Bill(models.Model):
company_name = models.ForeignKey(Contact, on_delete=models.CASCADE)
grand_tot = models.DecimalField(max_digits=9, decimal_places=2)
status = models.CharField(max_length=100, choices=bill_status_choice)
lifecycle_status = models.CharField(max_length=100, choices=lifecycle_status_choice)
...
which has a fk to:
class Contact(models.Model):
associated_company = models.CharField(max_length=100)
...
Views.py
...
from bills.models import Bill
from django.db.models import Sum
def home(request):
data = Bill.objects.all().order_by('date')
context = {
'data ':data ,
}
return render(request, 'home.html',context)
Front end chartsjs:
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [
{% for data in data %} '{{data.company_name}}', {% endfor %}
],
datasets: [{
label: '# of Votes',
data: [{% for data in data %} {{ data.grand_tot }}, {% endfor %}],
The problem:
I am using charts.js in my front end template and I am trying to display a chart in which as a user creates new company names the chart should display the total amount grouped by company names how would I achieve that?
eg:
I create two invoices for "xyz" company with amounts: $100 & $200 || & create one invoice for "abc" company with amount $100
I want the chart to group the "xyz" invoice amounts and display $300 (ie:100+200) || & "abc" = $100
FYI I'm aware I'm using something completely wrong in the view function but its just something that I tried.
Thanks
You can .annotate(…) [Django-doc] with:
from django.db.models import Sum
Contact.objects.annotate(bills_total=Sum('bill__grand_tot'))
The Contact objects that arise from this QuerySet will have an extra attribute .bills_total.
You can filter this with as satus paid with:
from django.db.models import Q, Sum
contacts = Contact.objects.annotate(bills_total=Sum('bill__grand_tot', filter=Q(bill__status='Paid')))
You can thus for example render this with:
{% for contact in contacts %}
{{ contact.associated_company }}: {{ contact.bills_total }}
{% endfor %}
or convert it to a list of Python dictionaries for example and then return it as a JSON blob.
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 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 want to build a table with Google Charts that will contain information about teams, what people are in the team and what roles they have inside the team.
One problem I have encountered is that some fields is empty in the database, but it should still be added to the same row in the table.
An example of how I want it to look is like this:
TeamName Members Role Contract Country City
Joe Doe Programmer Own Staff Greenland Nuuk
Jane Doe Design
I have built this so far but the problem is that only one of my objects in the database have all information, so only that person was added in the table
function drawChart() {
// Table-chart with the teams
var data = new google.visualization.DataTable();
data.addColumn('string', 'TeamName');+
data.addColumn('string', 'Members');
data.addColumn('string', 'Role');
data.addColumn('string', 'Contract');
data.addColumn('string', 'Country');
data.addColumn('string', 'City');
_teams = []
_object = []
{% for obj in object_list %}
{% for team in obj.team.items %}
{% for role in obj.role.items %}
{% for contract in obj.cont.items %}
{% for location in obj.loc.items %}
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}
google.visualization.Table(document.getElementById('table-div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
Anyone have any idea of how I can solve this?
I would like to include JavaScript inside a form widget in Symfony2, but quotes are escaped inside the JavaScript command, see:
{{ form_widget(form.sdf,
{ 'attr': { 'value': "document.MSketch.getMol('sdf');" } }
) }}
and the result I get:
<input type="hidden" id="form_sdf" name="form[sdf]" required="required" value="document.MSketch.getMol('sdf');" />
I have read this topic : Twig and autoescaping
But autoescape false is not working when using it like this:
{% autoescape false %}
{{ form_widget(form.sdf,
{ 'attr': { 'value': "document.MSketch.getMol('sdf');" } }
) }}
{% endautoescape %}
How to have quotes?
EDIT: Using raw filter isn't helping:
{% set cmd = 'document.MSketch.getMol("sdf");' %}
{{ form_widget(form.sdf, { 'attr': { 'value': cmd|raw } } ) }}
But raw filter is working outside of the form_widget, so where is the problem?
Have you tried to simply escape quotes? \' or \"