How to properly use MySQL Generated Fields in Django

2019-04-15 Thread rmschne
I have a generated field in a MySQL table "alpha 
= upper(substr(`lname`,1,1))" where the field lname is a last name of a 
person. Idea is that I get a field of the first letter of the last name.  

In Django, I have in the table 'attendees' a field alpha = 
models.CharField("alpha", max_length=1, db_column='alpha', 
help_text='leading alphabetic letter of lastname.')

This works ok when I a new record into the database and the field "alpha" 
is computed correctly.  It works where I can query out the data using 
Django.  

Now I have discovered that if in Django I adjust one of the the other 
fields (not lname), when I do a "save() on the record", Django throws an 
error:
"The value specified for generated column 'alpha' in table 'attendees' is 
not allowed.")

The one field i am changing in the "attendee" table is a foreign key field; 
and I'm giving Django the foreign key object.  So I think I'm doing that 
correctly; but the new attendee object is not being saved.  

I've searched Google for "Django Mysql generated field" and come up with 
nothing relevant on anything special needed; but I suspect I'm missing 
something hence this query. Looking for something special about generated 
fields in MySQL and Django, if anything special?

Some code extracts:

class Guest(models.Model):
lname = models.CharField(max_length=150, db_column='Lname', 
blank=True,help_text="Last name")
alpha = models.CharField("alpha", max_length=1, db_column='alpha', 
help_text='leading alphabetic letter of lastname.')
contact = models.ForeignKey(Contact, related_name='adcontact', 
db_column='ContactID',blank=True, null=True, help_text="Name of linked 
contact for this guest")
timestamp = 
models.DateTimeField(db_column='timestamp',auto_now=True,blank=False)

cad=Guest.objects.filter(contact__id=idfrom)
print "Guest: ",len(cad)
if cad:
for i in cad:
print "i.contact:",i.id,i.contact
print "contactto:",contactto.id,contactto
i.contact=contactto
try:
i.save(["contact"])
except Exception as e:
print "Exception. cad contact save failed.",e


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/45a3e32d-29d7-4129-896b-01698beec3e1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to get Foreign Key Objects programmatically?

2017-10-29 Thread rmschne
I'm using Django as front end to a MySQL database. User interface is a 
terminal program, not a web site.

I've written a very simple generic function to edit the fields of one 
record of a Django "object".  It works fine for editing editable fields. 
User specifies which field, then is shown the current value, raw_input() 
for the new value, then save() the record.

For fields that connect to Foreign Keys, what I want to do is present to 
user a simple list of Foreign Key records, from which the user will pick 
the relevant ID.  I know, given a list and the ID, how to then edit the 
record by doing a Django get(id=ID) on the Foreign Key table.  What I'm 
having trouble doing is figuring how

1. Identify into a variable the name of the Foreign Key table/object
2. Then with that variable do a call to the relevant Foreign Key table, 
e.g. ForeignKeyTable.objects.all()

See code below for <===WHAT I DO NOT KNOW HOW TO DO IN CODE Below.  I think 
I need some Django function that gives me the foreign key table in some 
useable generic form.

Hope all this makes sense. 

--rms

def EditDjangoObjectData(djangoobject,show=False,editonerecord=False):
"""
EditDjangoObjectData()
djangoojbect=a django object, e.g. a record in a table
"""
print "\nToDo Note: This routine not yet working on fields with 
foreign keys!"
changelist=[]
ok=True
while ok:
change=None
fields = [(f.name, f.editable) for f in 
djangoobject._meta.get_fields()]
if show:
print "\nfields:\n",fields
print "django object:\n",djangoobject
s="\nEditable Fields ('enter' to return): \n"
fieldlist=[]
for i in fields:
if i[1]:   # only for 'editable' fields
if i[0].lower() <> "id":
s=s+i[0]+", "
fieldlist.append(i[0])
s=s+"DELETE or '?'"
fieldok=False
while not fieldok:
fieldtochange=raw_input("Enter field name to change:\n"+s+": ")
if not fieldtochange:
return None
elif fieldtochange.upper()=="DELETE":
ans=raw_input("...Confirm DELETE by typing 'DELETE': ")
try:
if ans=="DELETE":
rtn=djangoobject.delete()
print "Deleted. ",rtn
return rtn
except:
print "***DELETE Failed.",sys.exc_info()[0]
ans=raw_input("Press 'Enter' to continue ... ")
elif fieldtochange=="?":
PrintObjectDetails(djangoobject)
elif fieldtochange in fieldlist:
fieldok=True
else:
print "\nError. ",fieldtochange,"is not in list. Try 
again."
print "Current Value of Field to 
Change:",fieldtochange,"is:",getattr(djangoobject, fieldtochange)
**
** In here add some code to show a list of the foreign key records for user 
to select, e.g. ID, Description, 
**for r in ForeignKey.objects.all():   <== WHAT I DO NOT KNOW HOW TO DO IN 
CODE.
**print i.id, i.description
**ID=raw_input("Enter ID:)
**foreignkeyobject=ForeignKey.objects.get(id=ID)<== WHAT I DO NOT KNOW 
HOW TO DO IN CODE.
** ... then put that object into the relevant field 
newvalue=raw_input("Enter New Value: ")
change="changed ["+fieldtochange+"]"
print "\nTo Save   :",djangoobject
print "The Change:",change,"to",newvalue
if not newvalue:
return None
elif newvalue.lower()=="none":
newvalue=None
elif newvalue.lower()=="true":
newvalue==True
elif newvalue.lower()=="false":
newvalue=False
setattr(djangoobject, fieldtochange, newvalue)
try:
djangoobject.save()
print ": Success. Saved:",change,"to",newvalue
print ": New Object:",djangoobject
changelist.append(change)
print "ChangeList:",changelist
except:
print "***Save Failed.",sys.exc_info()[0]
ans=raw_input("Press 'Enter' to continue ... ")
if editonerecord:
ok=False
return changelist

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4028d8fa-88b8-4940-ba41-a1b47a0913ba%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unicode error in __unicode__(self) function

2017-05-09 Thread rmschne
 

> I'm sorry - but this isn't your real error.
>
> You will see it in your WSGI daemon logs once you set DEBUG to false. 
>
>  
>
> This error is caused by Django trying to print the error using ascii codec 
> for the debug output (I haven't chased it down any further and I should 
> really report it).
>
>  
>
> As said, your real error is somewhere else and that will probably make 
> more sense.
>
>  
>
> -- 
>
> Melvyn Sopacua
>

Melvyn,

Thanks. I understand what you are saying. Obvious, but I didn't notice 
that. However, I do think it's a Django bug. This app is not running on a 
web server so there is no WSGI daemon.  Do you have a suggestion on what I 
can do to get a better detection of the error to enable reporting it? 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b3ed676d-811a-4c53-b176-bd460f5dd54a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unicode error in __unicode__(self) function

2017-05-08 Thread rmschne
Yes, it is the first name of a person with a European name, who it's got 
that "ó" character. My understanding that it is Unicode. The variable 
prints ok in the rest of the code to the screen and in Django templates, 
but this __unicode_(self) method fails. 


On Monday, 8 May 2017 17:22:42 UTC+1, Tom Evans wrote:
>
> What data is "Jón"? 
>
> Is it u'J\xf3n' or something else? (print repr(self.fname)) 
>
> Cheers 
>
> Tom 
>
> On Mon, May 8, 2017 at 5:10 PM, rmschne <rms...@gmail.com > 
> wrote: 
> > I have a Django setup that has worked for a very long time. Yesterday I 
> > upgraded from Django 1.10 to 1.11.1 and am getting the error: 
> > 
> > raise DjangoUnicodeDecodeError(s, *e.args) 
> > django.utils.encoding.DjangoUnicodeDecodeErrorJón 
> > : 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in 
> > range(128). You passed in  ( > 'soc_util.models.Meetingattendee'>) 
> > 
> > when in the code simply printing the "Meetingattendee" object with 
> > 
> > def __unicode__(self): 
> > print self.fname 
> > return self.fname 
> > 
> > The above is a simplified version. The error first cropped up on the 
> more 
> > complex version 
> > 
> > def __unicode__(self): 
> > s=u'%s: %s, %s %s, %-12s, %s %s, %s, INV:%s, PO:%s, ItemCode:%s' 
> % 
> > (self.id,self.meeting.date.strftime("%d-%b-%Y"),self.table,self.seat,\ 
> > self.attendeestatus.status,self.fname, self.lname, 
> > self.affiliation, \ 
> > self.invoiceno,self.ponumber,self.itemcode) 
> > return s 
> > 
> > where I eventually determined that the code was not working when working 
> the 
> > field self.fname. 
> > 
> > self.fname fails when it is "Jón".  Works fin with "Jon", of course. 
> > 
> > I have not tried to revert back to Django 1.10, but i guess that's the 
> next 
> > step unless there is something in Django 1.11.1 that was changed that 
> > affects this. I can't find anything mentioned in the release notes. 
> > 
> > -- 
> > You received this message because you are subscribed to the Google 
> Groups 
> > "Django users" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> an 
> > email to django-users...@googlegroups.com . 
> > To post to this group, send email to django...@googlegroups.com 
> . 
> > Visit this group at https://groups.google.com/group/django-users. 
> > To view this discussion on the web visit 
> > 
> https://groups.google.com/d/msgid/django-users/4d37cc78-7fe9-41b6-bcba-eb788465e54f%40googlegroups.com.
>  
>
> > For more options, visit https://groups.google.com/d/optout. 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e450ce55-cafa-4cb3-adda-6decea1c87cf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Unicode error in __unicode__(self) function

2017-05-08 Thread rmschne
I have a Django setup that has worked for a very long time. Yesterday I 
upgraded from Django 1.10 to 1.11.1 and am getting the error:

raise DjangoUnicodeDecodeError(s, *e.args)
django.utils.encoding.DjangoUnicodeDecodeErrorJón
: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in 
range(128). You passed in  ()

when in the code simply printing the "Meetingattendee" object with

def __unicode__(self):
print self.fname
return self.fname

The above is a simplified version. The error first cropped up on the more 
complex version

def __unicode__(self):
s=u'%s: %s, %s %s, %-12s, %s %s, %s, INV:%s, PO:%s, ItemCode:%s' % 
(self.id,self.meeting.date.strftime("%d-%b-%Y"),self.table,self.seat,\
self.attendeestatus.status,self.fname, self.lname, 
self.affiliation, \
self.invoiceno,self.ponumber,self.itemcode)
return s
 
where I eventually determined that the code was not working when working 
the field self.fname.

self.fname fails when it is "Jón".  Works fin with "Jon", of course.  

I have not tried to revert back to Django 1.10, but i guess that's the next 
step unless there is something in Django 1.11.1 that was changed that 
affects this. I can't find anything mentioned in the release notes.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4d37cc78-7fe9-41b6-bcba-eb788465e54f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to access Django data with the field name in text?

2016-11-14 Thread rmschne
yep, that did it. It was getattr() and setattr() I was unaware of (or 
forgot!).  

I made my code a bit more generic (and I know I have not put in much error 
correction or exception detection, but will do so).  Thank you.  See code 
here:

fields = [(f.name, f.verbose_name) for f in 
Meetingattendee._meta.get_fields()]
s=''
for i in fields:
s=s+i[0]+", "
fieldtochange=raw_input("Enter field to change:\n"+s+": ")
print "Current Value of Field to 
Change:",fieldtochange,"is:",getattr(att, fieldtochange)
newvalue=raw_input("Enter New Value: ")
if not newvalue:
return None
setattr(att, fieldtochange, newvalue)
att.save()
print "Saved:",att


On Monday, 14 November 2016 11:58:06 UTC, Vijay Khemlani wrote:
>
> If I understood it correctly, you might want to do it like this
>
> setattr(att, "fname", "value_to_be_set")
>
> and to get the value
>
> first_name = getattr(att, "fname")
>
> On Mon, Nov 14, 2016 at 8:38 AM, rmschne <rms...@gmail.com > 
> wrote:
>
>> I have a extracted all the field names from a Django model into a list 
>> called "fields", e.g.
>>
>> fields = [(f.name, f.verbose_name) for f in 
>> Meetingattendee._meta.get_fields()]
>>
>> I ask the user to select a record, e.g.
>>
>> att=Meetingattendee.objects.get(id=attid) 
>>
>> where "attid" is the ID of the record (input by the user)
>>
>> I now will ask user to input the name of the field of interest, e.g. 
>> "fname" which is one of the fields and holds "first name",  I then want to 
>> enable viewing/changing the selected field, e.g. in code to work with the 
>> first name field, it would be simply att.fname, but in this case the name 
>> of the field a string (input from user).  How to convert the input string 
>> name "fname" into something that in code would recognise that the user 
>> wants to work with att.fname?
>>
>> (hoping this question is clear!)
>>
>> --rms
>>
>>
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/df713caf-24f3-4309-b270-0b58e12c75cc%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/df713caf-24f3-4309-b270-0b58e12c75cc%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d8a0431b-cc03-44c4-adc9-e3f35063d7e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to access Django data with the field name in text?

2016-11-14 Thread rmschne
I have a extracted all the field names from a Django model into a list 
called "fields", e.g.

fields = [(f.name, f.verbose_name) for f in 
Meetingattendee._meta.get_fields()]

I ask the user to select a record, e.g.

att=Meetingattendee.objects.get(id=attid) 

where "attid" is the ID of the record (input by the user)

I now will ask user to input the name of the field of interest, e.g. 
"fname" which is one of the fields and holds "first name",  I then want to 
enable viewing/changing the selected field, e.g. in code to work with the 
first name field, it would be simply att.fname, but in this case the name 
of the field a string (input from user).  How to convert the input string 
name "fname" into something that in code would recognise that the user 
wants to work with att.fname?

(hoping this question is clear!)

--rms



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/df713caf-24f3-4309-b270-0b58e12c75cc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Re. My Django Book.

2015-07-31 Thread rmschne
I'm no way an advanced user, but I found the book simplistic and not worth 
it.  Django's own documentation is much 
better https://docs.djangoproject.com

On Thursday, 30 July 2015 21:35:16 UTC+1, Steve Burrus wrote:
>
> * Say I was wondering if anyone else has ever read this particulkar Django 
> book called "Sams Teach Yourself Django in 24 Hours" I checked out of the 
> library yesterday? [yeah I know it's one of the "24 hours" series] Does it 
> really teach the beginner a lot of things concerning Django?*
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/272afb4b-6e50-45be-92a8-4580049c3a3f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model Manager QuerySet over-ride class not working as expected

2014-11-03 Thread rmschne
Collin,

Thanks ... no I'm not saying that as I did do any assert statements.  When 
I add that to the main calling programme, it fails with an "Assertion 
Error".  Having not used assert statements before, I'm not sure what that 
means.  Can you help?

What I am saying is that when from the calling programme, I call the main 
object with a filter, it works as expected--only members with 'Active' 
status.  When I call the custom class (Class MemberActive) with no filter 
(as the filter is in the custom class), I get all records regardless of 
status, e.g. the custom class is running without regard to the def 
statement.

On Monday, 3 November 2014 01:51:59 UTC, Collin Anderson wrote:
>
> Hello
>
> You are saying this doesn't work as expected?
>
> class MemberActive(models.Manager):
> def get_queryset(self):
> qs = super(MemberActive, self).get_queryset().filter(status=
> 'Active')
> return qs
>
> class Member(models.Model):
> # etc
> Active_objects = MemberActive()
>
> assert all(m.status == 'Active' for m in Member.Active_objects.all())
>
> Collin
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/683fd596-567a-49ac-89b9-50e6f9231a9e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model Manager QuerySet over-ride class not working as expected

2014-11-03 Thread rmschne
Daniel,

Gosh. Tail between legs. Clearly, my eyes aren't what they used to be. Not, 
and should have been, using my Retina screen for this work! Well spotted. 
Yes this is real code (edited down). Yes, I have "g" in the real code 
rather than a "q". When I fixed that (global fixing 62 errors), all is well.

What I did (not excuses...just what happened which in engineering is 
important to understand!): In reading the documentation for the upgrade I 
saw that get_query_set() was changed to get_queryset(), i.e. the "_" 
removed. I did a global search and replace in the model.py file, but 
mistakenly put in "get_gueryset()" as new code.  I didn't then and 
continued till now not notice.  Interestingly, neither did Django or Python 
complain (far as I can tell). Replacing the "g" for a "q" it now works as 
expected.

Thanks!

--rms


On Monday, 3 November 2014 10:12:10 UTC, Daniel Roseman wrote:
>
> On Sunday, 2 November 2014 18:12:10 UTC, rmschne wrote:
>>
>> I've upgraded to Django 1.7.1  
>>
>> Following the upgrade most (haven't tested all, but for all tested this 
>> true) the over-rided queryset is not functioning.  
>>
>> when the code calls
>> qs=Member.Active_objects.all()
>>
>> then all members are returned, not just those which confrom to the filter 
>> specified in the Class MemberActive(models.Manager)
>>
>> this all worked for many years and only now works following upgrade to 
>> 1.7.1.  I upgraded just to keep up.  Now regret that decision, but 
>> difficult to go back.
>>
>> I've tried both get_query_set() and get_queryset() ... I understand the 
>> latter is required in 1.7.
>>
>> Any suggestions?
>>
>>
>> ===the code snippets:
>>
>> class MemberActive(models.Manager):
>> def get_guery_set(self):
>> qs=super(MemberActive, 
>> self).get_query_set().filter(status='Active')
>> return qs
>>
>> class Member(models.Model):
>> 
>> membertype=models.ForeignKey(Membertype,related_name='members',db_column='mtypeid',
>>  
>> null=True, on_delete=models.SET_NULL,help_text='Type of 
>> member.',verbose_name='Member Type')
>> lname = models.CharField(max_length=150, db_column='lame', 
>> blank=True, help_text='Last name.',verbose_name='Last Name') 
>> fname = models.CharField(max_length=150, db_column='fame', 
>> blank=True, help_text='First name.',verbose_name='First Name') 
>> status = models.CharField(max_length=12,db_column="status", 
>> blank=True,help_text="Membership status)
>>
>> objects = models.Manager() # the default manager
>>
>> Active_objects = MemberActive()
>>
>  
>
> Is this your real code? You have two typos in the name of the overridden 
> method: it should be `get_queryset`, not `get_guery_set` (you have a g for 
> a q, and an extra underscore).
> --
> DR. 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f3f2bec0-8986-43f2-b64e-14ed53d71545%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model Manager QuerySet over-ride class not working as expected

2014-11-03 Thread rmschne
Colin,

Thanks... no, I'm saying anything about an "assert" statement as I did not 
use it.  I'm saying that
: when I call the main class object ("class Member"), the return is all 
records in the database (as expected). 
: when I call the custom subclass object (class MemberActive), I expect a 
filtered list, but it returns all records (not expected and "the bug")
: when I call the custom subclass object (class MemberActive), and filter 
it, the return is only active members (as expected)

I've never used asserts. I added your assert line into the code and Python 
fails. I know little about asserts and will have to research what that's 
all about.  Probably a clue.


On Monday, 3 November 2014 01:51:59 UTC, Collin Anderson wrote:
>
> Hello
>
> You are saying this doesn't work as expected?
>
> class MemberActive(models.Manager):
> def get_queryset(self):
> qs = super(MemberActive, self).get_queryset().filter(status=
> 'Active')
> return qs
>
> class Member(models.Model):
> # etc
> Active_objects = MemberActive()
>
> assert all(m.status == 'Active' for m in Member.Active_objects.all())
>
> Collin
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/dc828809-d0f9-4ad3-a510-a03006b67acd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Model Manager QuerySet over-ride class not working as expected

2014-11-02 Thread rmschne
Also, when I call from the calling programm:

qs=Member.all().filter(status='Active') ... then just those records where 
status=Active are returned
qs=Member.Active.all() ... all records from data base returned ... but 
expected only status=Active



On Sunday, 2 November 2014 18:12:10 UTC, rmschne wrote:
>
> I've upgraded to Django 1.7.1  
>
> Following the upgrade most (haven't tested all, but for all tested this 
> true) the over-rided queryset is not functioning.  
>
> when the code calls
> qs=Member.Active_objects.all()
>
> then all members are returned, not just those which confrom to the filter 
> specified in the Class MemberActive(models.Manager)
>
> this all worked for many years and only now works following upgrade to 
> 1.7.1.  I upgraded just to keep up.  Now regret that decision, but 
> difficult to go back.
>
> I've tried both get_query_set() and get_queryset() ... I understand the 
> latter is required in 1.7.
>
> Any suggestions?
>
>
> ===the code snippets:
>
> class MemberActive(models.Manager):
> def get_guery_set(self):
> qs=super(MemberActive, 
> self).get_query_set().filter(status='Active')
> return qs
>
> class Member(models.Model):
> 
> membertype=models.ForeignKey(Membertype,related_name='members',db_column='mtypeid',
>  
> null=True, on_delete=models.SET_NULL,help_text='Type of 
> member.',verbose_name='Member Type')
> lname = models.CharField(max_length=150, db_column='lame', blank=True, 
> help_text='Last name.',verbose_name='Last Name') 
> fname = models.CharField(max_length=150, db_column='fame', blank=True, 
> help_text='First name.',verbose_name='First Name') 
> status = models.CharField(max_length=12,db_column="status", 
> blank=True,help_text="Membership status)
>
> objects = models.Manager() # the default manager
>
> Active_objects = MemberActive()
>  
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ea64ef4c-4b9e-465e-8fad-0e3261ec20de%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Model Manager QuerySet over-ride class not working as expected

2014-11-02 Thread rmschne
I've upgraded to Django 1.7.1  

Following the upgrade most (haven't tested all, but for all tested this 
true) the over-rided queryset is not functioning.  

when the code calls
qs=Member.Active_objects.all()

then all members are returned, not just those which confrom to the filter 
specified in the Class MemberActive(models.Manager)

this all worked for many years and only now works following upgrade to 
1.7.1.  I upgraded just to keep up.  Now regret that decision, but 
difficult to go back.

I've tried both get_query_set() and get_queryset() ... I understand the 
latter is required in 1.7.

Any suggestions?


===the code snippets:

class MemberActive(models.Manager):
def get_guery_set(self):
qs=super(MemberActive, self).get_query_set().filter(status='Active')
return qs

class Member(models.Model):

membertype=models.ForeignKey(Membertype,related_name='members',db_column='mtypeid',
 
null=True, on_delete=models.SET_NULL,help_text='Type of 
member.',verbose_name='Member Type')
lname = models.CharField(max_length=150, db_column='lame', blank=True, 
help_text='Last name.',verbose_name='Last Name') 
fname = models.CharField(max_length=150, db_column='fame', blank=True, 
help_text='First name.',verbose_name='First Name') 
status = models.CharField(max_length=12,db_column="status", 
blank=True,help_text="Membership status)

objects = models.Manager() # the default manager

Active_objects = MemberActive()
 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b50fb9fd-8c2c-41db-93a6-f4329e7498b3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Text Field stifles creating HTML

2013-04-11 Thread rmschne
Further debugging ... printed the HTML that is produced by the call to 
render and the HTML is created correctly.  Thus, I have concluded the 
problem has nothing to do with Django.  Closed.

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




Text Field stifles creating HTML

2013-04-11 Thread rmschne
Django 1.5.1. I have a data model with a Django TextField: 
notes=models.TextField(db_column='notes',blank=True) and in thy MySQL the 
'notes' field is "TEXT".

When I output the 'notes' field in a Django Template in a for loop, the 
template just stops.  It does not go through the entire list of records. 
When I remove that field and output no fields that Django knows as 
"TextField" it works properly.  The database table now has only 25 records, 
but eventually there will be hundreds.  

What could be causing this?

Code below:  the first bit is just test block.  taking {{ s.notes }} out in 
either of the places makes it work ok. If {{ s.notes }} present in either 
place, fail.


==
{% for s in speaker_list %}
{{ s.id }}, {{ s.lname }}, {{ s.targetseason.season }}, {{ s.affiliation 
}}, {{ s.targetmtg.date|date:"D d M Y" }} {{ s.notes }} 
{% endfor %}



ID
Name
Affiliation
Title
Contact(s)
Target Season
Target Meeting Type
Target Meeting
Status
Notes



{% for s in speaker_list %}

{{ s.id }}
{{ s.fname }} {{ s.lname }}
{{ s.affiliation }}
{{ s.jobtitle }}
{{ s.contactname }}
{{ s.targetseason.season }}
{{ s.targetmtg.typemtg }}
{{ s.targetmtg.date|date:"D d M Y" }}
{{ s.status.description }}
{{ s.notes }}


{% endfor %}



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




Re: TemplateDoesNotExist Error...

2012-11-19 Thread rmschne
Yes, with guidance from Django/Python, I am sure the error occurs there. 
Django/Pythyon presents the trace and the line number which causes the 
exception is reported to the command Line.  However, I will look again at 
that line and all lines above.

Yes, I know there is a "good" chance as the clue is that is what the error 
message says. However, the fact is the file does exist. I've used 
copy/paste to test using "ls" the existence of both the Template folder and 
the file.  "ls" can find it. OSX's Finder can find it.  It's there.

If I comment out this part of the code, the next section which works on 
another template located in the same folder also fails.  Oddly, the first 
set of commands working on a template in the same folder works.  It's just 
the "next" one.

As mentioned, a web server is not involved, so not sure how to use the 
LOGGING variable.  I will look again.

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



TemplateDoesNotExist Error...

2012-11-19 Thread rmschne
 

I have moved to a new laptop which is both my development and production 
platform. The only change in infrastructure is that I run Python, Django, 
and all else in a virtual environment (VirtualEnv).  

I am not using Django to run on a web server.  

I have a function which produces a set of HTML files.  The first calls

t=get_template('soc_ad_host_and_guest_list.html')  
txt=smart_str(t.render(Context({ ... more stuff })))

and the above works fine.

On the second call to a different template which a) does exist, and b) is 
in the template folder defined by TEMPLATE_DIRS,

 t=get_template('soc_ad_table_guest_list_for_prog.html')
 txt=smart_str(t.render(Context({'host_list': hostlist,})))and at the 
statement txt= I get the Django Error: TemplateDoesNotExist

Since I'm not on a web server I can't see the so-called "post mortem" 
message.  But the template files 'soc_ad_table_guest_list_for_prog.html' 
does indeed exist, its permissions are 770 (same as the first template that 
does work).

Suggestions? Any more debugging I can turn on?

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



Re: All of the sudden getting TemplateDoesNotExist error

2012-07-25 Thread rmschne
Karen,

All sorted now.

Thanks!  Well (tail between legs), the problem was not the template that 
was being called, but a template being "included" inside that template. 
 That second template is loaded based on a few "if" statements, and a 
bug/flaw in my logic (undetected until now ... code in place for months), 
failed to load a valid template file.  Didn't get error messages (no access 
to "post mortem" page as I don't run the app on a web servrer) sufficient 
to point me to the real cause and I was chasing red herrings for a while.

Message for others:  when in similar circumstances, look for issues not 
only with the first-called template, but any templates "included".

Re "alpha" ... well, simple inertial.  The Django stuff I do is not on a 
web server but on my PC.  I use Django to construct static HTM files, and 
other things, from content held in the database. I simply copy the HTM 
files to the server on change.  Sort of taking the approach "it works, 
don't break it on purpose".  I'll do an upgrade to current version this 
week.  

On Wednesday, 25 July 2012 02:33:17 UTC+1, Karen Tracey wrote:
>
> On Tue, Jul 24, 2012 at 11:41 AM, rmschne  wrote:
>
>> I have made no changes to settings.py. Honest.  I'm running Django 1.4.0 
>> alpha.
>
>
> Why alpha rather than the released version? Not that I think it has 
> anything to do with the problem, it just seems odd to stick with an alpha 
> level after the official release is available.
>
>  
>
>> The variable TEMPLATE_DIRS is pointing to a folder which exists and the 
>> template 'directory.html' i wish to load in in that 
>> folder, /Users/rmschne/Documents/source/django/projects/socmgmt/templates/. 
>>  My ID has appropriate permissions (running on Mac OS/X). 
>>
>> All of the sudden today (and it worked  a few days ago), I get 
>> "TemplateDoesNotExist" error.  This happens for any of the templates I try 
>> to load.
>>
>> Frankly, I'm at a kinda loss as to where to start debugging this since 
>> everything looks ok and I don't recall making any changes that would be 
>> relevants.
>>
>>
> With DEBUG on the template loader post mortem on the debug page should 
> give some clues.  What does it say?
>
> Karen
> -- 
> http://tracey.org/kmt/
>
>

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



All of the sudden getting TemplateDoesNotExist error

2012-07-24 Thread rmschne
I have made no changes to settings.py. Honest.  I'm running Django 1.4.0 
alpha. The variable TEMPLATE_DIRS is pointing to a folder which exists and 
the template 'directory.html' i wish to load in in that 
folder, /Users/rmschne/Documents/source/django/projects/socmgmt/templates/. 
 My ID has appropriate permissions (running on Mac OS/X). 

All of the sudden today (and it worked  a few days ago), I get 
"TemplateDoesNotExist" error.  This happens for any of the templates I try 
to load.

Frankly, I'm at a kinda loss as to where to start debugging this since 
everything looks ok and I don't recall making any changes that would be 
relevants.

Thoughts?

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



Re: Query Set involving Model Method

2011-01-17 Thread rmschne
Much thanks to all.

I could not get something like:
gs=DinnerHost.objects.all().filter(complete()=True

to work. probably think fingers on my side to get the nomenclature
write; but I suspect not possible.

While I liked the idea of computing a new field "complete" in the
database which is updated on Save.  While initially thought to be a
good idea I changed my mind because:
1.  reqireired running the Python/Django program to update ... yet
some of the data in the db gets update via many other tools and so
there will be an consistency issue.
2.  writing a stored procedure to update in MysQL ... too complicated
3.  doing it as a batch update in Python/Django ... means hitting all
the records and then sort of messes up the value of the timestamp on
each record.  I'd rather that timestamp mean something more real than
that.
4.  add a related table which does this computation (fixing problem
3) ... too complicated

in the end what I did was in the program where I want to do something
with the "not complete" records, I write a small routine in the
program that extracts a query set with all records, then loops through
all records and finds where, using the Model definition, "if not
h.complete():" where "h" is the record from the loop in the query set.
Then I just append to a list the ID of that record.  Then i re-query
the database for those records where ID is in the list.

Works.  understandable for those who follow, etc.  No db changes and
no added maintenance.

 
hosts1=DinnerHost.objects.all().filter(year__exact=CURRENT_YEAR)
tablelist=[]
for h in hosts1:
if not h.complete():
tablelist.append(h.tablename)
 
hosts2=DinnerHost.objects.filter(year__exact=CURRENT_YEAR).filter(tablename__in=tablelist)

Now hosts2 has what I want.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Query Set involving Model Method

2011-01-16 Thread rmschne
Mikhail,

Thanks. I like that idea.  Simple and understandable for those who
follow me.

On Jan 16, 2:51 pm, Mikhail Korobov <kmik...@googlemail.com> wrote:
> It doesn't work that way. ORM translates you queries to SQL and the DB
> is responsible for filtering. It is not possible to translate
> arbitrary python function to SQL or pass it to DB engine. So you have
> to formulate you query using .filter syntax or raw SQL.
>
> Another possibility is to denormalize data: add 'complete' field to
> the model and recalculate it on save (or whenever it make sense). This
> is often a good solution and it is better than complex queries in
> terms of performance.
>
> On 16 янв, 19:16, rmschne <rmsc...@gmail.com> wrote:
>
>
>
>
>
>
>
> > Thanks. I'm still messing with this; but don't think it quite what I'm
> > looking for.
>
> > I want/need the Model Definition function complete() for use at the
> > record level.  I did this as a function since the rules are not based
> > simply on the value of the fields.
>
> > Ideally, I'd like to have the class DinnerHoseManager(modes.Manager)
> > use the complete() function to help return the query set for where
> > complete()=True.  How to put that into this class?
>
> > It's not the simple filter. Need a little more complexity to
> > determining "complete" based on the two if statements.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Query Set involving Model Method

2011-01-16 Thread rmschne
Thanks. I'm still messing with this; but don't think it quite what I'm
looking for.

I want/need the Model Definition function complete() for use at the
record level.  I did this as a function since the rules are not based
simply on the value of the fields.

Ideally, I'd like to have the class DinnerHoseManager(modes.Manager)
use the complete() function to help return the query set for where
complete()=True.  How to put that into this class?

It's not the simple filter. Need a little more complexity to
determining "complete" based on the two if statements.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Query Set involving Model Method

2011-01-16 Thread rmschne
Following is an extract of a Model I'm using.  I'd like to be able to
query it to get a query set return that uses one of the Model
Definitions, e.g. get all the Hosts where "complete=True" where
'complete' is a model definition.

I know the nomenclature to use when exclude/include on a field in the
model, e.g. using "sponsor"
qs=DinnerHost.objects.exclude(sponsor=False)

But I want to use the model definition, along the lines suggested by
(but does not work) to get all the completed hosts:

qs=DinnerHost.objects.filter(complete=True)
and tried
gs=DinnerHost.objects.filter(complete()=True

What is the right nomenclature to get this?

Thanks

===


Backup:

class DinnerHost(models.Model):
member = models.ForeignKey(Member, null=True,
db_column='memberid', related_name="hosts", blank=True)
meeting = models.ForeignKey(Meeting, null=True,
db_column="meetingid", related_name="hosts", blank=True)
host = models.CharField(max_length=300, db_column='Host',
blank=True)
sponsor = models.BooleanField(db_column='Sponsor', blank=True)

def complete(self):
# rules for what makes a complete booking
if self.sponsor and self.isadreceived and self.isfullybooked:
return True
if not self.sponsor and self.isfullybooked:
return True
return False

objects = models.Manager()


Note;
1. not all fields show, for simplicity
2. isfullybooked and isadreceived are both Model methods.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: how to query foreign keys down more than one level

2010-08-07 Thread rmschne
Thanks to Steve and Daniel.  Cool.

I'm learning as I go about naming fields.  Going back and fixing where
possible (but sometimes a lot of work). Agree right to do the first
time; but learning!

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



how to query foreign keys down more than one level

2010-08-07 Thread rmschne
I have a model like that I would like query down more than one level
(using my nomenclature).

class Library(models.Model)
  branch=models.CharField(max_length=100)

class Book(models.Model)
  libraryid=models.ForeignKey(Library,related_name="books")

class Chapter(models.Model)
  bookid=models.ForeignKey(Book,related_name="chapters")


I can get a library object:

l=Library.objects.filter(branch="Covent Garden")

and then get a query set of all the books in Covent Garden

b=l.books.all()

How do I get a query set of all the chapters (in all the books) in the
Covent Garden library?

then then if I added

class Paragraph(models.Model)
  chapterid=models.ForeignKey(Chapter,related_name="paragraphs")

How would I get a query set of all the paragraphs (in all the chapters
in all the books) in the Covent Garden library?

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



Re: Crashing Dev Server (or Browser?)

2010-08-01 Thread rmschne
Sorted.  But gosh, why did this simple error crash Python?

for both these models, a recent change was to remove a database field
and replace with function in the model.  However I neglected to change
the __unicode__() method for that model to change the the variable
from "self.abcdefg" to "self.abcdefg()".  Doing that for both fixed
the crashing problem.

I've never been able to crash Python before.  Exception handling
always seemed to work. I feel rather proud.  (but wonder how this
possible).

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



Re: Crashing Dev Server (or Browser?)

2010-08-01 Thread rmschne
4C-BB7B-F27ED45A9A65> /System/Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so
   0x1011f3000 -0x1011f4ff7  _hashlib.so ??? (???)
<0251E074-8F4E-6731-04FA-1D92B42DF43E> /System/Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_hashlib.so
   0x1011f8000 -0x1011fbff7  zlib.so ??? (???)
 /System/Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/lib-dynload/zlib.so
   0x10154 -0x101546fff +_mysql.so ??? (???) <71D7CF20-
D04F-3CA2-D091-4CA096A7E8D9> /Users/rmschne/.python-eggs/
MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
   0x101552000 -0x101601fef +libmysqlclient_r.16.dylib
17.0.0 (compatibility 17.0.0) <1D248DEB-52F6-551E-93F9-2F00C023FDE7> /
usr/local/mysql/lib/libmysqlclient_r.16.dylib
   0x1017b5000 -0x1017baff7  array.so ??? (???)
 /System/Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/lib-dynload/array.so
   0x1017c -0x1017c0fff  _bisect.so ??? (???)
<88DC4681-9949-89B5-042C-0D95FEF9B70E> /System/Library/Frameworks/
Python.framework/Versions/2.6/lib/python2.6/lib-dy

Crashing Dev Server (or Browser?)

2010-08-01 Thread rmschne
I have  a small Django app that until now has been used simply for
access to the data (in MySQL) for doing computations/reporting and
outputting results to files.  Have not been using the ADMIN module or
Dev server or anything.   Now that hard part of this work, I'm
starting to get the admin app going.

All the tables from the model are registered
(admin.site.register(CLASSNAMEHERE)).  All works but for two  out of a
dzon of the classes (tables in MySQL). For those two when I click the
link in the admin page using latest version of Apple Mac Safari,
*both* Safari and the dev server crash.  I can't tell which causes
which, and frankly find it odd that either to affect the other like
this.

Running Django 1.2.1 and Python 2.6.1

Any ideas?

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



Re: distinct() ?

2010-07-21 Thread rmschne
statuscodes=Member.objects.values('status').order_by('status').distinct()

It gives me the expected results.  Three items in the dictionary from
a database table of about 10,000 records:
[{'status': u'ACTIVE'}, {'status': u'RESIGNED'}, {'status':
u'TRANSFER'}]

it's what i both expected and want.

On Jul 21, 7:33 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
> I thought you were trying to get:
>
> I'm expecting only the four distinct records.
>
> You'll get a ValuesQuerySet or list of dictionaries with redundant keys this
> way.
>
> Thanks,
> Subhranath Chunder.
>
>
>
> On Wed, Jul 21, 2010 at 11:40 PM, rmschne <rmsc...@gmail.com> wrote:
> > Member.objects.values('status').order_by('status').distinct()  from
> > jaymzcd works perfectly. Thanks!
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@google 
> > groups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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



Re: distinct() ?

2010-07-21 Thread rmschne
Member.objects.values('status').order_by('status').distinct()  from
jaymzcd works perfectly. Thanks!

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



Re: distinct() ?

2010-07-21 Thread rmschne
Yep.  (as I slap my forehead).

I read that but erroneously concluded that since I had no sort_by on
the query, I didn't pursue it.  There is a default ordering in the
model.
I've solved the problem by passing the returned dictionary through my
own distinct() function which strips out duplicates.

Thanks!

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



distinct() ?

2010-07-21 Thread rmschne
I'm trying to use the distinct() and it's giving me unexpected
results.  Surely it's something simple, but I can't spot it.

I've referred to 
http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

In SQL, it would be:
select distinct status from members;

in Django I am using:
statuscodes=Member.objects.values('status').distinct()

With SQL I get the four distinct values of status from the database I
expect.

In Django, I get back a dictionary with every record.  I'm expecting
only the four distinct records.

Any thoughts on what i'm doing wrong?

Thanks!

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



Re: can foreign key fields be empty?

2010-07-21 Thread rmschne
Em,

Perfect.  Thanks for taking the time on this.  Greatly appreciated!!
I'm going to re-write the code here.

(in all my reading, I missed _isnull field lookup)

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



Re: can foreign key fields be empty?

2010-07-19 Thread rmschne
thanks. I've read almost all the documentation at least three or for
times (or more) and I go back to it constantly. Plus I have a couple
of books that I read all the time (I esp. like the book by Forcier,
Bissex, and Chun).  Neither the documentation nor this book gives, far
as I can tell, an example of how to get a query set that shows all
records with no parent.

The pointer you gave, thanks very much, explains how to set the data
model to allow nulls, which I've done already.  Further, as I
originally mentioned, I'm not using Django to control data entry, so
the None=True in the data model doesn't really have any impact, I
think.  Perhaps i'm wrong on that; but no matter because the data with
null parent fields are indeed in the database.

My problem, perhaps badly explained, was to extract with Django
queryset all those records in the without parents.  That's what's
vexing me.

I've done it now with a SQL query to return a Python list. Not as
elegant, but appears to work .  Thanks.

On Jul 18, 9:05 pm, Ramiro Morales <cra...@gmail.com> wrote:
> On Sun, Jul 18, 2010 at 4:33 PM,rmschne<rmsc...@gmail.com> wrote:
> > Thanks ... but where does "None=True" go?
>
> That should be null=True winn defining the ForeignKey field.
>
> See
>
> http://docs.djangoproject.com/en/1.2/topics/db/models/#field-options
>
> Please accept this humble suggestion:
>
> Reading the documentation from beginning to end once
> will help you a lot when beginning. It would be unfortunate
> to not take advantage of such a great body of documents.
> There are other projects where this is not possible
> because the docs are very basic. But this isn´t the
> case with Django.
>
> Regards,
>
> --
> Ramiro Morales  | http://rmorales.net

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



Re: can foreign key fields be empty?

2010-07-18 Thread rmschne
Thanks ... but where does "None=True" go?

On Jul 18, 7:08 pm, Subhranath Chunder <subhran...@gmail.com> wrote:
> A simple "None=True" should work.
>
> Thanks,
> Subhranath Chunder.
>
>
>
> On Sun, Jul 18, 2010 at 11:25 PM, rmschne <rmsc...@gmail.com> wrote:
> > I have two tables where one is a foreign key for the other. For some
> > of the "children" there is no "parent".  Hence I want to leave the
> > linking field NULL (empty) in the child database table.  I am having
> > trouble making a queryset which finds all children without parents.  I
> > was thinking looking for the linking field to be <1 or None or
> > something.  Not working.  I'm thinking that it is because Django
> > cannot allow a child record to no have a parent when their a foreign
> > key defined?
>
> > I'm not using Django, yet, to put data into the database, so there are
> > children with no parents in the database.  This makes sense for the
> > purpose of the application, but I can't get Django to tell me which
> > children have no parents.
>
> > Thoughts?
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@google 
> > groups.com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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



can foreign key fields be empty?

2010-07-18 Thread rmschne
I have two tables where one is a foreign key for the other. For some
of the "children" there is no "parent".  Hence I want to leave the
linking field NULL (empty) in the child database table.  I am having
trouble making a queryset which finds all children without parents.  I
was thinking looking for the linking field to be <1 or None or
something.  Not working.  I'm thinking that it is because Django
cannot allow a child record to no have a parent when their a foreign
key defined?

I'm not using Django, yet, to put data into the database, so there are
children with no parents in the database.  This makes sense for the
purpose of the application, but I can't get Django to tell me which
children have no parents.

Thoughts?

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



Re: Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-16 Thread rmschne
To complete the story, in case someone finds this in the future, I
ended up with the following which at the time of this writing seems to
work:

class MyNullBooleanField(models.NullBooleanField):
"""Designed to work with how Microsoft Access stores booleans as
-1 and 0 into MySQL.
The to_python function was taken from the Django modeld with
addition of -1 for true."""
__metaclass__ = models.SubfieldBase
def to_python(self,value):
if value in (True, False):
return bool(value)
if value in ('None',):
return None
if value in ('t', 'True', '1', '-1', 1, -1):
return True
if value in ('f', 'False', '0', 0):
return False
if value is None:
return None

The whole to_python function was taken from the standard definition
from the Django library.  My simple first draft wasn't complete
enough. I found that i needed to test for the integers 0,1, and -1 in
addition to their string equivalents in if value in "('t', 'True',
'1', '-1', 1, -1)" and "if value in ('f', 'False', '0', 0)". With that
change it appears to handle the boolean data stored into MySQL as
written by the Microsoft Access forms on the front end.

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



Re: Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-16 Thread rmschne
(While slapping my forehead) ... figured it out.  Have to remove
"models" as a prefix to MyNullBooleanField, as of course, the field
definition is not in models.

forinvoice.MyNullBooleanField(null=True,
db_column='forinvoice', blank=True)

Now to get on debugging the functionality of the new field.

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



Re: Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-16 Thread rmschne
Tom,

Thanks ... Can I get a bit more of your brain power. I'm struggling
with understanding the custom-model-fields document sufficient to
allow me to do it.

At the top of the models.py files, I put in:

class MyNullBooleanField(models.NullBooleanField):
"""Designed to work with how Microsoft Access stores booleans as
-1 and 0 into MySQL"""
__metaclass__ = models.SubfieldBase
def to_python(self,value):
if value is None: return
if value == 0:
return False
else:
return True

down further in that file, as a first test of this new field, for the
table/class where I want to use it:

class MemberAddress(models.Model):
member=models.ForeignKey(Member,related_name='addresses',
db_column='memberid')
city = models.CharField(max_length=50, db_column='city',
blank=True)
forinvoice=models.MyNullBooleanField(null=True,
db_column='forinvoice', blank=True)

When I run the code I get the error on the above "forinvoice" line:

AttributeError: 'module' object has no attribute 'MyNullBooleanField'

I was assuming that by defining the new custom field at the top of the
models.py file, it would work.  I can't find anything in the custom-
model-fields doc which says "where" to put this custom definition.  I
just assumed they intended it to go into models.py

What am i doing wrong?  Thanks!!

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



Re: Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-15 Thread rmschne
Oh ... by the way, we aren't using Access as a front end to Django.
There is nothing (far as I know) in Django to front-end to!

This app has been successfully making us money for more than 20
years.  The data side moved to MySQL a long time ago (can't remember
when) to enhance performance and security, but the relatively
sophisticated Access side remained in place and continued to evolve.
Still see no viable replacement on the horizon for Access for the
front end for use by people.  There are a number of tools that have
suficient capability to replace it but all would cost a fortune to
make it happen.  Instead, we're using Python/Django as a basis now for
enhanced reporting/number-crunching and future automation (which sends
us in the direction of having so many people having to use the Access
app).   Had we had Python and Django in the late 1980's we'd probably
be there now.

On Jul 14, 3:57 pm, Tom Evans <tevans...@googlemail.com> wrote:
> On Wed, Jul 14, 2010 at 1:45 PM, rmschne <rmsc...@gmail.com> wrote:
> > As I understand, in Django/Python, True is 1 and False=0.  And when
> > connected to the database, we use a TinyInt for that variable and
> > assign it to a NullBooleanField.
>
> True and False are global objects of type bool, not 1 and 0. bool
> constructor converts integers to True/False as appropriate.
>
>
>
> > Problem is that some people use their PC's with a Microsoft Access
> > based front end to the database (MySQL).  The forms use check-boxes,
> > and when checked, which is supposed be "true", Access puts -1 into the
> > data base.  Django doesn't recognize that value as True.
>
> Yes, Access is dire. I think you can probably count the number of
> people using Access as a front end to django on one hand (possibly one
> hand with four fingers cut off).
>
>
>
> > I can't change the Access forms or system and don't tell me to stop
> > using Access. We don't have unlimited resources to fix all the
> > problems in the world!
>
> > I'm wondering if there is some way to tell Django in the data model to
> > let a model variable return True when <>0 (instead of when=1) , and
> > False when 0?
>
> > This seems the cleanest easiest way; but I can't see how to make this
> > possible?  Is it?  Or is there another approach ?
>
> Define a MyBooleanField that extends models.BooleanField, override
> to_python(). Use that instead of models.BooleanField.
>
> Docs on that:http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/
>
> Cheers
>
> Tom

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



Re: Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-14 Thread rmschne
Tom,

Thanks!

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



Redefine True and False for Boolean and/or NullBoolean Fields?

2010-07-14 Thread rmschne
As I understand, in Django/Python, True is 1 and False=0.  And when
connected to the database, we use a TinyInt for that variable and
assign it to a NullBooleanField.

Problem is that some people use their PC's with a Microsoft Access
based front end to the database (MySQL).  The forms use check-boxes,
and when checked, which is supposed be "true", Access puts -1 into the
data base.  Django doesn't recognize that value as True.

I can't change the Access forms or system and don't tell me to stop
using Access. We don't have unlimited resources to fix all the
problems in the world!

I'm wondering if there is some way to tell Django in the data model to
let a model variable return True when <>0 (instead of when=1) , and
False when 0?

This seems the cleanest easiest way; but I can't see how to make this
possible?  Is it?  Or is there another approach ?

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



Re: QuerySet returned based on a Python List?

2010-03-28 Thread rmschne

>
> c1=Contact.objects.filter(hostid__tablename__in=list_of_names)
>
> The ORM is cool.

Ah.  "in".  how could I have missed that in the doc.  Too much staring
and not enough reading, I guess.  Thanks!

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



QuerySet returned based on a Python List?

2010-03-28 Thread rmschne
I have a query in Django with returns a queryset.

  c1=Contact.objects.filter(hostid__tablename=s)

where "s" is a string holding a tablename.

What I want to do is have Django return a query set where "s" is not
just a string, but a Python list, e.g. ['01','03','54'].

How do i construct a query that would do this?  I suspect it is not
the filter function, but can't spot something else that would work.
Thanks

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



Creating PHP code via template? Ignores PHP code enclosed in print <<

2009-12-30 Thread rmschne
I am trying to include some PHP code in Django template to created PHP
file(s) which get executed on the web server when copied across.

I'm finding that PHP code that is inside of <

Re: How to update one field in one existing record via Django?

2009-12-16 Thread rmschne
Thanks for the quick feedback.  I'm starting my "try" and I'm sure it
will work.

On Dec 16, 3:42 pm, Itay Donenhirsch <i...@bazoo.org> wrote:
> and ofcourse that should be:
> b.save()
> and not without the ()s
>
>
>
> On Wed, Dec 16, 2009 at 5:40 PM, Itay Donenhirsch <i...@bazoo.org> wrote:
> > try:
> >  b = Att.objects.get( pk = whatever_you_like )
> >  b.fieldname = a_variable
> >  b.save
> > except Att.DoesNotExist:
> >  print "oy vey"
>
> > you could also replace b.fieldname = ... with:
> > b.__setattr__( 'fieldname', a_variable )
>
> > itay
>
> > On Wed, Dec 16, 2009 at 5:35 PM, rmschne <rmsc...@gmail.com> wrote:
> >> Am I missing something?  I want to be able to update just one field in
> >> one records of a database via the Django data model.  If I create an
> >> object for that record and update that one field, via
>
> >> b=Att(fieldname=a_variable)
> >> b.save
>
> >> It creates a new record with all other fields blank.  For simplicity
> >> (and scalability of code), I'd prefer not to create a new record, nor
> >> do I want to put in all the field names.
>
> >> I undestand how I could (but have not yet done this) write custom SQL
> >> to do this; but is there a way using the native Django method of
> >> updating existing database?
>
> >> --
>
> >> You received this message because you are subscribed to the Google Groups 
> >> "Django users" group.
> >> To post to this group, send email to django-us...@googlegroups.com.
> >> To unsubscribe from this group, send email to 
> >> django-users+unsubscr...@googlegroups.com.
> >> For more options, visit this group 
> >> athttp://groups.google.com/group/django-users?hl=en.

--

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




How to update one field in one existing record via Django?

2009-12-16 Thread rmschne
Am I missing something?  I want to be able to update just one field in
one records of a database via the Django data model.  If I create an
object for that record and update that one field, via

b=Att(fieldname=a_variable)
b.save

It creates a new record with all other fields blank.  For simplicity
(and scalability of code), I'd prefer not to create a new record, nor
do I want to put in all the field names.

I undestand how I could (but have not yet done this) write custom SQL
to do this; but is there a way using the native Django method of
updating existing database?

--

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




Re: Avoiding MIME_BASE64_TEXT SpamAssassin Test when sending Email From Django?

2009-11-24 Thread rmschne
Jerek,

Thanks ...  starting now.

--

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




Avoiding MIME_BASE64_TEXT SpamAssassin Test when sending Email From Django?

2009-11-23 Thread rmschne
I'm using Django's email sending functions (http://
docs.djangoproject.com/en/dev/topics/email/#topics-email) to send
mail.

I construct the simple HTML mail with a small bit of Python code which
is based on data from a database accessed via Django and using a
Django template to construct the html text.  I pass this text to
Django's email functions, e.g.

msg=EmailMessage(subject, html_content, from_email, [to])
msg.content_subtype="html"
msg.send

The mail goes just fine.  In testing I'm sending mail to myself.  My
own SpamAssassin filter is trapping the mail as "spam" !!
 --
--
1.7 MIME_HTML_ONLY BODY: Message only has text/html MIME parts
2.8 MIME_BASE64_TEXT   RAW: Message text disguised using base64
encoding

I'm trying want to NOT send in base64 encoding so as to not attract
this SpamAssassin.  How when constructing the text for the mail in
Python/Django to avoid this?

I have nothing but text in the email.  The html is simple.  It has a
style sheet in the header.  The header looks like this:


   
   
   The Scottish Oil Club
   

Re: Unicode Text for Dictionary Keys ok for Templates?

2009-08-18 Thread rmschne

Karen,

Humm.  Ah.  Yes. Obvious, isn't it!  Thanks.

On Aug 16, 8:13 pm, Karen Tracey <kmtra...@gmail.com> wrote:
> On Sun, Aug 16, 2009 at 1:28 PM, rmschne <rmsc...@gmail.com> wrote:
>
> > I'm extracting data from a database and then cross-tabbing the data
> > (with some Python) code to create a list of dictionary data.  Because
> > the key names are derived from data in the database, and the database
> > is composed of unicode text, the keys are unicode, e.g. here are three
> > records in the list of dictionaries:
>
> > 'Date': datetime.date(2009, 3, 31), (u'ORM',): 1L, (u'ORMR',): 23L},
>
> You might want to revisit how you are creating these dictionaries, because
> your 'unicode' keys are not unicode.  They are single-element tuples where
> the single elements are unicode strings.  Note the parens and comma in
> (u'ORM',): 1L, for example.  If the key was the unicode string u'ORM' this
> would show up as simply u'ORM': 1L.
>
>
>
> > [snip]
> > The template is
> > {% for li in member_stats %}
> > {{ li.Date }} {{li.HON }} {{li.ORM }} {{li.ORMR }} {{li.CORP1 }}
> > {{li.CORP2 }} {{li.CORP3 }}
> > {% endfor %}
>
> > The Date fields come out as expected.  The other fields do not.
>
> > Is it because they are Unicode? If so, how to deal with this.  As
> > mentioned, these aren't hard-coded, but are coming originally from the
> > data to construct a cross tab table (sometimes called Pivot Table).
>
> From a template li.HON will translate to the dictionary lookup li[u'HON'] in
> Python.  That will find a matching unicode key u'HON' but you don't have
> that, your keys are tuples.  You can experiment in the shell to see what
> happens:
>
> >>> key1 = u'ORM'
> >>> key2 = (u'ORMR',)
> >>> d = {key1: 1L, key2: 23L}
> >>> d
>
> {u'ORM': 1L, (u'ORMR',): 23L}>>> d['ORM']
> 1L
> >>> d['ORMR']
>
> Traceback (most recent call last):
>   File "", line 1, in 
> KeyError: 'ORMR'
>
> >>> d[('ORMR',)]
> 23L
>
> I think you want to fix your dictionary creation step to actually create
> keys that are unicode, not single-element tuples.
>
> Karen
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Unicode Text for Dictionary Keys ok for Templates?

2009-08-16 Thread rmschne

I'm extracting data from a database and then cross-tabbing the data
(with some Python) code to create a list of dictionary data.  Because
the key names are derived from data in the database, and the database
is composed of unicode text, the keys are unicode, e.g. here are three
records in the list of dictionaries:

'Date': datetime.date(2009, 3, 31), (u'ORM',): 1L, (u'ORMR',): 23L},
{(u'EXEC',): 48L, (None,): 39L, (u'POT',): 10L, (u'HON',): 65L,
(u'CORP1',): 1L, (u'CORP2',): 4L, (u'CORP3',): 7L, 'Date':
datetime.date(2009, 4, 30), (u'ORM',): 1L, (u'ORMR',): 23L},
{(u'EXEC',): 48L, (None,): 39L, (u'POT',): 10L, (u'HON',): 65L,
(u'CORP1',): 1L, (u'CORP2',): 4L, (u'CORP3',): 7L, 'Date':
datetime.date(2009, 5, 31), (u'ORM',): 1L, (u'ORMR',): 23L},
{(u'EXEC',): 48L, (None,): 39L, (u'POT',): 10L, (u'HON',): 65L,
(u'CORP1',): 1L, (u'CORP2',): 4L, (u'CORP3',): 7L, 'Date':
datetime.date(2009, 6, 30), (u'ORM',): 1L, (u'ORMR',): 23L},

the call to get the template created (I'm writing to a file):

t=get_template('memberdir/member_statistics.html')
f.write(smart_str(t.render(Context({'member_stats': n}

where "n" is the list of dictionaries.

The template is
{% for li in member_stats %}
{{ li.Date }} {{li.HON }} {{li.ORM }} {{li.ORMR }} {{li.CORP1 }}
{{li.CORP2 }} {{li.CORP3 }}
{% endfor %}

The Date fields come out as expected.  The other fields do not.

Is it because they are Unicode? If so, how to deal with this.  As
mentioned, these aren't hard-coded, but are coming originally from the
data to construct a cross tab table (sometimes called Pivot Table).

--rms

--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Model Methods and displaying in template?

2009-08-09 Thread rmschne

Daniel,

Now we're cooking. You were quite right.  A red herring that I had the
wrong syntax.  The function list2text was not correct. It had been
correct but for whatever reason I didn't notice that I messed up a tab
key (in Python) and it was not computing correctly (whereas at one
point it was). I fixed the missing tab and I put a few more bits of
defensive coding.  Thanks!

On Aug 9, 12:55 pm, Daniel Roseman <dan...@roseman.org.uk> wrote:
> On Aug 9, 12:42 pm, rmschne <rmsc...@gmail.com> wrote:
>
>
>
>
>
> > I'm looking for the right syntax for inside a template to display a
> > model variable that is actually not a field in the database (defined
> > by the mode), but a Model method.
>
> > Class Member(model.Models):
> >     id = models.IntegerField(primary_key=True, db_column='ID')
> >     lname = models.CharField(max_length=150, db_column='LName',
> > blank=True)
> >     fname = models.CharField(max_length=150, db_column='FName',
> > blank=True)
> >      (plus other fields)
>
> >     def contactslistindirectory(self):
> >         """Returns a comma deliminted list of all member contacts
> > (with last contact prefixed by and)"""
> >         s1=self.contacts.all().filter(indirectory=True)
> >         s=list2text(s1)
> >         return s
>
> > The model method "contactslistindirectory() returns a string of the
> > name of the contacts for that member.  It's getting that information
> > from another model called Contact which has a ForeignKey connection
> > back to Member.
>
> > I have a template working that can display {{ member.lname }},
> > {{member.fname }} and others.  The template loops through all
> > members.
>
> > I want to display in the template for each member the value of what is
> > in contactslistindirectory.  I've tried
> > {{ member.contactslistindirectory }} and that doesn't work.  I don't
> > know the syntax for displaying the value of a Model Method in a
> > template.  I'm sure the answer is right in front of me, but despite
> > searching the documentation for examples, I can't spot it.  I can see
> > how the model methods are defined, but as yet have not seen how to use
> > that in a  template.
>
> > Any pointers?
>
> {{ member.contactslistindirectory }} is the correct syntax. There must
> be something wrong with the method - perhaps the filter is not
> returning any results, or perhaps list2text is incorrect.
>
> You might try debugging by putting a 'print s' before the return
> statement in your method, and seeing what that prints in the console.
> --
> DR.
--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Model Methods and displaying in template?

2009-08-09 Thread rmschne

I'm looking for the right syntax for inside a template to display a
model variable that is actually not a field in the database (defined
by the mode), but a Model method.

Class Member(model.Models):
id = models.IntegerField(primary_key=True, db_column='ID')
lname = models.CharField(max_length=150, db_column='LName',
blank=True)
fname = models.CharField(max_length=150, db_column='FName',
blank=True)
 (plus other fields)

def contactslistindirectory(self):
"""Returns a comma deliminted list of all member contacts
(with last contact prefixed by and)"""
s1=self.contacts.all().filter(indirectory=True)
s=list2text(s1)
return s

The model method "contactslistindirectory() returns a string of the
name of the contacts for that member.  It's getting that information
from another model called Contact which has a ForeignKey connection
back to Member.

I have a template working that can display {{ member.lname }},
{{member.fname }} and others.  The template loops through all
members.

I want to display in the template for each member the value of what is
in contactslistindirectory.  I've tried
{{ member.contactslistindirectory }} and that doesn't work.  I don't
know the syntax for displaying the value of a Model Method in a
template.  I'm sure the answer is right in front of me, but despite
searching the documentation for examples, I can't spot it.  I can see
how the model methods are defined, but as yet have not seen how to use
that in a  template.

Any pointers?


--~--~-~--~~~---~--~~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Making Custom Model Methods to Work

2008-08-24 Thread rmschne

I'm new to Django, and have played with Python for a few years on and
off (not a real programmer).  I'm keen to use Django to explore some
data because of its custom data models which I plan to rely on
extensively (putting the complex code there).

Try as I might, I can't see how to get them to work.  I can get the
fields from the database to display in the html created by the
render_to_response() function, but the custom fields do not compute
and display.  They come out empty. I'm also struggling how to get
access to the data inside of Python to enable data handling by other
Python code.  For example, when I issue a "print mvalues[0]" in the
example below, I get all the fields for the first record of the
database returned, but I don't the custome fields, which I expected.
My guess is I have to some other code format, but I don't see examples
for this in "The Definitive Guide to django" by Holovaty and Kaplan-
Moss.

Example: The data model-

class Tmeetings(models.Model):
Date = models.DateTimeField(null=True, blank=True)
Speaker = models.CharField(blank=True, max_length=150)
Venue = models.CharField(blank=True, max_length=150)
Cost = models.FloatField(null=True, blank=True)

def __str__(self):
return '%s, %s' % (self.Date, self.Speaker)

def test (self):
return self.Speaker+self.Venue

class Meta:
db_table = 'tmeetings'

class Admin: pass

Example: The test template file mtg_summary.html


{{ meeting_title }} 


template: mtg_summary.html
Talk_title: {{ Talk_Title }}
Speaker: {{ Speaker }}
Speaker_Title:{{ Speaker_title }}
test: {{ test }}



Example: The Problem (code snippet)

>>>from django.shortcuts import render_to_response
>>>from soc.models import Tmeeting
>>>m_values=Members.objects.values()
>>> print render_to_response('mtg_summary.html',mvalues[0])
Content-Type: text/html; charset=utf-8




 



template: mtg_summamry.html
Talk_title: None
Speaker: George Smith
Speaker_Title: Title of the test record
test: 


>>>

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Making Custom Model Methods to Work

2008-08-24 Thread rmschne

Daniel

You helped a lot.  You are right that my code wasn't clear.  I only
extracted snipets and forgot bits, e.g. talk _title and speaker_title
which are in the model but not in what I reported.  Frankly, all I'm
trying to do right now is experiment to learn how this works.
Eventually, I have a couple of projects in mind, the first being
something to generate HTML files for a web site based on content in a
database.

 You are right, the root cause is that I was not yet understanding how
to access the models and part of my learning is deaing with ojects in
Python.  With your key help, it now works and I see the light.

I learned:

1.  create the objects (one record from the database table) by
my_objectname=[Classname].objects.all()[N] where N is the record
number.
2.  when change the data model, I have to restart the python shell ...
on the to-do list is to learn how to redefine the data model.
3.  in the template, use the objectname in the double brackets, e.g.
{{ my_objectname.date }} and {{ my_objectname.test }}
4.  calling render_to_response is differnt than I thought!
print render_to_response('mtg_summary.html',{'my_meeting':my_meeting})

Question: in the context of this example, in
{'my_meeting':my_meeting}), what are these two things opposite of the
colon?

> It's not at all clear from the code what you're trying to do.
> talk_title and speaker_title aren't defined anywhere in the code
> you've given us, but I'm not even sure if those are the 'custom
> fields' you're referring to.
>
> What's more, the code you've given us would not be capable of
> producing the output you've shown, so this clearly isn't the actual
> code. We would need to see the actual view and template code - it's
> best if you paste it at dpaste.com and give us a link.
>
> If by 'custom fields' you mean methods on the model, like your test()
> example, you wouldn't expect the values() method to show them. It will
> only show the actual model fields.
>
> I think you're misunderstanding how to access models in your code and
> templates. values() isn't the normal way of doing it - really, you
> just want to be passing an instance of Tmeeting to your template and
> then using normal dot notation to access the values.
>
> For example:
>
> my_meeting = Tmeeting.objects.all()[0]
> print my_meeting.date
> print my_meeting.speaker
> print my_meeting.test()
> print render_to_response('mtg_summary.html',
> {'my_meeting':my_meeting})
>
> and in the template:
> Talk_title: {{ my_meeting.talk }}
> Speaker: {{ my_meeting.speaker }}
> Speaker_Title:{{ my_meeting.speaker_title }} {# where is this
> coming from? #}
> test: {{ my_meeting.test }}
>
> etc.
>
> (Note that the convention is to have lower case names for model fields
> and methods.)
>
> --
> DR.
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---