Wednesday, May 2, 2012

Re: Modify __unicode__

On 2012-05-02, at 12:46 , Nikhil Verma wrote:

> Hi All
>
> In models.py my table structure is :-
>
> class ABC(models.Model):
> name = models.CharField(max_length=80,blank=True,null=True)
> date_created = models.DateTimeField(blank=True,null=True)
>
> def __unicode__(self):
> return "%s %s" % (self.name, self.date_created)
>
>
> Let say my first entry is :-
> name = django
> date_created = 2012-05-02 # it will look like this datetime.datetime(2012,
> 5, 2, 15, 42, 24)
>
> I want to modify this ABC(__unicode__ method) object in such a way that
> whenever i call this object from forms
> like this :-
>
> forms.py
>
> efg = forms.ModelChoiceField(queryset= ABC.objects.all())
>
> The dropdown created above should have values like this:-
>
> 1) django Wednesday PM 2 May # Modify dateTimeField which retuen day of
> week AM or PM and then day and name of month
> 2) django1 Wednesday PM 2 May
> .
> .
> .
> .
> and so on ..
>
> How can i modify the __unicode__ method to achieve this ?

A DateTimeField maps to a Python datetime object[0], so… just call strftime[1]
with whatever format parameters you need on "self.date_created" before
interpolating it into the result string?

Also `__unicode__` should return a unicode object[2], with your current
implementation Python will call `str.decode('ascii')`, which will blow up
if your name or your formatted date string contain any non-ascii character
(because it's August in French — août — or March in German — März — or
October in Thai — ตุลาคม, for instance).

[0] http://docs.python.org/library/datetime.html#datetime-objects
[1] http://docs.python.org/library/datetime.html#datetime.datetime.strftime
[2] http://docs.python.org/reference/datamodel.html#object.__unicode__
[3] http://docs.python.org/library/stdtypes.html?highlight=decode#str.decode
technically it calls something similar to `str.decode(sys.getdefaultencoding())`,
but in Python 2 the default encoding is ascii

PS: I'd suggest learning about Python a bit, Django stands on the shoulders of
a giant, not alone.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment