If you’re getting the following error when trying to activate an account using Django 1.4 and django-registration:

can't compare offset-naive and offset-aware datetimes

Then you need to update the source of django-registration manually.

The error file will tell you exactly what file to edit. In this case we need to edit:

registration/models.py

the full path to my file was:

/usr/local/lib/python2.6/dist-packages/registration/models.py

The next step is to import new timezone support:

from django.utils.timezone import utc

Next go to the bottom of the file, and find:

return self.activation_key == self.ACTIVATED or \
    (self.user.date_joined + expiration_date <= datetime.datetime.now())

And replace with:

 return self.activation_key == self.ACTIVATED or \
    (self.user.date_joined + expiration_date <= datetime.datetime.utcnow().replace(tzinfo=utc)) 

That should work now!

This is only a hack. I'm not even sure if it's correct. So if you do come across this and you can do better, please let me know.

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·

As you should know, the Django team released has released version 1.4 

My servers are running on Ubuntu, and to upgrade all I needed to do was use setup-tools:

easy_install --upgrade django

This will find Django 1.4 and upgrade your current version for you.

To check what version you’re currently running:

django-admin --version

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·

If you need to add a content type to your filefield do this: (i.e. PDF only)


file = models.FileField(upload_to='uploads/', validators=[validate_pdf])

Then create a new file in app/validators.py and:

from django.core.exceptions import ValidationError
def validate_pdf(value):
    if not value.read(5) == '%PDF-':
        raise ValidationError("This file is not in PDF format.")

Then add it via django app.validators import validate_pdf
If you’re having problems viewing whatever you uploaded via admin panel, check your settings.py for MEDIA_ROOT etc.

Tags: , , ,

· · · ◊ ◊ ◊ · · ·

When you’re on to creating forms in django, it can be a bit of a  headache (I was pulling out my hair!)

Disclaimer: make sure you read the documentation on ModelForms.

All I wanted to do was instead of allowing a user to choose which user they’re going to be when posting something, I wanted it to be the one logged in/currently authenticated.

Luckily, there are some awesome people around such as Prometheus, on the irc.Freenode.net #django channel who helped me with this.

For example, you have a model for a basic blog:

class Blog(models.Model):
    user = models.ForeignKey(user)
    title = models.CharField(max_length=30)
    post = models.CharField(max_length=200)

Now we make a ModelForm so that we can automatically generate some nice HTML without getting dirty:

class BlogForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(BlogForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        instance = super(BlogForm, self).save(commit=False)
        if self.user:
            instance.user = self.user
        return intance.save()

    class Meta:
        model = Blog
        exclude = ('user')

Let’s say you want to make a view to pass this to your template:

 

@login_required
def new_post(request):
    blog = Blog()
    if request.method == 'POST':
        form = BlogForm(data=request.POST, instance=blog, user=request.user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/blog/')
        else:
            print "it all went shit"
    else:
        form = BlogForm(instance=blog, user=request.user)

    return render_to_response('new_blog.html',  {'form' : form}, context_instance=RequestContext(request))

And voila! It should work. You basically, inside the ModelForm (BlogForm) you can set your own save functions. Piece of cake, now that you know how it works. :)

 

Tags: , ,

· · · ◊ ◊ ◊ · · ·

Twig Template Engine

30 Dec 2010

EDIT: nl2br() with Twig tutorial: twig-nl2br

A while back I started to learn django, and I absolutely loved it. However, I was so used to PHP for my web development, I naturally went back.

Then I found Twig! I’ve started using this in my latest project, and oh my! It’s an amazing little template engine. It’s definitely the best one I’ve ever used for PHP and the best thing is the fact it reminds me so much of how django does their templates. It’s very quick and easy to put in new themes, modify them… it’s a life-saver.

Some of the coolest things with Twig, is the fact you can do the whole nl2br (http://php.net/nl2br) stuff inside the template engine, for example:

{{ show_content|nl2br }}

How cool is that?! Another one, is transforming a raw timestamp to something much more readable. Ah, it’s a lifesaver.

I suggest you go visit the Twig site: http://www.twig-project.org/
And read the docs for template design: http://www.twig-project.org/doc/templates.html

P.S. I forgot to mention, the extensions are so easy to code for, and even easier to add to your project!

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·