Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
How to add a preview page
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: a boolean field that determines whether the post is public or not 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+)/$', … -
Going international, pt. 1
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: Make the content available in both languages. 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 … -
Django Quick Tips #2: Image Thumbnails
One of the most common tasks in web development is resizing uploaded images into thumbnails of the original. Today I’ll ... -
Building My Django Weblog: Part 6
Very early on, when I was still playing with the look and layout of the website, I asked my friend Lisa. At the time, I was still just running the django development server. Anyway, Lisa has a great mind for web standards and the evolution of web markup. So she immediately picked up on the fact that my pages had a doctype of Transitional HTML 4.01 and gave me quite a bit of a lecture on things I should do instead. She recommended going with at least strict HTML 4.01, but preferably with XHTML. At the time, I wasn't sure what any of that meant (and I'm even still learning my way through it). So, anyway, I launched the website a few weeks later, with a few things not quite working the way they should have been. Content types were one of those things. One of the first bugs that got reported was by James Rowe: he saw, in my atom feed, that lists and block quotes and other things had embedded paragraph tags (<p>...</p>). And so in some cases, I had nested paragraph tags. Here's what happened. In Django's admin, when you have a text field, you just type … -
Django Internships at the Journal-World
I’m extremely excited to announce our new internship program here in Lawrence. Starting this summer we’re going to be hiring interns to join our kick-ass team and learn the ropes. If you’re a student, or if you’re trying to break into the world of next-generation web development, I can’t think of a better place to get started. You’ll get to spend up to six months developing cool toys (in Django, of course), live in one of the coolest towns in the country, and learn web development from the best. -
Upgrading Ubuntu for Django Users
I just updated my Slice from Ubuntu Dapper (6.06.1), the currently available version from Slicehost, to Ubuntu Feisty (7.04). I ... -
Amazon S3 Updates Pricing
Amazon just sent out an email to AWS developers. S3 has a new pricing model, which actually reduces cost: Current ... -
Another django-restful-model-views Update
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. -
[EN] Django model managers, Do Not Repeat Yourself !
I've recently come up with a great django feature "model Managers".Each django model has it's own manager class, which can be overriden by your custom class.Let's say there's a model containing fields:class Person(models.Model): name = models.CharField(maxlength="100", blank=False, verbose_name="Your name") age = models.IntegerField(verbose_name="Your age") def __str__(self): -
[EN] Django extending User, custom User methods
Django doesn't allow to subclass the User model yet.Each Django model lets you easily create model methods.Behind the scene, each django model has its own methods, f.e. save()which saves the model data into the database.Django provides the lightweight User framework in "django/contrib/auth/",where "User" model is defined with fields:username, password, is_staff, first_name, last_name, email, -
URL Pet Peeves
One of the best features of Django is the clean URL structure. The following is an example of what could ... -
Building My Django Weblog: Part 5
The time came for me to start thinking about where to host my site. And although I have some experience with using dreamhost to host sites, I wasn't particularly thrilled with that idea. Instead, I started thinking about using a VPS. That would allow me to use gentoo linux as my hosting environment, and it meant that I wouldn't have to hack around and do clever things just to run django behind apache and mod_python. Added to that, regular hosting is about 10 US dollars a month, while a VPS is about 20 a month. I decided to go with VPS Land because they offered the best price point for the feature list. And they've proved to be an excellent provider in all the time I'd been with them. (I switched out to linode simply because a friend of mine is there, and I have to represent and keep it real). Anyway, after upgrading gentoo and installing django on my VPS it was time to start opening up the testing to other people to get their feedback on various features. One of those features was the look of the site. Since I'd already decided on a layout, it was time … -
Building My Django Weblog: Part 4
In one of my earliest blog posts, I wished my sister a happy birthday. Today is exactly two years since, so Happy Birthday to Sindhu :) Edit: My sincerest apologies to all your feed readers -- my blog programming skills are not good enough, apparently, to keep drafts from getting published. I thought I'd fixed the problem this morning, before getting on the plane in San Jose to return Boston, but apparently not. I don't think I even fixed the feed, so I'm not entirely sure what it was I fixed. In any case, my humblest apologies to everyone for the inconvenience caused. I hope it doesn't put you off my blog. It definitely shows how much I have yet to learn. I like to get my news from reddit usually. The nice thing about reddit is that there tends to be a variety of stories, and every so often you get a gem of an article about CSS. So, for example, you get a menu of css techniques, or you find out about Yahoo's javascript and CSS library--yui, and reading these open up possibilities. So, I've never delved into web-two-point-oh stuff yet. The last line of Javascript I ever … -
O MVC, o MTV e o Django
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 … -
Building my Django Weblog: Part 3
One day, while searching for something Django related, I ran into a really nicely done Django weblog. What caught my attention here, is that he came up with a way to spiffy up his comments display by showing a country flag for each commenter. It looks really spiffy. So I decided to play copycat. Well, it only took a few minutes to implement it in the testing version of my own blog, and I showed it off to a couple of my friends in IRC. One of them, tjfontaine, said something along the lines of "oh neat, libgeoip." Obviously, I hadn't seen or heard of this libgeoip thing so I asked him about it and he linked me to it. Now this was interesting, because it comes with python bindings. And the best part, of course, is that it is in portage. So I installed it, and had a look at their usage sample. Essentially, you just download their ip to country map, which they update once a month, and so you don't have to hit their servers everytime you do a lookup. Next up, I wrote the templatetag to use GeoIP. In its entirety, it looks like this: from … -
Building my Django Weblog: Part 2
Up until a few days ago, my Django blog application was violating DRY. Well, let's be honest, it probably still is, but this one was a blatant violation. What happened was that I wanted to be able to add users to my system without necessarily having them listed as bloggers, since I'm hoping to provide, in the future, gallery, mail and other miscellaneous services to the extended Kulleen clan. To solve that I created a Person class which had a foreign key into Django's own user class, plus some extra fields. Two of those fields were first_name and last_name, so that meant that for each blogger, I had to enter their names twice. Silliness, I tell you! Now, I'd read James' article about extending the User model late last year, during the early stages of my django learnings. And to be honest, I didn't really understand the implications. All of a sudden, two days ago, it hit me! So, I made a few changes to my blog to make use of that technique. My code went from this: class Person( models.Model ): first_name = models.CharField (maxlength = 100) last_name = models.CharField (maxlength = 100) user = models.ForeignKey ( User, verbose_name="Associated … -
Django Registration for Newbies
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. -
A Quick Note About my Feeds and Blogs
Hi Everyone, I've just finished rebuilding the feeds on this site, and I thought I'd let you all know of some changes. The feeds I put in place when the website launched are still active and will continue to be for a while (for your convenience). However, the links to those feeds are no longer being advertised. I have switched the url layouts now to be hopefully a little more consistent and a little more intuitive. The story is is basically this: any link under the "Weblogs" link will have an associated feed, accessible by appending "/rss/" or "/atom/" to the end of the URL. The feeds page explains this with examples. The available types of feeds are: the entire blog the entire per-person blog the entire tagged blog per-person tagged blog comments for a specific blog I've added feed icons on all the relevant pages so as to make it more accessible. Additionally, you'll notice the introduction of a new blogger: my sister. She'll start blogging some time soon, hopefully. So, now, while the tag cloud situation still remains, the tags will at least link to the specific blogger (and give you a 404 if that blogger hasn't made … -
Building My Django Weblog
For quite a few months, I'd been wanting to build my own weblog. You might recall that I had started using Django to code up my ex-employer's websites. Well, that was a fantastic experience, educationally, because I got exposed to a really great framework. As part of that effort, I rebuilt their rather simple blog (which was -- and probably still is -- hosted at Typepad, leaving the website interface a little klunkily inconsistent) Anyway, Aimee and I started talking about having our own web space. Otherwise, her blog and my blog would be hosted in separate neighborhoods on the web, which does nobody any good, really. So, I decided to take the code I'd written up for StreamBase and use it for my own site. Along the way, I kept reading James' blog especially the bits about generic views and application/project layout and, of course, hacking the FreeComment model. In the #django channel, bitprophet would teach me how to wrap generic views and do other tricky (for me!) things. Meanwhile Colin (Magus-) would help me with basic Django things that everyone should know, but I didn't. So, I started hacking away at it. Every day, I would upload a … -
Django serialization.
Bastante usado em unittest e doctests.wiliam@wiliam:~/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:wiliam@wiliam:~/dev/myapp$ python manage.py loaddata fixtures/countries.jsonLoading 'fixtures/countries' fixtures...Installing json fixture 'fixtures/countries' from absolute path.Installed 242 object(s) from 1 fixture(s) -
django queryset weirdness
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 [1]: from django.contrib.auth.models import User In [2]: u=User.objects.all() In [3]: u[0].password Out[3]: 'sha1$0913d$6c5cfefb89b3c77dc8573e466a943c7acd177f6b' In [9]: u[0].set_password('testme') In [10]: u[0].save() In [11]: u[0].password Out[11]: 'sha1$0913d$6c5cfefb89b3c77dc8573e466a943c7acd177f6b' In [12]: q=User.objects.get(id=1) In [13]: q Out[13]: <user : root> In [14]: q.set_password('testme') In [15]: q.save() In [16]: q.password Out[16]: 'sha1$24e9c$868ff39f08c3bde96397e33ea6a8847a658a16bc' Maybe this is related to queryset caching, which would print the same password even after calling set_password. But it looks like in the first method, the password does not even get written to the database. This might be a bug. I will need to run more tests and report (or possibly patch) it... Update: Perhaps I am not clear in the above post. The weirdness is that in the above two scenarios u[0] and q should essentially reference the same user object, but calling set_password (and later save) method on the u[0] reference does not seem to work (i.e. the … -
First Post at the New Website
Welcome, everyone, to my new home on the web. I've built this site using django, with tonnes of help from all sorts of people. I've listed them on the about page for now. As this website gets fleshed out, I'll add more details. So, I'll be blogging here from now on, and not on planet gentoo any longer. I think the planet will be syndicating this feed for a while, though. Please do have a look around, and find me all the bugs you can find. Since this website is very much a work in progress, there will be several improvements over the next few weeks and months. So, I'll talk quickly about some of the design aspects of this site. Wherever possible, I've tried to output valid XHTML 1.0 code. If you find something invalid, please leave me a comment below. I've input all the posts and comments from Planet Gentoo here, so everyone who's ever chatted with me on that blog has their conversation carried over to here. In the next few posts, I'll go into more detail about this site, including the django backend code, the colours, the stylesheets, and artwork (yes, that includes the logo, which … -
django-restful-model-views contribution update
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. -
Ticket #3882 (closed: fixed)
Já está disponível na versão de desenvolvimento do Django o localflavor BR.Ticket: #3882Changeset 4874 e 4908 -
django.contrib.localflavor.br
Primeira versão implementada, agora vem os teste."""BR-specific Form helpers"""from django.newforms import ValidationErrorfrom django.newforms.fields import Field, RegexField, Select, EMPTY_VALUESfrom django.newforms.util import smart_unicodefrom django.utils.translation import gettextimport rephone_digits_re = re.compile(r'^(\d{2})[-\.]?(\d{4})[-\.]?(\d{4})$')class BRZipCodeField(RegexField):..def __init__(self, *args, **kwargs): ....super(BRZipCodeField, self).__init__(r'^\d{5}-\d{3}$',....max_length=None, min_length=None,....error_message=gettext(u'Enter a zip code in the format XXXXX-XXX.'),....*args, **kwargs)class BRPhoneNumberField(Field):..def clean(self, value): ....super(BRPhoneNumberField, self).clean(value)....if value in EMPTY_VALUES:......return u''....value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))....m = phone_digits_re.search(value)....if m:......return u'%s-%s-%s' % (m.group(1), m.group(2), m.group(3))....raise ValidationError(u'Phone numbers must be in XX-XXXX-XXXX format.')class BRStateSelect(Select):.."""..A Select widget that uses a list of brazilian states/territories..as its choices..."""..def __init__(self, attrs=None):....from br_states import STATE_CHOICES # relative import....super(BRStateSelect, self).__init__(attrs, choices=STATE_CHOICES)Coisas pra resolver:>>> from django.contrib.localflavor.br.forms import BRZipCodeField, BRPhoneNumberField, BRStateField, BRStateSelect>>> from django import newforms as forms>>> class BRForms(forms.Form):... zipcode = BRZipCodeField()... phone = BRPhoneNumberField()... statef = BRStateField()... statec = forms.ChoiceField(widget=BRStateSelect)...>>> brf = BRForms()>>> print brf.as_table()...>>>>O widget BRStateSelect ainda não é renderizado corretamente, isso acontece com os fields que tem Select como classe base. A solução que vem sendo adotada usa o método __init__, que nesse caso não fica elegante pois teríamos que importa STATE_CHOICES de br_states.py. Bom o tempo está apertado, tenho que ir, aqui tem um exemplo de como usar o __init__, a única diferença e que os dados vem da banco de dados.