Posts tagged Code
Django: Sending mail with Templates
Jul 19th
It’s interesting how only a few lines of code can save so much work. A few days ago, I was working on adding a new feature to a system I wrote a while ago using django. I noticed there were a few places that I wanted to send out an email along with logging. I started looking into Django’s ability to send out emails, after much searching I found the mail_admins function. I wasn’t a huge fan of having the email content buried in the code. I did a few quick searches on the documentation and came up with no real solutions. Using Django’s render_to_response as an example I created a function that would allow me to send an email using a Django template.
from django.template import loader
from django.core.mail import mail_admins
def render_to_email(template, subject, context):
template = loader.render_to_string(template, context)
mail_admins(subject, template)
The function works exactly like Django’s render_to_response function, with one added value to the function for setting the email’s subject
render_to_email('email_general_error.html', 'General Error', { 'request': request, 'message': message})
Html5 LocalStorage, Client Side Memcached.
May 5th
Although HTML5 isn’t 100% finalized, there are a few things that have been finished up and implemented in the newer browsers. One such feature is a local storage, it doesn’t provide any fancy functions it’s more of a client side Memcached. It’s a persistent storage area that’s accessed using a key, value pair, attached to the window object.
window.localStorage['key'] = 'value'
Setting the value of the key is just a matter of assigning a variable. Obtaining an already saved value is also just as easy.
var value = window.localStorage['key']
Here is a small sample using a few basic functions to show how it might be used. You are able to enter text in the box and save it. when the page reloads that new value will display in the browser. When you click on load it will load whatever value is saved in the current storage.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Html LocalStorage</title>
<script type="text/javascript" charset="utf-8">
function save() {
obj = document.getElementById('btn_text');
if(obj.value)
window.localStorage['text'] = obj.value
}
function load() {
obj = document.getElementById('btn_text');
value = window.localStorage['text'];
if(value)
obj.value = window.localStorage['text'];
}
</script>
</head>
<body onload="load();">
<input type="text" value="" id="btn_text">
<input type="button" onclick="save();" value="Save"> | <input type="button" onclick="load();" value="Load">
</body>
</html>
Keep in mind that because of browsers are only starting to roll out these implementations now, it might not work in all browsers. Also be sure to use the most recent versions.
I’ll be writing and posting more HTML5 posts, giving examples and code on implementing some of the new exiciting things that will be out soon.
Java Rant #1
Feb 17th
Once apon a time, I to some extent spent time learning Java. It was not a lot of Java, and it wasn’t extremely indepth. It was more of a “get to know the language”; doing some simple database hits, very basic console and windows app. This was all back in 2000-2001 so much has changed since then. I have since learnt and worked with c#, Python, Ruby and have for the most part been happy with what these languages bring to the table.
In recent days I have been contemplating over working on a few personal projects, some being “desktop apps” and others being web apps. Normally I would have written any desktop apps with C#, but with my recent migration away from just windows I feel it might be a good time to give Java another chance.
It seems a lot of the things I really wasn’t a fan of are still there today, things that other languages have been able to overcome several years ago and Java still can’t seem to handle.
Properties
Why is it that a language as “young” as C# not only has been able to handle properties in a nice way but they have also been able to change it a second time allowing for “automatic” generation of “basic” properties…
Simple “Person” Class in C#
public class Person {
public string Name { get; set; }
public string Email { get; set; }
}
Similar class in Java.
public class Person {
protected String name;
protected String email;
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setName(String value) {
name = value;
}
public void setEmail(String value) {
email = value;
}
}
I guess you could expose the values in Java as protected to be public and change them directly, But if you need to make a change down the road where you need to add some sort of validation or something to these values, your left to putting it outside of the class that is responsible for the properties.
I am not turning away from Java, but I would think after so many years and so many implementations in other languages that something would have been implemented. Unless there is some hidden command I have not been able to find online or in documenation.
Django ModelForms With Foreign Keys
Feb 14th
I have recently been working more and more with django forms. In previous projects we decided not to use them mostly cause we couldn’t get them to do what we wanted them to do. In retrospect it was more of a lack of understanding how they worked and insufficient time to sit down and learn them.
Earlier in the week I was working with a model based form with a foreign key to another model. Problem I ran across was that I wanted said form to be displayed on the page, and also post the proper foreign key id without the user selecting it ( foreign keys are selected through a select box which can get quite large ). The page in which this form would be displayed would always know the foreign key id, so there would never need to be a situation where the form would ever need to show the user a select box.
After much trial and error, here is what I came up with.
from django.forms import ModelForm
from django import forms
from models import Thread
from models import Post
class ThreadForm(ModelForm):
class Meta:
model = Thread
fields = ('Message', 'user')
class PostForm(ModelForm):
class Meta:
model = Post
fields = ( 'Message', 'user')
The Post in question would normally have a foreign key in this instance to Thread, but we exclude it from the form so that it is not validated against or displayed to the user.
<form action="/post/{{ thread.pk }}/" method="post">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
In the actual form posting we are using the threads key in the url that is receiving the new post, If you were not using in the url, you could simple just add it as a hidden value on the page.
def post_add(request, thread_id):
a_form = PostForm(request.POST)
if(a_form.is_valid()):
post = a_form.save(commit=False)
post.thread_id = thread_id
post.save()
In the post_add view which accepts the thread_id and passes it to the method, we create the form based on the post data. validate it and save it. By adding the commit=False we stop the Form from saving the data to the database. and we return a model object. Which we can then pass along the thread_id and save it.
Their are a few things that could be added to the view for extra checking. We could do a lookup for a thread id and make sure its there, and do checks for request.method, or even add in handling for ajax requests. The example view isn’t complete and is only there as a quick sample of how to handle these types of forms.
