What's new in Django community blogs?

Django + Apache no Windows

May 09 2007 [Archived Version] □ Published at PyMan under tags  django

Com a crescente divulgação do django aqui no Brasil, muitos estão começando a testar e usar esse WebFramework.

A maioria dos desenvolvedores usam o 'manager.py runserver' para fazerem seus testes com django no windows, ou por falta de necessidade de usaru m servidor para testes ou por não conseguir configurar um.

No post de hoje vou mostrar a instalação e configuração do Django em ambiente Windows utilizando apache + modpython.

Os programas utilizados são:
Python 2.4.4
Apache 2
ModPython 3.2.8
Django 0.95.1

1 - Instalando o Python
Para instalar o Python no Windows é só dar duplo clique no arquivo .msi e seguir o guia de instalação

2 - Instalando o Apache

Para instalar oapache no windows é só dar um cuplo clique no executável e seguir o guia de instalação.

Para testar o apache é só acessar http://localhost


3 - Instalando o modpython

Para instalar o modpython é só dar um cuplo clique no executável e seguir o guia de instalação. No final da instalação é só informar a pasta em que o apache foi instalada.

Depois abra o arquivo 'http.conf' que fica dentro da pasta 'conf' do apache e adicione esta linha:

LoadModule python_module modules/mod_python.so

4 - Instalando o django

Descompacte o arquivo .tar.gz baixado no site do django.

Abra o prompt de comando, geralmente encontrado em "Iniciar > Programas > Acessórios > Prompt de comando", e entre na pasta descompactada.

Digite o comando:

python setup.py install

e o django será instalado.

5 - Configurando o django no apache

Abra novamente o arquivo 'http.conf' e adicione no final do arquivo:

<Location "/meusite/">
SetHandler python-program
PythonPath "['C:\django_sites'] + sys.path"
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE teste.settings
PythonDebug On
</Location>

onde meusite é o endereço virtual. Ex: http://localhost/meusite

No python path a pasta colocada tem que ser aonde estão os projetos feitos em django, no nosso caso foi 'C:\django_sites'.

e o teste.settings é o arquivo settings.py do seu projeto feito em django, onde teste é o nome do projeto.

Agora é só iniciar o apache e ver em http://localhost/meusite o django funcionando!



djanger = Django developer

May 09 2007 [Archived Version] □ Published at PyMan under tags  django

Durante uma conversa com o Marinho, onde estávamos falando sobre a falta de sistemas em django, como cms, blogs, wikis e acabou saindo uma nova expressão: djanger, onde djanger é a pessoa que utiliza o django.

Sent at 12:22 PM on Saturday

Andrews Medina:
heheh verdade :p

Marinho Brandão:
… e ir oferencendo o serviço a djangers (essa expressão eu acabei de inventar… ehhe ) e ganhar dinheiro com AdSense


Nessa conversa tambem nasceu um novo projeto o 'bingo!'. Ainda não sei se será esse nome mesmo, mas em breve terão notícias sobre ele.



How to add a preview page

May 07 2007 [Archived Version] □ Published at orestis.gr

When using the django web administration page to add blog posts, it's nice to be able to preview the post to catch layout glitches, typos and markup issues. The best way to do this is to have a preview page.

To add a preview page, the model should have:

  1. a boolean field that determines whether the post is public or not
  2. a smart get_absolute_url function.

Separate your posts

The first is easy:

    is_public = models.BooleanField(default=False)

Make your URLs smart

The second:

 def get_absolute_url(self):
    if self.is_public:
        return "/%s/blog/%s/%s/" % (self.language, 
           self.pub_date.strftime("%Y/%m/%d").lower(), self.slug)
    else:
        return "/%s/blog/preview/%d" %(self.language,self.id)

The django admin uses the get_absolute_url function to put a "Display on site" button on an object's page. So when you have public entries, you get to see what all the world sees, but when an entry is not public, the get_absolute_url function returns a special url.

Add a pre-view

The final piece to the puzzle is to have a view that is protected:

   @login_required 
   @user_passes_test(lambda u: u.is_staff)
   def entry_preview(request, entry_id):
      entry = get_object_or_404(Entry, pk=entry_id)
      return render_to_response('entry_detail.html', {'entry':entry}, 
        context_instance=RequestContext(request))

I use the is_staff property, but this can easily be changed to something else.

Don't forget to add the relevant url to your urls.py :

(r'^preview/(?P<entry_id>\d+)/$', entry_preview),

That's all!

You gotta love Django. I got from idea to implementation, and of course blog post in about 30 minutes! And, most of which I was hunting a bug in my middleware which trashed the account login redirect.

Comments


Going international, pt. 1

May 06 2007 [Archived Version] □ Published at orestis.gr

Introduction

From the start, I was interested in making the content posted here available in two languages: Greek and English. This is no small feat, and I thought long and hard on how to make it possible and get it working just the way I like it. So here is a rundown of how internationalization works here:

The prerequisites are not many:

  1. Make the content available in both languages.
  2. Make the interface available in both languages.

I have slacked and made the tags English-only. Maybe I'll fix that later on, but it'll do for now.

Approaches

Now, you have two choices about making a site handle international visitors. You either:

  • let them decide what language they prefer, by providing the choices somewhere in your interface or,
  • try to use their request data (like the IP address, or the language preference sent by their browser) to decide their preferred language.

The first approach is the most foolproof, as a user explicitly chooses his language. He can't be wrong, can he? But, there is a snag: what is the first page he sees? If it is in his own language, there's no problem. But if it is in another language, he'll get confused and probably leave. Advanced users may scan the interface for visual clues to change the language (if they know they have this option). With first impressions being so important, you shouldn't scare your visitors away.

This is solved by the second approach, mostly. However, the problem there lies in that a) the location of the user not always matches their language, b) most users never set their language preference in their browser anyway (I have no source for this, it's just a gut feeling) and c) the user has no visible choice in your site. If you guess wrong, he can't change it, so he leaves.

Solution

Well, this leaves us with the only sensible approach: Combine these two. So this is what I've done, of course aided by Django.

We first try to find implicit facts that point to a language. In Django, this is done using the LocaleMiddleware:

LocaleMiddleware tries to determine the user’s language preference by following this algorithm:

  • First, it looks for a django_language key in the the current user’s session.
  • Failing that, it looks for a cookie called django_language.
  • Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations.
  • Failing that, it uses the global LANGUAGE_CODE setting.

This is a pretty good approach, as it handles both new and returning visitors.

We also provide a simple interface, the two little flags on the right edge of the header, to give the option of setting the language explicitly. This should cover us but...

Search engines

Unfortunately, we have to deal with search engines, too. Crawlers don't have sessions, nor accept cookies, nor emit Accept-Language HTTP headers. So they'll reach only your default language. If we continue this reasoning, you'll have issues with incoming links too: When I link to a page that is in Greek, I'll expect my link to point in the same version. So we have to somehow put the language information on the URL too. Since we have everything translated, it makes sense to put the language in the lowest level possible:

http://www.example.com/en/
http://www.example.com/el/
http://www.example.com/fr/

etc.

So now, if someone links to a page, he also links to a language. So far so good. What about our first page, without any paths appended ? What would come up if someone bookmarked http://www.example.com ? Of course we will use the discovery mechanism described above and redirect him to the language we guess. This will work with crawlers too, as they handle redirects. The crawler will also find the language setting flags and will happily index all our languages, since now they have distinct URLs.

Final thoughts

There's also the possibility that a visitor will follow a link that is in another language than his own. We could try to redirect him to his preferred language, but this will put us back in the first, half-baked approach. Plus, he'll never be able to view content in another language, unless he clears his session and cookies, and change his preferred language in his browser. Instead, we'll just give him a discreet message in his preferred language notifying him that the content he is viewing is also available in another language, and give him the link to it.

Disclaimer

I haven't implemented any of this at the time of writing. I'll try to, and present the code and results in the part 2 of this article.

Comments


Another django-restful-model-views Update

Apr 27 2007 [Archived Version] □ Published at stonemind consulting under tags  django rest

As I mentioned a few weeks ago, Andreas Stuhlmueller has proposed a general REST API for Django, and as his ideas and mine seemed very compatible, we began talking about collaborating on a joint solution.


Καλώς ήλθατε

Apr 27 2007 [Archived Version] □ Published at orestis.gr

Επιτέλους αποφάσισα να φρεσκάρω το blog μου - νέος σχεδιασμός, νέες λειτουργίες, με 1 λέξη κα-τα-πλη-κτι-κο (και ελπίζω όχι πληκτικό :)

Γιατί όμως να το κάνω αυτό; Ποιος νοιάζεται; Βασικά εκτός από μένα (και είμαι αρκετά εγωκεντρικός για να είναι αυτό αρκετό) νοιάζεσαι εσύ αγαπητέ αναγνώστη, που κάθεσαι και διαβάζεις τις ασυναρτησίες που γράφω (την πάτησες ;). Εντάξει, δεν είναι αρκετό αυτό για να σου κρατήσει το ενδιαφέρον, οπότε όριστε, θα κάνω μια προσωπική αποκάλυψη (τρρρρρρρρ-πσχσ! (τύμπανα)):

Είμαι ΠΑΠΑΤΡΕΧΑΣ!

Ναι ναι, ΠΑΠΑΤΡΕΧΑΣ! Έχω καταπιαστεί με χίλια-δυο πράγματα και τα έχω αφήσει όλα στη μέση. Φωτογραφία, μουσική, ιστιοπλοΐα, τα κοινά, υπολογιστές (αυτό και αν έχει ζουμί), gadgetάκια, όλα με ενθουσιάζουν για λίγο καιρό, διαβάζω, μαθαίνω, ξοδεύω και μετά τα παρατάω και πιάνουν σκόνη, είτε κάπου στο χαοτικό δωμάτιο μου, είτε στον επίσης χαοτικό εγκέφαλο μου. Γι' αυτό λοιπόν αποφάσισα να το ρίξω στο γράψιμο, μπας και ασχοληθώ λίγο παραπάνω με τα ενδιαφέροντα μου. Και για προστιθέμενη αξία, μένει η πληροφορία και on-line μήπως ενδιαφέρεται και κανένας άλλος. (Στην πραγματικότητα, με έπιασε το παπατρεχιλίκι μου (παπατρεχάλα;) και ήθελα να φτιάξω δικό μου μηχανισμό για blog, και πρέπει να γράψω διάφορα για να γεμίσει. Το είπα και ξαλάφρωσα.)

Αυτά λοιπόν για τώρα. Θα ακολουθήσει μια σειρά με άρθρα στυλ "Πώς γυρίστηκε" όπου θα περιγράφονται αναλυτικά όλοι οι μηχανισμοί που χρησιμοποιούνται για να λειτουργήσει αυτό το blog. Μείνετε στο κανάλι σας...

Comments


Welcome

Apr 27 2007 [Archived Version] □ Published at orestis.gr

I've finally managed to refresh my blog - new design, new functionality, oh my! I hope you like it :)

But why do this? Who cares? Well, apart from me (and I'm really self-centered enough to make this enough), you care, my dear reader, sitting there reading my mumblings (there you are ;). OK, that's not enough to keep you interested, so I'll make a genuine self announcement:

I'm a jack of all trades!

...and master of none. I've dabbled in lots and lots of stuff, only to abandon them later on. Photography, music, sailing, politics, computers (this is big), gadgets, you name it. I get all worked up about one thing, I study it, learn it, spend money on it and after a while the excitement has wore off and I leave it gathering dust somewhere in my chaotic room or in a corner of my chaotic brain. So this is why I decided to start writing, hoping that I will spend some more time doing things I really like. And, to add some value, all the information will be available on-line to everybody interested. (Well, really, I just wanted to create my own blog software, and I need to write stuff to fill it. There you go. I feel much better.)

That's all for now. I'll follow up with a series of posts that will describe the "making of" of this blog. So stay tuned...

Comments


OpenID Session Middleware for Django

Apr 24 2007 [Archived Version] □ Published at zerokspot.com

Simon Willison just did something that will probably save me a week or so on my way to [email protected]: He released an OpenID consumer app for django. From what I’ve read so far, this one doesn’t (yet!) integrate itself into Django’s auth subsystem, but provides a session middleware. I guess now I can rewrite the commenting app again, this time to support OpenID and remove the captcha for those people, who are logged in.


O MVC, o MTV e o Django

Apr 17 2007 [Archived Version] □ Published at PyMan under tags  django mvc web


Como muitos sabem, MVC ( Model – View – Controller ) é um padrão de desenvolvimento, que é um padrão que separa o desenvolvimento nessas 3 camadas.

Model – nessa camada é implementada o banco de dados ou o modelo objeto-relacional.

Controller – nessa camada é implementado as regras de negocio, onde são processados os dados vindo camada Model e passados para a camada View.

View – nessa camada é onde fica a interface do sistema.

O MVC é muito utilizado nos dias de hoje e tem agradado a muitos desenvolvedores para web por separar a parte de programação de dados da parte da programação visual de um sistema feito para web, onde geralmente essas partes de um sistema são feitos por pessoas diferentes.

Em conseqüência ao aceitamento desse padrão pela comunidade, surgiram muitos frameworks que implementam esse padrão como o Ruby on Rails, Struts, Mentawai, TurboGears, Django entre muitos outros.

Como citado acima o desenvolvimento usando o django é feito de acordo com o MVC separado nessas 3 camadas. Até ai tudo perfeito, mas há um problema.

Qual problema?

O django usa as nomenclaturas para as camadas,diferente do modelo MVC. Para modelo o django usa model, para view ele usa template, até ai tudo bem. Mas ele define o controller como view. Isso mesmo, o django define o controller como view. E tem também as generic ‘views’ que são controllers genéricos para situações comuns como master/detail, delete, update.

O problema é maior ainda porque muitos desenvolvedores acham que essa nomenclatura errada chique porque as iniciais delas são igual aquele canal de TV a MTV ( Model – Template – View ).

Eu mesmo não gostei nada disso, porque isso pode confundir muitos que estão iniciando nesse framework.

Eu só não entendo porque eles resolveram chamar o controller de view.

Pensei, pensei e ainda não descobri.

Bom, eu prefiro o MVC e você?


Simple Random Character Function

Apr 16 2007 [Archived Version] □ Published at Eric Florenzano's Blog

Simple Random Character Function

Apr 16, 2007

I use this function all the time, most recently for some anti-spam techniques, and it's worth posting somewhere. It's modified from an entry on the activestate cookbook.

def random_chars(length):
    import random
    allowed_chars = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789"
    word = ""
    for i in xrange(0, length):
        word = word + allowed_chars[random.randint(0,0xffffff) % len(allowed_chars)]
    return word

Also, for anyone who knows me and is interested: my surgery went well and I'm recovering faster than I would have expected. Hopefully I'll be back to 100% speed in the next few days!

Anyways, hopefully this small code snippet is useful to someone else, as well!

Posted in:


Django Registration for Newbies

Apr 13 2007 [Archived Version] □ Published at stonemind consulting under tags  django talk nerdy to me

I recently turned my attention to user account management in Django and what follows are (cleaned-up) notes I made while exploring the django-registration contribution. As a result, this post is very introductory and task oriented, but hopefully, it will help orient newcomers like me to what's available and provide a foundation for exploring these topics in more depth.


Django serialization.

Apr 09 2007 [Archived Version] □ Published at Pythonidae under tags  django json serialization

Bastante usado em unittest e doctests.

[email protected]:~/dev/myapp$ python manage.py shell
>>> from
myapp.purchase.models import Country
>>> from django.core import serializers
>>> f = open('countries.json', 'w')
>>> data = serializers.serialize("json", Country.objects.all())
>>> f.write(data)
>>> f.close()

Você pode carregar manualmente usando python manage.py loaddata:

[email protected]:
~/dev/myapp$ python manage.py loaddata fixtures/countries.json
Loading 'fixtures/countries' fixtures...
Installing json fixture 'fixtures/countries' from absolute path.
Installed 242 object(s) from 1 fixture(s)


django queryset weirdness

Apr 09 2007 [Archived Version] □ Published at Amit Chakradeo Inc. under tags  django programming python

I needed to reset the django admin password and found this page which tells us how to do this. It did not work for me, however I tried to get the user object explicitly, reset the password and save it and it worked! Here is a session describing the behavior: > python manage.py shell In […]


django queryset weirdness

Apr 09 2007 [Archived Version] □ Published at Amit Chakradeo Inc. under tags  django programming python

I needed to reset the django admin password and found this page which tells us how to do this. It did not work for me, however I tried to get the user object explicitly, reset the password and save it and it worked! Here is a session describing the behavior: > python manage.py shell In […]


django-restful-model-views contribution update

Apr 06 2007 [Archived Version] □ Published at stonemind consulting under tags  django rest talk nerdy to me

I've updated the django-restful-model-views contribution, based on feedback I've received, primarily to make this a more generic REST API (not just model based). This update also begins implementing some ideas borrowed from Ruby on Rails.


django-planet aggregates posts from Django-related blogs. It is not affiliated with or endorsed by the Django Project.

Social Sharing

Feeds

Tag cloud

admin administration adsense advanced ajax amazon angular angularjs apache api app appengine app engine apple application security aprendiendo python architecture argentina articles asides audrey australia authentication automation backup bash basics best practices binary bitbucket blog blog action day blogging book books buildout business c++ cache capoeira celery celerycam celerycrawler challenges chat cheatsheet cherokee choices christianity class-based-views cliff clojure cloud cms code codeship codeship news coding command community computer computers computing configuration consumernotebook consumer-notebook continuous deployment continuous integration cookiecutter couchdb coverage css custom d data database databases db debian debugging deploy deployment deployment academy design developers development devops digitalocean django django1.7 django admin django cms djangocon django framework django-nose django-readonly-site django-rest-framework django-tagging django templates django-twisted-chat django web framework tutorials documentation dojango dojo dotcloud dreamhost dughh easy_install eclipse education elasticsearch email encoding english error europe eventbrite events expressjs extensions fabric facebook family fashiolista fedora field file filter fix flash flask foreman form forms frameworks friends fun functional reactive programming gae gallery games geek general gentoo gis git github gmail gnome google google app engine guides gunicorn hack hackathon hacking hamburg haskell heroku holidays hosting howto how-to howtos how-tos html http i18n image imaging indifex install installation intermediate internet ios iphone java javascript jinja2 jobs journalism jquery json justmigrated kde la latex linear regression linkedin linode linux login mac machine learning mac os x markdown math memcached meme mercurial meta meteor migration mirror misc model models mod_wsgi mongodb months mozilla multi-language mvc mysql nasa nelenschuurmans newforms news nginx nodejs nosql oauth ogólne openshift opensource open source open-source openstack operations orm osx os x ottawa paas packages packaging patterns pedantics pelican penetration test performance personal personal and misc philippines philosophy php pi pil pinax pip piston planet plone plugin pony postgis postgres postgresql ppoftw presentation private programmieren programming programming &amp; internet project projects pycharm pycon pycon-2013-guide pydiversity pygrunn pyladies pypi pypy pyramid python python3 queryset quick tips quora rabbitmq rails rant ratnadeep debnath reactjs recipe redis refactor release request resolutions rest reusable app review rhel rtnpro ruby ruby on rails scala scaling science screencast script scripting security server setup shell simple smiley snaking software software collections software development south sphinx sprint sql ssh ssl static storage supervisor support svn sysadmin tag tag cloud talk nerdy to me tastypie tdd techblog technical technology template templates template tags test testing tests tip tips tools tornado training transifex travel travel tips for geeks tumbles tutorial tutorials twisted twitter twoscoops typo3 ubuntu uncategorized unicode unittest unix use user authentication usergroup uwsgi uxebu validation virtualenv virtualenvwrapper web web 2.0 web application web applications web design &amp; development webdev web development webfaction web framework websockets whoosh windows wordpress work workshop wsgi yada znc zope