Django: How to get string from CharField object? -


I have a dynamic model, which is essentially a list of words. It is very simple and it is defined as follows:

  class word (models.model): word = models.charphield (max_length = 100)  

I need a special word in the form of string object (I am changing all the characters in the word with the stars for a simple executioner game). However, I can not find the word as a string object.

I tried to add this method to the word class, but it did not seem to work.

  def __str __ (self): return str (self.word)  

I get an empty string object instead of the word

< P> What should I do to get the value of CharField as a string object? Thanks for your help.

Edit: The strange thing for me is that there is no problem in returning an integer. For example, if I do something like this:

  word = Word (pk = 2821) print word.id  

... it will print 2821, ID of that particular record

Are you sure that you word objects correctly? In your example, creates words = word (pk = 2821) a new word with a pk 2821 and a blank The word field if you have received the actual Word object from the database containing the value in your word field, then word.word is a The string should be returned. E.g.

  & gt; & Gt; & Gt; W1 = word (pk = 5, word = 'eggs')> gt; & Gt; & Gt; & Gt; W1.word 'Egg' & gt; & Gt; & Gt; & Gt; W1.save ()> gt; & Gt; & Gt; & Gt; W2 = Word.objects.get (pk = 5)> gt; & Gt; & Gt; & Gt; W2.word u'eggs'  

Can you also verify that the words are properly stored by connecting with a DB client in your database and viewing its output Being:

  yourappname_word LIMIT Choose from 20 words; As I said,  word.word  should work, so the problem can be that how are you avoiding or bringing objects to your  Word? 


Comments