I'm encountering a very strange error. I have an app ID defined in my settings.py file like so:
CARDSPRING_APP_ID = '################'
This works on nearly every page in my site, except for one. Strangely enough, other variables work. In a script section on the page, I have the following:
alert("cs appid=" + {{ CARDSPRING_APP_ID }} +
" sectoken=" + {{ securityToken }} +
" timestamp= " +{{ timestamp }} +
" hash = " + {{ digestedHash }} +
" ccnum " + $('.card-number').val() +
" exp" + $('.expiration-month').val() + $('.expiration-year').val() +
" user = " + {{ csid }});
When the page is rendered, it evaluates to this
alert("cs appid=" + +
" sectoken=" + DDFJRMZXD12WVWHFFC###### +
" timestamp= " +1346183125 +
" hash = " + a929b3aec9179c700c09d###### +
" ccnum " + $('.card-number').val() +
" exp" + $('.expiration-month').val() + $('.expiration-year').val() +
" user = " + SG1###);
Importantly, {{ CARDSPRING_APP_ID }} has evaluated to nothing. Does anyone know why this might be the case? Thank you!
UPDATE
I tried creating a context_processors.py file as described in the answer below, and made sure to add it to the appropriate spot in settings.py . I still don't have any luck -- it evaluates on one page, but not on the other
UPDATE 2
The template is called with this command:
return render_to_response('howto'+str(number)+'.html',locals(),context_instance= RequestContext(request))
UPDATE 3
Got it to work -- needed to add this to my settings.py
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
"myapp.context_processors.cardspring",
)
Create a file called context_processors.py and write the following context processor:
from django.conf import settings
def cardspring(request):
return { 'CARDSPRING_APP_ID': settings.CARDSPRING_APP_ID }
Then add your.location.context_processors.cardspring to TEMPLATE_CONTEXT_PROCESSORS in your Django settings file, where your.location is the location of your context_processors.py file.
Related
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to edit the Review objects associated with an instance of Movie.
models.py
class Movie(models.Model):
title = models.CharField(max_length=160)
class Review(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews')
author = models.CharField(max_length=150)
active = models.BooleanField(default=True)
views.py
# Create and save movie object
movie = Movie(title="Nightcrawler")
movie.save()
# Create and save two review objects
review1 = Review(movie=movie, author="John", active=True)
review2 = Review(movie=movie, author="Rob", active=False)
review1.save()
review2.save()
print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
active_reviews = movie.reviews.filter(active=True)
print("There are " + str(len(active_reviews)) + " active reviews.")
movie.reviews.set(active_reviews)
movie.reviews.first().author = "Abby"
# Try and save both objects just for good measure.
# Not sure if it is necessary to do this. Does not
# seem to work anyway
movie.reviews.first().save()
movie.save()
print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
print("Author of the first review is: " + str(movie.reviews.first().author))
The output of the views.py code is as follows:
Before: Nightcrawler has 2 reviews.
There are 1 active reviews.
After: Nightcrawler has 2 reviews.
Author of the first review is: John
I want and expected the changes made to movies.reviews to be saved, but the output reveals that neither the set() method or changing the author value actually alters the Movie instance. Why are none of these edits being preserved?
Interestingly, the line movies.reviews.first().delete() does seem to actually remove the first review. I am curious why this works and the other changes do not.
Thank you for your time!
If you want to manipulate the object, you should store it in a variable first
movie = Movie(title="Nightcrawler")
movie.save()
# Create and save two review objects
review1 = Review(movie=movie, author="John", active=True)
review2 = Review(movie=movie, author="Rob", active=False)
review1.save()
review2.save()
print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
active_reviews = movie.reviews.filter(active=True).all()
print("There are " + str(len(active_reviews)) + " active reviews.")
movie.reviews.clear()
movie.reviews.set(active_reviews)
first_review = movie.reviews.first()
first_review.author = "Abby"
first_review.save()
movie.save()
It's not being saved because the object you updated is not the same with the object you saved because you ran another query by calling first() again.
If you intend to only keep the "active" reviews, you can use remove instead to remove inactive reviews.
movie.reviews.remove(*movie.reviews.filter(active=False))
set does not have any effect here because the active_reivews you passed as parameter is already linked or already set. If you want to stick with set, do a clear first.
How do I utter a message, displaying results based on a datasheet, and attach a hyperlink within the text? Example of what I am trying to achieve:
num = phone_format(str(sheet["" + chr(ord(requested_info_column)+1) + "{}".format(row)].value))
dispatcher.utter_message(text="The " + column_names[requested_info_column]
+ " for the " + str(sheet["B{}".format(row)].value) + " project is "
+ str(sheet["" + str(requested_info_column) + "{}".format(row)].value)
+ " and can be reached at " + num)
formatting method:
def phone_format(n):
formatNum = '({}){}-{}'.format(n[0:3], n[3:6], n[6:])
hypNum = '%s' % (n, formatNum)
return hypNum
The issue I am having is that Rasa X displays the string, with the correct data, but the hyperlink is not attached to the phone number.
Displaying links in the front end is different for different platforms. Rasa X uses Markdown Format to display the links.
So, instead of the normal anchor tag, you need to use Markdown link format for display.
Change
hypNum = '%s' % (n, formatNum)
to this
hypNum = '[%s](tel:%s)' % (formatNum,n)
Hope this solves your issue.
I want to pass data from my Django view to my html and then take the data to my chart js or pass the data directly to my amchart.
views.py:
def nodo_detail(request,nodo_id):
El_Nodo = Nodo.objects.get(pk=nodo_id)
all_nodos = Nodo.objects.order_by('pk').all()
var = Variable()
v = dir(var)
elemento = El_Nodo.variable_set.order_by('pk').all()
watts = elemento.last().Watts
prefix = ''
chartData = "["
for t in elemento:
chartData += prefix
chartData += "{\n"
chartData += " date: "
chartData += '"' + str(t.Data_time.year) + "-"
chartData += str(t.Data_time.month) + "-"
chartData += str(t.Data_time.day) + " "
chartData += str(t.Data_time.hour) + ":"
chartData += str(t.Data_time.minute) + ":"
chartData += str(t.Data_time.second) + '"' + ",\n"
chartData += " value:"
chartData += str(t.Watts) + ",\n"
chartData += " volume: "
chartData += str(t.Watts) + "\n }"
prefix = ", "
chartData += "]"
context = {'El_Nodo': El_Nodo,
'all_nodos': all_nodos,
'v': v,
'watts': watts,
'chartData':chartData,
"asdf":json.dumps(chartData)}
return render(request, 'inicio/detail.html', context)
The data that I want to pass is chartData, with the for loop I try to do the JSON format also I try the JSON python librery.
detail.html:
{% block Stock %}
<input type="hidden" id="stock" value="{{chartData}}"> <!-- or asdf-->
{% endblock%}
amchartjs:
var chartData = JSON.parse(document.getElementById("stock").value);
// or directly
var chartData = JSON.parse('{{ chartData }}');//or asdf
I understand that with this way it is necessary refresh the whole web page to view new data, Also like to know how to do it dynamic? Thanks and sorry for bad english
Make an AJAX call that returns an array, and you populate this in JavaScript. This implies to make a JSON view that returns a JSON array. Like this:
class QueryResultsView(generic.TemplateView):
template_name='your_template.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(QueryResultsView, self).get_context_data(**kwargs)
# Create a variable you fill
context['my_big_sql'] = MyModel.objects.filter(blabla=blibli)
return context
And from there, in your template file (this is your template file, not a JavaScript file) general_study_results.html add something like:
<script>
var myData =
{% for row in my_big_sql %}
{{ row.column }}{% if not forloop.last %},{% endif %}
{% endfor %};
</script>
And then you have all your data in your HTML file ready to be used via amchartjs or any library you want.
I fail to select a form using its name with Mechanize in rails. The source code of the page I am trying to take data from looks like this:
var strAccesBamPoppin = "";
if(!emailing){
strAccesBamPoppin = '<form name="bamaccess_' + idTCM + '" id="bamaccess_' + idTCM + '" class="bamaccessDecloi" autocomplete="off" method="post" action="'+chemin+'"';
if (typeConnexion == "True") {strAccesBamPoppinPoppin = strAccesBamPoppin +'>';
With python, I would use something like
XX.select_form('bamaccess')
What would be the equivalent with Ruby? Thanks.
XX.forms.select{|x| x[:name][/bamaccess/]}
The above should work for sure.
XX.forms_with(name: /bamaccess/)
This will return an array of all the forms with a name containing bamaccess
Keep in mind that /string/ is a regexp since the name will contain bamaccess_*****
I'm trying to send email message in one of my views and would like to format the body of the message, such that it shows in different lines.
This is a snippet code in views.py:
body = "Patient Name: " + patient_name + \
"Contact: " + phone + \
"Doctor Requested: Dr. " + doctor.name + \
"Preference: " + preference
email = EmailMessage('New Appointment Request', body, to=['ex#gmail.com'])
email.send()
The email is shown like this:
Patient Name: AfrojackContact: 6567892Doctor Requested: Dr. IrenaPreference: Afternoon
How do I make it show like this:
Patient Name: Afrojack
Contact: 6567892
Doctor Requested: Dr. Irena
Preference: Afternoon
I suggest to use the django template system to do that.
You could do:
```
from django.template import loader, Context
def send_templated_email(subject, email_template_name, context_dict, recipients):
template = loader.get_template(email_template_name)
context = Context(context_dict)
email = EmailMessage(subject, body, to=recipients)
email.send()
```
The template will look like: this could for example be in the file myapp/templates/myapp/email/doctor_appointment.email:
```
Patient Name: {{patient_name}}
Contact: {{contact_number}}
Doctor Requested: {{doctor_name}}
Preference: {{preference}}
```
and you will use it like
```
context_email = {"patient_name" : patient_name,
"contact_number" : phone,
"doctor_name": doctor.name,
"preference" : preference}
send_templated_email("New Appointment Request",
"myapp/templates/myapp/email/doctor_appointment.email",
context_email,
['ex#gmail.com'])
```
This is very powerfull, because you can style all the email in the way you want,
and you re-use the same function over and over, just need to create new template
and pass appropriate context/subject and recipietns
you should add '\n' for newlines.
or you could try this:
body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)
or, if you are using python >= 3.6:
body = f'''Patient Name: {patient_name}
Contact: {phone}
Doctor Requested: Dr. {doctor.name}
Preference: {preference}'''
You are going right but you just missed a letter n
body = "Patient Name: " + patient_name + "\n"
+ "Contact: " + phone + "\n"
+ "Doctor Requested: Dr. " + doctor.name + "\n"
+ "Preference: " + preference
This will add new line after each and every line and most probably solve your problem.
this should do the trick for breakline:
\n