problem saving form data in sams "24 hour" book example
I'm a new user to django and am attempting to go through the Sams "Teach Yourself Django in 24 hours" book and am having an issue related to the chapter on saving form data. I'm hoping someone can give me a hand. I'm using Django 1.0 Here's my model: class Person(models.Model): userID = models.ForeignKey(User, unique=True) name = models.CharField('name', max_length=200) birthday = models.DateField('Birthday', blank = True, null=True) email=models.EmailField('Email', max_length=100, unique=True) Here's what the book says to use for the form: def person_form(request, pID='0'): p = get_object_or_404(Person, pk=pID) if request.method == 'POST': if request.POST['submit'] == 'update': message = 'Update Request for %s.' % p.name PersonForm = forms.form_for_instance(p) f = PersonForm(request.POST.copy()) if f.is_valid(): try: f.save() message += ' Updated.' except: message = ' Database Error.' else: message += ' Invalid.' That seems to be the "old" way of doing forms (I found that forms_for_instance doesn't exist), so I've modified it to look like this: class PersonForm(ModelForm): class Meta: model=Person def person_form(request, pID='0'): p = get_object_or_404(Person, pk=pID) if request.method == 'POST': if request.POST['submit'] == 'update': message = 'Update Request for %s.' % p.name f = PersonForm(request.POST) if f.is_valid(): try: f.save() message += ' Updates.' except: message = ' Database Error.' else: message += ' Invalid.' I hope my modications are correct here - they could be part of the issue. The problem I have is that when I go to the form for a person, such as http://127.0.0.1:8000/people/Form/3/, and then modify a field such as the birthday, when I then click on the update button, the is_valid () method returns false and the errors that get printed to the form are: * Person with this UserID already exists * Person with this Email already exists It seems like update is trying to create a new person with the same UserID, when really I want to just be modifying the person with that UserID. Can anyone tell me what I'm doing wrong? Thanks, Margie --~--~-~--~~~---~--~~ 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: problem saving form data in sams "24 hour" book example
Thank you so much - that was a huge help! Margie On Dec 2, 5:17 pm, "Colin Bean" <[EMAIL PROTECTED]> wrote: > On Tue, Dec 2, 2008 at 5:09 PM, Margie <[EMAIL PROTECTED]> wrote: > > > I'm a new user to django and am attempting to go through the Sams > > "Teach Yourself Django in 24 hours" book and am having an issue > > related to the chapter on saving form data. I'm hoping someone can > > give me a hand. > > > I'm using Django 1.0 > > > Here's my model: > > > class Person(models.Model): > > userID = models.ForeignKey(User, unique=True) > > name = models.CharField('name', max_length=200) > > birthday = models.DateField('Birthday', blank = True, null=True) > > email=models.EmailField('Email', max_length=100, unique=True) > > > Here's what the book says to use for the form: > > > def person_form(request, pID='0'): > > p = get_object_or_404(Person, pk=pID) > > if request.method == 'POST': > > if request.POST['submit'] == 'update': > > message = 'Update Request for %s.' % p.name > > PersonForm = forms.form_for_instance(p) > > f = PersonForm(request.POST.copy()) > > if f.is_valid(): > > try: > > f.save() > > message += ' Updated.' > > except: > > message = ' Database Error.' > > else: > > message += ' Invalid.' > > > That seems to be the "old" way of doing forms (I found that > > forms_for_instance doesn't exist), > > so I've modified it to look like this: > > > class PersonForm(ModelForm): > > class Meta: > > model=Person > > > def person_form(request, pID='0'): > > p = get_object_or_404(Person, pk=pID) > > if request.method == 'POST': > > if request.POST['submit'] == 'update': > > message = 'Update Request for %s.' % p.name > > f = PersonForm(request.POST) > > if f.is_valid(): > > try: > > f.save() > > message += ' Updates.' > > except: > > message = ' Database Error.' > > else: > > message += ' Invalid.' > > > I hope my modications are correct here - they could be part of the > > issue. > > > The problem I have is that when I go to the form for a person, such as > >http://127.0.0.1:8000/people/Form/3/, and then modify a field such > > as the birthday, when I then click on the update button, the is_valid > > () > > method returns false and the errors that get printed to the form are: > > * Person with this UserID already exists > > * Person with this Email already exists > > > It seems like update is trying to create a new person with the > > same UserID, when really I want to just be modifying the person > > with that UserID. > > > Can anyone tell me what I'm doing wrong? > > > Thanks, > > > Margie > > Change the way you create your form from this: > > f = PersonForm(request.POST) > > to this: > > f = PersonForm(request.POST, instance=p) > > Then your form will be populated with the data from 'p', and update > that record instead of creating a new one. > > Colin- Hide quoted text - > > - Show quoted text - --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
open source project management app that uses django?
Hi everyone, I would like to create a django project managment web app to be used internally in my company. I am a software developer, but have little experience with web apps other than my recent work going through the sams django tutorial book. I'm wondering if anyone knows of any open source/free django web app that I might be able to use to get started on this project. Let me describe the usage model to give you an idea of what I'm aiming for. At a very high level, the usage model for this web app is that a "manager" assigns tasks to "employees" on a weekly basis. Associated with each task is a set of measurements that must be performed by the employee as he/she does the task. The measurements vary based on the task, and somemes the measurement is reported with a comment string, sometimes a number, or sometimes a check mark in one of 'n' radio boxes. As the employees complete the tasks, they fill in the measurements. At the end of the week, the manager can look at each task and review the resulting measurements, and based on that data, decide the next weeks' tasks. Unlike a project mangament tool like MS Project, which helps you schedule and gannt chart the schedule, this is really a tool to for enhancing project communication. It is intended to allow the manager to easily communicate tasks to the employees, get the results back, and then make decisions about what the next set of tasks sould be. All without having to spend a lot of time emailing and talking to people. In the environement where it will be used, the manager is getting results back from maybe 100 different employees, each of which have a few tasks to do. The data is not complex, but there is just too much of it to manage without a tool. Currently folks are using wiki and excel, but in my opninion this is not really automated enough. My thought is that a django web client could provide a very simple and easy to use interface, and could also be extended to get all sorts of nice long term trend information. For exmaple, t would be interesting to know if a project being run at site A executes task 'foo' more frequently or for longer periods of time than a project being run at site B. As data is across multiple similar projects, it seems that it could be mined for lots of interesting info to help improve the productivity of future projects. Ok - so hopefully you get the idea. Now for my questions: * Does anyone know of existing web apps (django or otherwise) like that already exists? * Does this sound like something that would be good to do in Django? * Does anyone know of any free/open source software (django based) that I could use as a starting point? Not being a web developer, I know that if I do this from scratch, I will probably not do a great job. No doubt there are a ton of intracacies to window layout, the structure of the models, the html templates, and other things I haven't even thought of. So I'm thinking it would be great to bootstrap from some existing code, even if it doesn't do quite what I want. I would be happy to contribute my own work back to the open source community. Thanks for any ideas! Margie --~--~-~--~~~---~--~~ 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: open source project management app that uses django?
Thanks - yes, that is pretty much the approach I am planning to take, but I just figured I'd see if there was anything interesting out there that would give me a spiffy look and feel for the reporting pages. One thing that I find confusing is how to come up with a color scheme. I know that seems sort of low priority, but I swear the first thing people notice is if your colors are "ugly" or very basic looking (ie, black and white). Anyway, I will proceed with putting the models together as that is clearly the meat of the project at this poitn. I just learned about CRUD tonight, and I can see how that is very nice. Thanks, Margie On Dec 3, 5:59 pm, maeck <[EMAIL PROTECTED]> wrote: > Margie, > > If you can think up a decent model, you might be able to setup the > core of the project management application in the Django contrib.admin > module. > Development will go fast as long as you can stay with standard CRUD > pages. > The admin model will also give you the user security hooks necessary > for the manager and employees. > > As soon as you nee a need for reporting pages or ways to do things a > little more complex than the admin can give you, you can build custom > pages for those. But I would think you could have 80% of your app > running only by setting up the database models and nice admin pages. > > Maeck > > On Dec 3, 3:41 pm, Margie <[EMAIL PROTECTED]> wrote: > > > > > Hi everyone, > > > I would like to create a django project managment web app to be used > > internally in my company. I am a software developer, but have little > > experience with web apps other than my recent work going through the > > sams django tutorial book. > > > I'm wondering if anyone knows of any open source/free django web app > > that I might be able to use to get started on this project. Let me > > describe the usage model to give you an idea of what I'm aiming for. > > > At a very high level, the usage model for this web app is that a > > "manager" assigns tasks to "employees" on a weekly basis. Associated > > with each task is a set of measurements that must be performed by the > > employee as he/she does the task. The measurements vary based on the > > task, and somemes the measurement is reported with a comment string, > > sometimes a number, or sometimes a check mark in one of 'n' radio > > boxes. As the employees complete the tasks, they fill in the > > measurements. At the end of the week, the manager can look at each > > task and review the resulting measurements, and based on that data, > > decide the next weeks' tasks. > > > Unlike a project mangament tool like MS Project, which helps you > > schedule and gannt chart the schedule, this is really a tool to for > > enhancing project communication. It is intended to allow the manager > > to easily communicate tasks to the employees, get the results back, > > and then make decisions about what the next set of tasks sould be. > > All without having to spend a lot of time emailing and talking to > > people. In the environement where it will be used, the manager is > > getting results back from maybe 100 different employees, each of which > > have a few tasks to do. The data is not complex, but there is just > > too much of it to manage without a tool. Currently folks are using > > wiki and excel, but in my opninion this is not really automated > > enough. > > > My thought is that a django web client could provide a very simple and > > easy to use interface, and could also be extended to get all sorts of > > nice long term trend information. For exmaple, t would be interesting > > to know if a project being run at site A executes task 'foo' more > > frequently or for longer periods of time than a project being run at > > site B. As data is across multiple similar projects, it seems that it > > could be mined for lots of interesting info to help improve the > > productivity of future projects. > > > Ok - so hopefully you get the idea. Now for my questions: > > > * Does anyone know of existing web apps (django or otherwise) like > > that already exists? > > > * Does this sound like something that would be good to do in Django? > > > * Does anyone know of any free/open source software (django based) > > that I could use as a starting point? Not being a web developer, I > > know that if I do this from scratch, I will probably not do a great > > job. No doubt there are a ton of intracacies to window layout, the > > structure of the models, the html templates, and other things I > > haven't even
Re: open source project management app that uses django?
Ok - this is very useful! It is just great to see a "real" app that does something similar to what I want. The code looks very nice and seems simple to understand. I have downloaded it and integrated into my little play django application, but I have one problem. In the README it says: 6. Inside your MEDIA_ROOT folder, create a new folder called 'helpdesk' and copy the contents of helpdesk/htdocs/ into it. Alternatively, create a symlink: ln -s /path/to/helpdesk/htdocs /path/to/media/helpdesk This application assumes all helpdesk media will be accessible at http://MEDIA_PATH/helpdesk/ I did the ln, but I don't understand how to make the contantes of media/helpdes accessible at http://MEDIA_PATH/helpdesk/ What do I do to make them "accessible"? Margie On Dec 3, 11:27 pm, "Hanny Wibisono" <[EMAIL PROTECTED]> wrote: > http://www.jutdahelpdesk.com/ > > > > -Original Message- > From: django-users@googlegroups.com [mailto:[EMAIL PROTECTED] > > On Behalf Of Margie > > Hi everyone, > > I would like to create a django project managment web app to be used > internally in my company. I am a software developer, but have little > experience with web apps other than my recent work going through the > sams django tutorial book. > > I'm wondering if anyone knows of any open source/free django web app > that I might be able to use to get started on this project. Let me > describe the usage model to give you an idea of what I'm aiming for. > > At a very high level, the usage model for this web app is that a > "manager" assigns tasks to "employees" on a weekly basis. Associated > with each task is a set of measurements that must be performed by the > employee as he/she does the task. The measurements vary based on the > task, and somemes the measurement is reported with a comment string, > sometimes a number, or sometimes a check mark in one of 'n' radio > boxes. As the employees complete the tasks, they fill in the > measurements. At the end of the week, the manager can look at each > task and review the resulting measurements, and based on that data, > decide the next weeks' tasks. > > Unlike a project mangament tool like MS Project, which helps you > schedule and gannt chart the schedule, this is really a tool to for > enhancing project communication. It is intended to allow the manager > to easily communicate tasks to the employees, get the results back, > and then make decisions about what the next set of tasks sould be. > All without having to spend a lot of time emailing and talking to > people. In the environement where it will be used, the manager is > getting results back from maybe 100 different employees, each of which > have a few tasks to do. The data is not complex, but there is just > too much of it to manage without a tool. Currently folks are using > wiki and excel, but in my opninion this is not really automated > enough. > > My thought is that a django web client could provide a very simple and > easy to use interface, and could also be extended to get all sorts of > nice long term trend information. For exmaple, t would be interesting > to know if a project being run at site A executes task 'foo' more > frequently or for longer periods of time than a project being run at > site B. As data is across multiple similar projects, it seems that it > could be mined for lots of interesting info to help improve the > productivity of future projects. > > Ok - so hopefully you get the idea. Now for my questions: > > * Does anyone know of existing web apps (django or otherwise) like > that already exists? > > * Does this sound like something that would be good to do in Django? > > * Does anyone know of any free/open source software (django based) > that I could use as a starting point? Not being a web developer, I > know that if I do this from scratch, I will probably not do a great > job. No doubt there are a ton of intracacies to window layout, the > structure of the models, the html templates, and other things I > haven't even thought of. So I'm thinking it would be great to > bootstrap from some existing code, even if it doesn't do quite what I > want. I would be happy to contribute my own work back to the open > source community. > > Thanks for any ideas! > > Margie- Hide quoted text - > > - Show quoted text - --~--~-~--~~~---~--~~ 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: open source project management app that uses django?
Ok - forget it - I figured it out! I found the django pages on how to serve static files and that showed me what I need to know and it looks great now. On Dec 4, 12:54 pm, Margie <[EMAIL PROTECTED]> wrote: > Ok - this is very useful! It is just great to see a "real" app that > does something similar to what I want. The code looks very nice and > seems simple to understand. I have downloaded it and integrated into > my little play django application, but I have one problem. In the > README it says: > > 6. Inside your MEDIA_ROOT folder, create a new folder called > 'helpdesk' and > copy the contents of helpdesk/htdocs/ into it. Alternatively, > create a > symlink: > ln -s /path/to/helpdesk/htdocs /path/to/media/helpdesk > > This application assumes all helpdesk media will be accessible at > http://MEDIA_PATH/helpdesk/ > > I did the ln, but I don't understand how to make the contantes of > media/helpdes accessible athttp://MEDIA_PATH/helpdesk/ > > What do I do to make them "accessible"? > > Margie > > On Dec 3, 11:27 pm, "Hanny Wibisono" <[EMAIL PROTECTED]> wrote: > > > > >http://www.jutdahelpdesk.com/ > > > -Original Message- > > From: django-users@googlegroups.com [mailto:[EMAIL PROTECTED] > > > On Behalf Of Margie > > > Hi everyone, > > > I would like to create a django project managment web app to be used > > internally in my company. I am a software developer, but have little > > experience with web apps other than my recent work going through the > > sams django tutorial book. > > > I'm wondering if anyone knows of any open source/free django web app > > that I might be able to use to get started on this project. Let me > > describe the usage model to give you an idea of what I'm aiming for. > > > At a very high level, the usage model for this web app is that a > > "manager" assigns tasks to "employees" on a weekly basis. Associated > > with each task is a set of measurements that must be performed by the > > employee as he/she does the task. The measurements vary based on the > > task, and somemes the measurement is reported with a comment string, > > sometimes a number, or sometimes a check mark in one of 'n' radio > > boxes. As the employees complete the tasks, they fill in the > > measurements. At the end of the week, the manager can look at each > > task and review the resulting measurements, and based on that data, > > decide the next weeks' tasks. > > > Unlike a project mangament tool like MS Project, which helps you > > schedule and gannt chart the schedule, this is really a tool to for > > enhancing project communication. It is intended to allow the manager > > to easily communicate tasks to the employees, get the results back, > > and then make decisions about what the next set of tasks sould be. > > All without having to spend a lot of time emailing and talking to > > people. In the environement where it will be used, the manager is > > getting results back from maybe 100 different employees, each of which > > have a few tasks to do. The data is not complex, but there is just > > too much of it to manage without a tool. Currently folks are using > > wiki and excel, but in my opninion this is not really automated > > enough. > > > My thought is that a django web client could provide a very simple and > > easy to use interface, and could also be extended to get all sorts of > > nice long term trend information. For exmaple, t would be interesting > > to know if a project being run at site A executes task 'foo' more > > frequently or for longer periods of time than a project being run at > > site B. As data is across multiple similar projects, it seems that it > > could be mined for lots of interesting info to help improve the > > productivity of future projects. > > > Ok - so hopefully you get the idea. Now for my questions: > > > * Does anyone know of existing web apps (django or otherwise) like > > that already exists? > > > * Does this sound like something that would be good to do in Django? > > > * Does anyone know of any free/open source software (django based) > > that I could use as a starting point? Not being a web developer, I > > know that if I do this from scratch, I will probably not do a great > > job. No doubt there are a ton of intracacies to window layout, the > > structure of the models, the html templates, and other things I > > haven't even thought of. So I'm thinking it would be great
modeling questions
Am trying to get the hang of specifying my models, so bear with me ... Suppose that I want to reprsent states and the cities that are in them. I think I would have a model that looks like this: class State(models.Model): name = models.CharField('name', max_length=20) class City(models.Model): name = models.CharField('name', max_length=20) state = models.ForeignKey(State) Now, suppose that cities can have the same name, as long as they are in different states, and I want a way to check that when the user adds a city, that he/she doesn't add it twice for the same state. IE, the user has data for certain states and cities and wants to add only those for which there is data. The user will manually click on "add state", which will take them to a page where they input some state data and then can click a 'submit' button to save it. And also from that window they can click on an 'add city' button that will take them to a window where they can input data for a city and then submit that. If I want to make sure that the same city isn't added twice for the same state, do I simply do that check when the city data is "posted"? IE, if they try to add the same city twice, I just give an error saying it's already there? What if I want the user to be able to enter a whole bunch of cities at once, for example by entering them all in a table on a single page. What would be the appropriate way to represent that table? Sorry, I know these are probably very basic questions, just want to make sure I am on the right track. May I ask - is there anyone in the SF Bay area that would be interested in providing some irelatively nexpensive consulting to me to get me bootstrapped? I'm thinking a few hours to get me off and running, with perhaps continued time as needed. I live in Menlo Park and work in Santa Clara. Have tons of software and python experience, but no practical experience with django, sql, and web clients. The project I am working on is a project management tool to manage the process of chip design (the state/city thing above is just an analogy). Thanks! Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Bay Area Django consultant wanted
Hi, I am looking for a django developer/consultant that I can consult with in getting myself bootstrapped on django. I have an application in mind and would like to develop it myself, but I would like someone to advise me on the model creation and basically help guide me in getting started. This would be relatively informal, possibly some time together where I can explain my project, followed by various questions/ email. I can pay a reasonable, but not exorbitant rate. I work for a large company and would be developing this product for that company, but would be paying this out of my own pocket. Looking for someone that is available pretty much immediately. My time is flexible in terms of day/time for meeting. Hope this is an ok place to post this, sorry if I am offending anyone, I will post it only this once. Thanks, Margie --~--~-~--~~~---~--~~ 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: Do you recommend "Practical Django Projects"?
I was a total web framework newbie and got started with the SAMS book. I think it's called "learn Django in 24 hours" or something like that. It has a ton of errors and from that standpoint, it not a good book. However, it is the only book I've found that really leads you step by step through creating a vey basic site. I was able to figure out the errors by searching around on the web. Creating their basic web site and having that hands on, practical code to refer to was very helpful, in my opinion. It definitely goes into much more depth than the online tutorial. I am now reading "Python Web Development with Django", by Forcier, Bissex and Chun. It is a better book, but since I was very inexperienced in this area to start with, I don't think I really would have understood it without first doing something more hands-on. On Jan 5, 10:38 am, Benjamin Buch wrote: > I agree, Practical Django Projects is a great book! > Altough I would only recommend it if you've read the docs and worked > you way through the tutorial (which are both excellent as someone > mentioned earlier...) > It's full of best practices and a lot of bits and pieces that are not > covered by the tutorial. > Which is good by the way because the tutorial is clearly for > beginners, and Practical Django Projects is more towards the > intermediate djangonaut I would say. > As brad says, it gives you more of the big picture. > > I've learned a lot from it! > > So if you've got some time, wait a few months, if you are to eager or > to curious to learn django, just go and get it. > Altough it's a little bit outdated, the biggest part of it (especially > best practices) is still up to date. > If you know some django, you will recognize the parts where it's > behind django 1.0.2. > > benjamin > > Am 05.01.2009 um 15:42 schrieb brad: > > > > > > > On Jan 5, 2:21 am, HB wrote: > >> Do you recommend "Practical Django Projects" instead? > > > I got this book as soon as it came out, and very soon after Django hit > > 1.0. It's a good book, and I learned a few "big picture" ideas from > > the sample apps, but I really had to read the docs to figure out how > > to do the specifics. > > > If you're looking for the "big picture", grab it from a library or > > borrow it from a friend.. otherwise, wait for the next edition or just > > read the docs (which are very excellent, btw).- Hide quoted text - > > - Show quoted text - --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
best way to do tabs?
Hi, This is not a directly a django question, but since django is the only web framework I know (and it's really cool, by the way!) I hope it's ok to post this here. Could someone advise me on the "best" way to do tabs? IE, I'd like to have a set of tabs at the top of my page with a sub navigation bar below. I am currently using a mechanism that I got from the pinax project - I use css similar to that in tabs.css, for those of you that know pinax. That css controls how the html classes are set up when html is rendered for a particular tab, causing the tabs to look "pressed" at the appropriate times. I'm a newbie at web page design, so I don't have a good feeling for if this is the right direction to be pursing. I find the css code and the way it interacts with site_base.html and base.html fairly confusing and hard to maintain, so I'm wondering if there is a better way. Also (and more importantly) would like my tabs to be more dynamic. For example, based on the user clicking on something, I would like to be able to add additional tabs. It seems like using the css mechanism in pinax makes that very difficult, because the css for each tab has to be defined up front in order to get the shading right when you click on a tab. Can anyone advise me on what the best direction to go in is for having nice tabs that are easy to undrestand? I have not yet learned jquery or ajax, but they are on my list, perhaps those provide better frameworks than css? Anyway, any pointers from those of you more experienced than me are appreciated! Margie --~--~-~--~~~---~--~~ 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: best way to do tabs?
I think the issue I have is that I seem to need to maintain "state". Let me use a contrived example. Suppose I have three tabs: books-tab, music-tab, and video-tab. When I click on books-tab, I get a subnav bar with three subnav tabs: "books about animals", "books about video", "books about places". And similarly, when I click on music-tab I get 3 different subnav tabs: music-1, music-2, music-3. When I click on books-tab, I want books- tab to darken. When I then clock on "books about video", I want books- tab to stay dark and books about video" to also darken. It seems that when I use css, when I go to the "books about video" html page, I must "remember" to set a special id that makes books-tab darken. It seems that the html for "books about video" has to know it is being called on behalf of the books tab, which seems inflexible. For example, say I wanted to create a "books about video" under video-tab, the html for "books about video" needs to now set a different id in order to darken the video tab instead of the books tab. Basically, the html for "books about video" needs to know which tab it is being invoked by - this seems bad. I haven't had a chance to look at your links below in any detail, but do you think they address this? Does javascript or jquery or yui address this issue in a way that is significantly different from css? I know I have to start looking into those tools so I at least understand what they provide. And secondly, what about creating dynamic tabs? Ie, if the usr is going to click on something that ends up creating a new tab, how can css address this at all? I mean, in the css one needs to up front have knowledge of the ids that cause the tabs to darken. If each tab has its own id and you are creating them dynamically, it seems like the static nature of css just can't deal with this. On Jan 8, 8:29 am, "Ariel Mauricio Nunez Gomez" wrote: > Margie, I agree the current metod for adding new tabs in Pinax is kind of > cumbersome. > > I also think ther is no need for javascript for that kind of simle stuff > (i.e. This would be an > overkillhttp://blog.evaria.com/wp-content/themes/blogvaria/jquery/index-multi...) > Perhaps you may want to search for more 'css menu' examples, I think you can > getaway with just using two classes 'selected' and 'normal' > > Like this guys > do:http://www.3point7designs.com/blog/2007/12/22/advanced-css-menu-trick/http://www.3point7designs.com/keyword-optimization/michigan-seo.html > > > > > > > > > > title="Home Page">Home Page > > About Us > > Web Design > > Graphic Designs > > Search Engine > > Optimization SEO > > > title="Contact Us">Contact Us > > > > Ariel.- Hide quoted text - > > - Show quoted text - --~--~-~--~~~---~--~~ 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: best way to do tabs?
Yes, I agree, my main problem is figuring out how to avoid rewriting the css files. I will look at that link and the active class, that sounds like it's a good way to go. Thanks!! On Jan 8, 9:40 am, "Ariel Mauricio Nunez Gomez" wrote: > Since I think you are not (yet) using AJAX, all the logic you need should be > available to the template already. > Your main issue sems to be not having to rewrite any css files but only > change the html item 'class' attribute. The last link and code snippet on my > previous mail address that issue(Using an 'active' class on the selected > item, you can dynamically set it on your template). > > Take some time to play with it and let us know how it goes. > > Frameworks like jquery can also create and change css styles on the fly, > like I said I see it as an overkill for such a simple task, but it is your > bikeshed and you get to paint it any color you may want :) > > Ariel. > > > > On Thu, Jan 8, 2009 at 12:30 PM, Margie wrote: > > > I think the issue I have is that I seem to need to maintain "state". > > Let me use a contrived example. > > > Suppose I have three tabs: books-tab, music-tab, and video-tab. When > > I click on books-tab, I get a subnav bar with three subnav tabs: > > "books about animals", "books about video", "books about places". And > > similarly, when I click on music-tab I get 3 different subnav tabs: > > music-1, music-2, music-3. When I click on books-tab, I want books- > > tab to darken. When I then clock on "books about video", I want books- > > tab to stay dark and books about video" to also darken. It seems > > that when I use css, when I go to the "books about video" html page, I > > must "remember" to set a special id that makes books-tab darken. It > > seems that the html for "books about video" has to know it is being > > called on behalf of the books tab, which seems inflexible. For > > example, say I wanted to create a "books about video" under video-tab, > > the html for "books about video" needs to now set a different id in > > order to darken the video tab instead of the books tab. Basically, > > the html for "books about video" needs to know which tab it is being > > invoked by - this seems bad. > > > I haven't had a chance to look at your links below in any detail, but > > do you think they address this? Does javascript or jquery or yui > > address this issue in a way that is significantly different from css? > > I know I have to start looking into those tools so I at least > > understand what they provide. > > > And secondly, what about creating dynamic tabs? Ie, if the usr is > > going to click on something that ends up creating a new tab, how can > > css address this at all? I mean, in the css one needs to up front > > have knowledge of the ids that cause the tabs to darken. If each tab > > has its own id and you are creating them dynamically, it seems like > > the static nature of css just can't deal with this. > > > On Jan 8, 8:29 am, "Ariel Mauricio Nunez Gomez" > > wrote: > > > Margie, I agree the current metod for adding new tabs in Pinax is kind of > > > cumbersome. > > > > I also think ther is no need for javascript for that kind of simle stuff > > > (i.e. This would be an overkillhttp:// > > blog.evaria.com/wp-content/themes/blogvaria/jquery/index-multi...) > > > Perhaps you may want to search for more 'css menu' examples, I think you > > can > > > getaway with just using two classes 'selected' and 'normal' > > > > Like this guys do: > >http://www.3point7designs.com/blog/2007/12/22/advanced-css-menu-trick... > > > > > > > > > > > > title="Home Page">Home Page > > > > About Us > > > > > title="Web > > > > Design and Development">Web Design > > > > Graphic Designs > > > > Search Engine > > > > Optimization SEO > > > > > > > title="Contact Us">Contact Us > > > > > > > > Ariel.- Hide quoted text - > > > > - Show quoted text -- Hide quoted text - > > - Show quoted text - --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
how/where to constrain the relationships in a model?
Supose I want to model the following: A Task is owned by a family but may additionally have specific owners that are within that family. The model would look like this: class Family(models.Model): surName=models.CharField() class Task(models.Model): ownerFamily=models.ForeignKey(Family) owners = models.ManyToManyField(Person, blank=True, null=True) class Person(models.Model): family = models.ForeignKey(Family) I want to enforce that the if a Task has owners, that each owner be in the Family specified by that task's ownerFamily. Could someone tell me where is the appropriate location in the code to enforce this? I'm not sure if there is a way to enforce this within the model itself. If not, then is the appropriate thing to do to just check it in my public interface when I, for example, add an owner to a task? Thanks! Margie Margie --~--~-~--~~~---~--~~ 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/where to constrain the relationships in a model?
Thanks Ariel! That makes sense ... On Jan 14, 1:52 pm, Ariel Mauricio Nunez Gomez wrote: > Margie, > > My best bet would be to override the model's save method and do your > validation there. > > http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo... > > Ariel > > On Wed, Jan 14, 2009 at 3:37 PM, Margie wrote: > > > Supose I want to model the following: A Task is owned by a family but > > may additionally have specific owners that are within that family. > > The model would look like this: > > > class Family(models.Model): > > surName=models.CharField() > > > class Task(models.Model): > > ownerFamily=models.ForeignKey(Family) > > owners = models.ManyToManyField(Person, blank=True, null=True) > > > class Person(models.Model): > > family = models.ForeignKey(Family) > > > I want to enforce that the if a Task has owners, that each owner be in > > the Family specified by that task's ownerFamily. > > > Could someone tell me where is the appropriate location in the code to > > enforce this? I'm not sure if there is a way to enforce this within > > the model itself. If not, then is the appropriate thing to do to just > > check it in my public interface when I, for example, add an owner to a > > task? > > > Thanks! > > > Margie > > Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
trouble with yesno to generate images
Hi, I am trying to generate a symbol for true and false in my table, but am having problems with the escaping of quotes and also with generating the < > tags. If I use the code below: {{ task.done|yesno:"," }} it ends up generating this: < ends up being <, > ends up being > and my quotes become " Could someone give me an example of how to use yesno to generate an image? Margie an image? Margie --~--~-~--~~~---~--~~ 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: trouble with yesno to generate images
Thanks very much, autoescape did the trick, here is the result for anyone interested: {% autoescape off %} {{ task.done|yesno:"," }} {% endautoescape %} Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Debug output from template language?
Is there a way to generate debug output from the template language? Suppose I have something like this: {% for field in form %} {{ field.label_tag }}{{ field }} {% if field.help_text %} {{ field.help_text }}{% endif %} {% endfor %} Suppose I want to know what attributes are available for 'field'. Any way to introspect field from within the template language and get the output sent to either the stderr/stdout of the server or to a file? Margie --~--~-~--~~~---~--~~ 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: Debug output from template language?
Ah, right - of course. Thanks, Malcom. This is only slightly related, but perhaps you have a good answer. Are most people using the standard template language? I know there are some others out there (though I can't remeber the names offhand). As a python programmer I find using the template language to be somewhat unintuitive. Would like something more python-like. Of course, I know that it is good to keep code out of the html, so making it hard to use is perhaps a good thing. But is this the template language that python programmers use, or is there something that folks like better? Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
looking for patch to user.messages that adds a category
Hi, I was searching for a way to add a class to messages that are created via user.message_set.create(message="my message here"). I found a number of people discussing this and found what seems to be patch that does just what I want: http://code.djangoproject.com/attachment/ticket/3995/3995.django.contrib.auth.diff However, after downloading the django source via: svn co http://code.djangoproject.com/svn/django/trunk/ I don't see that patch in place. This is my first time getting source rather than using the release. How would I find out what the status of this is? Perhaps I am not really seeing top of trunk? svn info for models.py shows this: lslogin6 trunk/django/contrib/auth % svn info models.py Path: models.py Name: models.py URL: http://code.djangoproject.com/svn/django/trunk/django/contrib/auth/models.py Repository Root: http://code.djangoproject.com/svn Repository UUID: bcc190cf-cafb-0310-a4f2-bffc1f526a37 Revision: 9814 Node Kind: file Schedule: normal Last Changed Author: mtredinnick Last Changed Rev: 9160 Last Changed Date: 2008-10-05 22:14:17 -0700 (Sun, 05 Oct 2008) Text Last Updated: 2009-02-06 12:33:42 -0800 (Fri, 06 Feb 2009) Checksum: a285c8cfc374d7cc53e163ff4d63b4c0 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-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: looking for patch to user.messages that adds a category
Thanks very much, Karen. That makes perfect sense. Well, it was at least a good excercise in learning how easy it is to download the source from the svn repository! Margie On Feb 6, 1:37 pm, Karen Tracey wrote: > On Fri, Feb 6, 2009 at 3:54 PM, Margie wrote: > > > Hi, > > > I was searching for a way to add a class to messages that are created > > via user.message_set.create(message="my message here"). I found a > > number of people discussing this and found what seems to be patch that > > does just what I want: > > >http://code.djangoproject.com/attachment/ticket/3995/3995.django.cont... > > > However, after downloading the django source via: > > > svn cohttp://code.djangoproject.com/svn/django/trunk/ > > > I don't see that patch in place. This is my first time getting source > > rather than using the release. How would I find out what the status > > of this is? Perhaps I am not really seeing top of trunk? > > The status is in the ticket: > > http://code.djangoproject.com/ticket/3995 > > Up near the top it says (new) not (fixed) so it's still an open ticket, and > no fix has been put into the codebase for this yet. > > When the code in svn is updated to include a fix, the status will be changed > to fixed, and there will be a comment added that notes what changeset made > the fix. Something like this: > > http://code.djangoproject.com/ticket/10187#comment:3 > > Only after you see something like that in your ticket of interest would > pulling the latest SVN trunk code get you a version with the fix already > integrated. > > If you want to run with the patch currently on the ticket, you'll need to > apply it to your checked-out copy of the source tree, using the patch > command. However, I'd be a bit cautious about applying that particular > patch. > > First, it is fairly old so unlikely to apply cleanly (patch can handle some > amount of code movement due to the base tree changing over time, but that > patch is over a year old and given how much the Django code base has changed > since Dec. 2007 I'd be surprised if that patch applies cleanly). > > Second, that patch adds a column to one of the auth tables, so is going to > cause problems if you try to use it with a pre-existing (already ran syncdb) > installation that doesn't have that new column. If you're intending to use > the patch only with new installs, or know how to manually update your > existing auth table to add the new column, then you're OK, but running that > code on an existing Django project without fixing up the existing auth table > is going to result in errors. > > [Side note: This need to add a column to an existing auth table is likely > one reason why this ticket has not been integrated. As Jacob notes in one > of the comments in the ticket, a transition plan is needed to handle > upgrading existing tables, and I don't see that that was addressed at all.] > > 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 -~--~~~~--~~--~--~---
Re: looking for patch to user.messages that adds a category
Very cool - thanks so much for giving me thsi pointer, Ramiro. I followed the snippet info and it's working great. Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
including non-editable fields in forms?
I have a model that contains a 'created' field where 'editable' is set to False in the model. I'd like to display the created field in my form, but not allow it to be modified. I tried putting it in the include list for the form, but that didn't seem to have any affect (it didn't display in the form). Is there a way to do this in a form or do I need to simply put the created field into my template separate from the display of the form? Margie --~--~-~--~~~---~--~~ 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: including non-editable fields in forms?
Thanks Malcolm. I think inserting it directly in the form template will work fine for my purposes. Margie On Feb 9, 9:18 pm, Malcolm Tredinnick wrote: > On Mon, 2009-02-09 at 21:14 -0800,Margiewrote: > > I have a model that contains a 'created' field where 'editable' is set > > to False in the model. > > > I'd like to display the created field in my form, but not allow it to > > be modified. I tried putting it in > > the include list for the form, but that didn't seem to have any affect > > (it didn't display in the form). > > > Is there a way to do this in a form or do I need to simply put the > > created field into my template separate from the display of the form? > > You could create a form Field subclass that only displays the data and > never validates it or inserts it into cleaned_data for the form. In > other words, a kind of read-only for field. There are a few details that > would have to be sorted out, but it sounds eminently possible if you > were going to do this a lot. One day we'll eventually add support for > read-only items in the admin and we'll have to invent something like > that for those, I suspect. > > On the other hand, I've always just inserted it directly into the form > template when I've had this kind of situation. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
can template var be passed into template tag?
Is there a way to pass a template variable into a custom template tag? For example, say that my template is rendered like this, so that books is in the context: books = books.objects.all() return render_to_response(template.html, { "books":books } context_instance=RequestContext(request) Now say inside my template I want to do something like this: {% for book in books %} {% getBookInfo book %} {% endfor %} The idea being that getBookInfo is going to return some html that describes the book. However, I find that the book variable is not expanded. So when I get into my getBookInfo custom template tag, the first argument it gets is just the literal 'book', rather than the book object created by iterating through books. This seems like a reasonable thing to want to do - am I approaching it the wrong way somehow? Margie --~--~-~--~~~---~--~~ 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: can template var be passed into template tag?
Thanks Karen. Don't know how I missed that. On Feb 18, 11:49 am, Karen Tracey wrote: > On Wed, Feb 18, 2009 at 2:35 PM, Margie wrote: > > > Is there a way to pass a template variable into a custom template > > tag? > > Certainly. Please read: > > http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#pass... > > 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 -~--~~~~--~~--~--~---
Re: Conditional Logic in Template Loop
My experience is that using the the various conditional templatetags is painful. I can never seem to do what I want, either because I'm too much of a newbie or there is some gotcha such as "filters don't work inside if" (I seem to remember something like that, but again, it might just be my own problem) I've come to the conclusion that it is easier to use a template tag. That way I can just do my thing with a little bit of python that I completely understand, and I don't have to constantly be looking up what I can do with the template language. I find the template tags where you define the tag and the renderer to also be very useful, as these give you access to the context. Margie On Feb 22, 7:13 pm, Chris wrote: > I'm displaying a list of records in a template. I want to > conditionally display controls for each record if the current user is > admin, or the user owns the given record (indicated by record.user == > request.user). > > What's the best way to do this? Logically, all I want to do is {% if > request.user.is_superuser or request.user == record.user %} display > controls {% endif %} inside the loop. However, Django's default > template language doesn't seem to support this basic syntax. Is there > a non-hackish way to accomplish this with the default language? > > Regards, > Chris --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
'tuple' object has no attribute 'has_header'
Anyone know what might be causing this error? It occurs when I fill in one of my forms (ie, from the use interface). I seem to never even get to the view.py function that processes the POST. Traceback (most recent call last): File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- packages/django/core/servers/basehttp.py", line 277, in run self.result = application(self.environ, self.start_response) File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- packages/django/core/servers/basehttp.py", line 634, in __call__ return self.application(environ, start_response) File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- packages/django/core/handlers/wsgi.py", line 243, in __call__ response = middleware_method(request, response) File "/home/mlevine/django/chipvision7/chip_vision/apps/account/ middleware.py", line 28, in process_response patch_vary_headers(response, ('Accept-Language',)) File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- packages/django/utils/cache.py", line 129, in patch_vary_headers if response.has_header('Vary'): AttributeError: 'tuple' object has no attribute 'has_header' I believe my code is in the same state it was when it was working a while back. I did some cleanup - removing img and .js files that weren't in use. I've tried to put all that stuff back, but no luck and this message isn't very informative .. Anyway, any hints appreciated. margie --~--~-~--~~~---~--~~ 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: 'tuple' object has no attribute 'has_header'
You are awesome, Alex. That was exactly it. Many thanks! Margie On Feb 22, 9:08 pm, Alex Gaynor wrote: > On Mon, Feb 23, 2009 at 12:05 AM, Margie wrote: > > > Anyone know what might be causing this error? It occurs when I fill > > in one of my forms (ie, from the use interface). I seem to never even > > get to the view.py function that processes the POST. > > > Traceback (most recent call last): > > File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- > > packages/django/core/servers/basehttp.py", line 277, in run > > self.result = application(self.environ, self.start_response) > > File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- > > packages/django/core/servers/basehttp.py", line 634, in __call__ > > return self.application(environ, start_response) > > File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- > > packages/django/core/handlers/wsgi.py", line 243, in __call__ > > response = middleware_method(request, response) > > File "/home/mlevine/django/chipvision7/chip_vision/apps/account/ > > middleware.py", line 28, in process_response > > patch_vary_headers(response, ('Accept-Language',)) > > File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- > > packages/django/utils/cache.py", line 129, in patch_vary_headers > > if response.has_header('Vary'): > > AttributeError: 'tuple' object has no attribute 'has_header' > > > I believe my code is in the same state it was when it was working a > > while back. I did some cleanup - removing img and .js files that > > weren't in use. I've tried to put all that stuff back, but no luck > > and this message isn't very informative .. > > > Anyway, any hints appreciated. > > > margie > > > You're view is returning a tuple insteaed of an HttpResponse object > > somewhere. > > Alex > > -- > "I disapprove of what you say, but I will defend to the death your right to > say it." --Voltaire > "The people's good is the highest law."--Cicero --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
how to show currently selected choices in ManyToMany fo
Let's say I have a model like this: class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) pulisher = models.ForeignKey(Publisher, blank=True, null=True) I want to generate a form that can be used to edit an existing Book object. In particular, I want the authors field to show up in the form as showing all of the possible authors and I want it to be initialized such that it shows the currently selected authors. I am able to initialize it so that it shows the possible selections, ie: class BookForm(models.Model): def __init__(self, myQueryset, *args, **kwargs): self.fields['authors'].queryset = myQuerySet But I can't figure out how to get the form to reflect the currently selected authors. Can anyone give me a pointer? Thanks, Margie I know how to set the initial --~--~-~--~~~---~--~~ 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 show currently selected choices in ManyToMany fo
Ok - I think I should actually be using initial - but still haven't gotten that to actually work. I'm trying something like this: In models.py class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) pulisher = models.ForeignKey(Publisher, blank=True, null=True) In forms.py class BookForm(forms.modelForm): def __init__(self, myQueryset, *args, **kwargs): self.fields['authors'].queryset = myQuerySet in views.py: bookObj = ... some prexisting book object authorChoices=Author.objects.filter(somefilter) bookForm = BookForm(authorChoices, initial={'authors':bookObj.authors} Should this work? Margie --~--~-~--~~~---~--~~ 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 show currently selected choices in ManyToMany fo
I think I'm going to try to come up with a more exact example of what I'm doing. I spent all last evening on this - could just not get the initial values set on my ModelMultipleChoiceForm. I guess I'll have to back up and start using a manage.py shell and pdb and step thrrough the django code to figure out what is going on. Sigh. On Feb 24, 1:05 am, Daniel Roseman wrote: > On Feb 24, 5:09 am, Margie wrote: > > > > > Ok - I think I should actually be using initial - but still haven't > > gotten that to actually work. I'm trying something like this: > > > In models.py > > class Book(models.Model): > > title = models.CharField(max_length=100) > > authors = models.ManyToManyField(Author) > > pulisher = models.ForeignKey(Publisher, blank=True, null=True) > > > In forms.py > > class BookForm(forms.modelForm): > > def __init__(self, myQueryset, *args, **kwargs): > > self.fields['authors'].queryset = myQuerySet > > > in views.py: > > > bookObj = ... some prexisting book object > > authorChoices=Author.objects.filter(somefilter) > > bookForm = BookForm(authorChoices, initial={'authors':bookObj.authors} > > > Should this work? > > > Margie > > Maybe (although there are some issues with the order of the arguments > in your __init__), but it's unnecessary. if you're using a ModelForm > to edit an existing instance, you should pass it in when you > instantiate the form. > > bookObj = whatever > bookForm = BookForm(instance=bookObj) > > And that way, when you save the form, it will save the changes to the > instance, rather than creating a new one. > -- > 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 -~--~~~~--~~--~--~---
avoiding a save when the form contains no new data
Say I create a form that reflects the current state of an object. The user can edit that form, and when they click 'save', I get back the new, possibly edited, values via the POST. In my POST code I do something like this: postDict = request.POST.copy() bookForm = BookForm(postDict, instance=bookObj) if bookForm.is_valid() bookForm.save() What do folks typically do to avoid saving the data if nothing has been modified in the form? Is there any django functionality for doing this, or do I just write the manual check that compares the fields in the form to the fields in the existing object? I'm not only concerned with the database access. In addition to avoiding the save, I'd like to emit a message to the user that reflects what they've done, or not done. IE, "book foo updated' or "book foo unchanged". Anyway, just curious if others have encountered this. Margie --~--~-~--~~~---~--~~ 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: avoiding a save when the form contains no new data
Hi Alex, Thanks for your reply. Yes, I had found and experimented with both has_changed() and changed_data(), but I found that they don't deal as I'd like with my case where my form contains fields that are not in the model. IE, using the Book example, if I have model Book(models.Model): name = models.CharField() model Author(models.Model) books = models.ManyToManyField(Book) If I create a BookForm that is like this, that allows the user to put in the authors: class BookForm(forms.ModelForm) authors = forms.CharField(widget=forms.Textarea, help_text="space separated list of authors") class Meta: model=Book I find that changed_data() always returns 'authors' and has_changed is always True. I will take a look at the source a bit more. Margie On Feb 25, 4:59 pm, Alex Gaynor wrote: > On Wed, Feb 25, 2009 at 7:55 PM, Margie wrote: > > > Say I create a form that reflects the current state of an object. The > > user can edit that form, and when they click 'save', I get back the > > new, possibly edited, values via the POST. In my POST code I do > > something like this: > > > postDict = request.POST.copy() > > bookForm = BookForm(postDict, instance=bookObj) > > if bookForm.is_valid() > > bookForm.save() > > > What do folks typically do to avoid saving the data if nothing has > > been modified in the form? Is there any django functionality for > > doing this, or do I just write the manual check that compares the > > fields in the form to the fields in the existing object? > > > I'm not only concerned with the database access. In addition to > > avoiding the save, I'd like to emit a message to the user that > > reflects what they've done, or not done. IE, "book foo updated' or > > "book foo unchanged". > > > Anyway, just curious if others have encountered this. > > > Margie > > > Form's have a method "has_changed" which says whether or not there is > > changed data, this should do just what you expect. > > Alex > > -- > "I disapprove of what you say, but I will defend to the death your right to > say it." --Voltaire > "The people's good is the highest law."--Cicero --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
purpose of formset hidden 'id' fields
I am using model formsets and seeing a hidden field get printed for the 'id' field. This is different than what I see if I use the same modelForm and just print that form. Let me use an example to clarify. Here's the model and form classes: class Publication(models.Model): title = models.CharField(max_length=30) class PublicationForm(forms.ModelForm): class Meta: model = Publication If I do this: p1 = Publication() publicationForm = PublicationForm(instance=p1) for field in publicationForm: print "FORM FIELD: ", field It prints the following: FORM FIELD: If I then do this: PublicationFormSet = modelformset_factory(Publication, form = PublicationForm) publicationFormSet = PublicationFormSet() for field in publicationFormSet.forms[0]: print "FORMSET FIELD: ", field It prints this FORMSET FIELD: FORMSET FIELD: Can anyone tell me what this hidden form-0-id field in the second "FORMSET" line is? Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
formset of ModelForms missing functionality?
I'm using formsets fairly successfully (thanks very much to Malcolm's great quiz example), but it seems to me there is some functionality missing.Say I create a formset of BookForms, where BookForm is a ModelForm. The user will filleout the formset and for each form in the formset, when I receive the POST data I will create an instance of a Book based on that data. I can't use a modelform_factory because when I create the formset, I don't have any book objects yet (which I would need to set the queryset for the modelform_factory). So instead I use a formset_factory that references a BookForm that is derived from a ModelForm. However, when I use a formset_factory, I don't have a nice way to save the forms in my formset as new book objects. For example, when I use just a ModelForm, I can do bookForm = BookForm(postDict) newBookObj = bookForm.save() When I use the formset, I can loop through the forms in the formset, but then I think I have to create the book objects myself. for form in bookFormSet.forms: newBookObj = Book(title=form.cleaned_data['title']) If I add fields to my book model, I would have to now rememeber to copy them inside this loop. Have I missed something? Margie --~--~-~--~~~---~--~~ 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: formset of ModelForms missing functionality?
My model does have multiple fields in it - the Book thing was just an example to simplify. And I do have fields that I need to exclude. Am I not able to exclude fields with the modelformset_factory? You reminded me that I could instead just set extra and use initial if necessary. However, I do need the exclude capability, so that might still be a problem if modelformset_factory does not support that. I can post some code later when I get things a big more cleaned up. Margie On Mar 3, 8:37 pm, Malcolm Tredinnick wrote: > On Tue, 2009-03-03 at 20:21 -0800, Margie wrote: > > I'm using formsets fairly successfully (thanks very much to Malcolm's > > great quiz example), but it seems to me there is some functionality > > missing. Say I create a formset of BookForms, where BookForm is a > > ModelForm. The user will filleout the formset and for each form in > > the formset, when I receive the POST data I will create an instance of > > a Book based on that data. > > > I can't use a modelform_factory because when I create the formset, I > > don't have any book objects yet (which I would need to set the > > queryset for the modelform_factory). > > Can you provide some short code fragments? There's a lot of Modelform > and Modelformsets floating around here and it's not clear whether some > of them are typos or what's going on. > > In particular, it's not clear to me why you can't do > > BookFormset = modelformset_factory(models.Book, extra=5) > > or, if you have a more complex form and also wanted to, say, exclude the > "author" field: > > BookFormset = modelformset_factory(models.Book, > my_forms.BookForm, > extra=5, exclude=["author"]) > > There's nothing in the code behind that which *requires* any books to > exist. > > In fact, you might even want to construct a ModelFormset subclass that > prevents any existing books from being selected as part of that, if you > only want new books to be entered. > > > So instead I use a > > formset_factory that references a BookForm that is derived from a > > ModelForm. However, when I use a formset_factory, I don't have a nice > > way to save the forms in my formset as new book objects. For example, > > when I use just a ModelForm, I can do > > > bookForm = BookForm(postDict) > > newBookObj = bookForm.save() > > > When I use the formset, I can loop through the forms in the formset, > > but then I think I have to create the book objects myself. > > > for form in bookFormSet.forms: > > newBookObj = Book(title=form.cleaned_data['title']) > > Yes, if you're not using anything tied to the model, you'll need to > create them yourself. Since it's only one line of code in this > particular case, it's not really that bad, though, surely. > > But it would be interesting to get some more details about why you > cannot use model formsets directly. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: formset of ModelForms missing functionality?
Yeah, I need to go back and review. I think my original problem was that I just didn't think about using extra to define the intial forms - I was thinking I needed a queryset. Your first resonse addressed that. But then you mentioned something about exclude and that made me think that maybe I couldn't use it. Of course I can. Anyway, I need to see if I can get myself back to a steady working state and then am going to revisit using the modelformset_factory. Thanks for the pointers. Margie On Mar 3, 10:24 pm, Malcolm Tredinnick wrote: > On Wed, 2009-03-04 at 16:49 +1100, Malcolm Tredinnick wrote: > > On Tue, 2009-03-03 at 21:44 -0800, Margie wrote: > > > > My model does have multiple fields in it - the Book thing was just an > > > example to simplify. And I do have fields that I need to exclude. Am > > > I not able to exclude fields with the modelformset_factory? > > > The example code I have showed fields being excluded. > > Gargh. Important typo: that should have said "the example code I have > *posted*", in my previous post. > > Also, the documentation for model forms shows, similarly, how to exclude > fields ([1]). So I don't understand your question. > > [1]http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#control... > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
formset initialization question
Hi Malcolm - Sorry, another formset question. Maybe you'll know the answer offhand, have been trying to figure this out for awhile now. I'm trying to set the initial value for a form field inside the constructor for the form. The high level goal is to send out the 'tile' field as a hidden input so that I can get it back in the POST so that I can figure out wich 'tile' each form in the forset corresonds to. For example, I'm trying to do this in my form constructor (specifically see the ==> line) class TaskTileDetailForm(forms.ModelForm): class Meta: model=TaskTileDetail exclude=('task') def __init__(self, tile, *args, **kwargs): super(TaskTileDetailForm, self).__init__(*args, **kwargs) self.fields['tile'].widget = forms.HiddenInput() ==> self.fields['tile'].initial = tile.id If I do this, then later when processing my POST data there is no 'tile' key in cleaned_data. IE, I get a KeyError when I do this: if taskTileDetailForm.cleaned_data["tile"] in taskTiles: If I intiaizize it with the initial arg when creating the formset, the cleaned_data["tile"] key is set just fine, ie when I use initial as shown at the ==> below: def makeTaskTileDetailFormSetForCreate(tileList, data=None): TaskTileDetailFormSet = formset_factory (form=TaskTileDetailForm, formset=CustomBaseFormSe) initial = [] for tile in tileList: initial.append({'tile': tile.id}) ==> taskTileDetailFormSet = TaskTileDetailFormSet(data, tiles=tileList, initial=initial) return taskTileDetailFormSet Is there something I am doing wrong when trying to initialize it as shown in the first snippet with: ==> self.fields['tile'].initial = tile.id that is causing cleaned_data to not get set when taskTileDetailFormSet.is_valid() is called? Sorry, I know this is hazy - have just been pulling my hair out forever now ... Margie --~--~-~--~~~---~--~~ 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: formset initialization question
Yes, I am defining _construct_form() as you do. I had just not thought to set initial there - but that makes sense. For reference, here is my current code, with it setting initial in _construct_form. But you may want to read on below before bothering to look at it because I have a theory about why cleaned_data is not getting set. class TaskTileDetailCustomBaseFormSetForCreate(BaseFormSet): def __init__(self, *args, **kwargs): self.tiles = list(kwargs.pop("tiles")) self.extra = len(self.tiles) super(TaskTileDetailCustomBaseFormSetForCreate, self).__init__ (*args, **kwargs) def _construct_form(self, i, **kwargs): kwargs["tile"] = self.tiles[i] kwargs["initial"] = {'tile':self.tiles[i].id} return super(TaskTileDetailCustomBaseFormSetForCreate, self)._construct_form(i, **kwargs) def makeTaskTileDetailFormSetForCreate(tileList, data=None): TaskTileDetailFormSet = formset_factory(form=TaskTileDetailForm, formset=TaskTileDetailCustomBaseFormSetForCreate) taskTileDetailFormSet = TaskTileDetailFormSet(data, tiles=tileList) return taskTileDetailFormSet After debugging into the source some more, I'm finding that my the problem is related to the fact that empty_permitted is getting set to True when all of my forms are considered "extra. Specifically, in site- packages/django/forms/forms.py, in the full_clean() function, I find that when empty_permitted is set to True, this code executes, which drops me out of the code without setting cleaned_data at all: # If the form is permitted to be empty, and none of the form data has # changed from the initial data, short circuit any validation. if self.empty_permitted and not self.has_changed(): return It seems to me that if I pass in initial when I create the TaskTileDetailFormSet, ie, like this: initial = [] for tile in tileList: initial.append({'tile': tile.id}) taskTileDetailFormSet = TaskTileDetailFormSet(data, tiles=tileList, initial=initial) then empty_permitted gets set to False ibecause my initial_form_count is non-zero. IE, in site-packages/django/forms/formsets.py, in _construct_form(), in thh code that looks like this: # Allow extra forms to be empty. if i >= self._initial_form_count: defaults['empty_permitted'] = True But if I pass initial in via my own _construct_form() function as you suggested, then I have no initial data, so all of my forms are "extra". IN this case self._initial_form_count is 0, and it seems that the result is that cleaned_data doesn't get set correctly. I am probably far from undrestanding this, but if what I said is atually true, it seems like this is actually a bug? The bug being that cleaned_data is not getting set correctly when the forms are created as "extra" forms. Perhaps cleaned_data is not supposed to get set in this case? The whole reason that I happened upon this is beacuse I am trying to identify which form is which, so I was looking at cleaned_data['tile']. I set that myself anyway, so I can just look at data['tile']. However, it seems that none of my post data is getting put in cleaned_data, so that still seems like a general problem. Margie On Mar 3, 11:17 pm, Malcolm Tredinnick wrote: > On Tue, 2009-03-03 at 22:42 -0800, Margie wrote: > > Hi Malcolm - Sorry, another formset question. Maybe you'll know the > > answer offhand, have been trying to figure this out for awhile now. > > I'm trying to set the initial value for a form field inside the > > constructor for the form. The high level goal is to send out the > > 'tile' field as a hidden input so that I can get it back in the POST > > so that I can figure out wich 'tile' each form in the forset > > corresonds to. > > > For example, I'm trying to do this in my form constructor > > (specifically see the ==> line) > > > class TaskTileDetailForm(forms.ModelForm): > > class Meta: > > model=TaskTileDetail > > exclude=('task') > > If this is a cut-and-paste, this line is almost certainly a bug. The > "exclude" parameter should be a tuple or a list, so ("task",) or > ["task"] (note the trailing comma in the tuple case). > > > > > def __init__(self, tile, *args, **kwargs): > > This line is a probably going to be a problem at some point. You cannot > just add new positional arguments into the front of the __init__ call > like this. When Django calls the constructor, it could well be passing > the "data" parameter as the first argument. > > Instead, pass it in as a keyword argument. To wit: > > def __init__(self, *args, **kw
Re: formset of ModelForms missing functionality?
Hi Malcolm. So after reviewing your pointers, I had high hopes of being able to move to using the modelformset_factory, but I still seem to have problems. The problem I run into is that when _construct_form (the one in django/forms/models.py) is called, it tries to do this: if i < self._initial_form_count: kwargs['instance'] = self.get_queryset()[i] I have no objects of my model yet and get_queryset() returns self._queryset, which is []. The above [i] index then causes a 'list index out of range exception'. I think this was what I first encountered which made me think that I had to have a queryset to use modelformset_factory. I cleaned up other things that you mentioned in your other posts - thanks much for those pointers. I've put my current code at http://dpaste.com/6281/ Note that when I instantiate the formset: taskTileDetailFormSet = TaskTileDetailFormSet(data=data, tiles=tileList, initial= [{"tile":tile.id} for tile in tileList] I am creating an initial entry for each form that I want created. Inside __init__ for TaskDetailCustomBaseFormSetForCreate I thus set self.extra to 0. My understanding is that I don't need any "extras" in this case because I am using initial to specify all of the forms that I want. (Setting extra to a larger number had no effect on the list index error - am just mentioning this for clarity) Anyway, I must be doing something dumb... sigh. The modelformset_factory works fine for me in another case query I have an existing set of model instances - just can't get it to work in this case where I don't yet have the model instances. Thanks for any pointers. Margie On Mar 3, 10:54 pm, Margie wrote: > Yeah, I need to go back and review. I think my original problem was > that I just didn't think about using extra to define the intial forms > - I was thinking I needed a queryset. Your first resonse addressed > that. But then you mentioned something about exclude and that made me > think that maybe I couldn't use it. Of course I can. > > Anyway, I need to see if I can get myself back to a steady working > state and then am going to revisit using the modelformset_factory. > Thanks for the pointers. > > Margie > > On Mar 3, 10:24 pm, Malcolm Tredinnick > wrote: > > > On Wed, 2009-03-04 at 16:49 +1100, Malcolm Tredinnick wrote: > > > On Tue, 2009-03-03 at 21:44 -0800,Margiewrote: > > > > > My model does have multiple fields in it - the Book thing was just an > > > > example to simplify. And I do have fields that I need to exclude. Am > > > > I not able to exclude fields with the modelformset_factory? > > > > The example code I have showed fields being excluded. > > > Gargh. Important typo: that should have said "the example code I have > > *posted*", in my previous post. > > > Also, the documentation for model forms shows, similarly, how to exclude > > fields ([1]). So I don't understand your question. > > > [1]http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#control... > > > Regards, > > Malcolm --~--~-~--~~~---~--~~ 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: formset of ModelForms missing functionality?
Yes, I agree with what you are saying about self._initial_form_count being set to a number greater than zero due to me using initial in my code that creates the formset, as follows: def makeTaskDetailFormSetForCreate(tileList, data=None): TaskDetailFormSet = modelformset_factory(TaskDetail, form=TaskDetailForm, formset=TaskDetailCustomBaseFormSetForCreate) taskDetailFormSet = TaskDetailFormSet(data=data, tiles=tileList, initial=[{"tile":tile.id} for tile in tileList]) return taskDetailFormSet But if I don't use initial - how do I create the initial values for the forms? I thought using initial is the "right" way to do it? And of course, as I described in the formset initialization thread, when I don't use initial and I instead try setting it in the init for the form, like this: class TaskDetailForm(forms.ModelForm): class Meta: model=TaskDetail exclude=('task') def __init__(self, tile, *args, **kwargs): super(TaskDetailForm, self).__init__(*args, **kwargs) self.fields['tile'].initial = tile.id I seem to have a different set of problems related to cleaned_data not getting set correctly. I guess these two threads are converging - I'll look for your response there. By the way, you may have noticed that in some cases my code has TaskTileDetail while in others it is TaskDetail. I tried shortening the name for the purpose of the posting, and ended up missing some when I did the cut and paste, sorry for any added confusion from that. Margie On Mar 4, 6:09 pm, Malcolm Tredinnick wrote: > On Wed, 2009-03-04 at 11:44 -0800, Margie wrote: > > Hi Malcolm. So after reviewing your pointers, I had high hopes of > > being able to move to using the modelformset_factory, but I still seem > > to have problems. The problem I run into is that when _construct_form > > (the one in django/forms/models.py) is called, it tries to do this: > > > if i < self._initial_form_count: > > kwargs['instance'] = self.get_queryset()[i] > > > I have no objects of my model yet and get_queryset() returns > > self._queryset, which is []. The above [i] index then causes a 'list > > index out of range exception'. I think this was what I first > > encountered which made me think that I had to have a queryset to use > > modelformset_factory. > > That second line of code will only be executed if > self._initial_form_count is greater than 0. You aren't providing any > initial forms, so it should be zero. > > Looking at the source (it's set in the BaseFormset.__init__ method), it > will only be non-zero if you supply initial data, which kind of makes > sense, since providing initial data for "extra" forms would mean you'd > always end up creating a new record every time you viewed and submitted > that form. I can see why it's set up that way, although it confirms my > wish to spend a couple of days going over the formsets documentation > with a two-by-four. > > I think it means that supplying this tile id via initial data is > probably not a great idea, as it will inadvertently create new records > own the track. I'd kind of been thinking that approach might have been a > little clunky, anyway, so this backs up that hunch. I'll put some more > details in the formset initialization thread, because it's probably more > appropriate there. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: formset of ModelForms missing functionality?
Ok - gotcha. Yes, I think I've come full circle now! At the time I started this thread I had moved away from the modelFormSet and back to teh regular formset. Using the regular formset and my own logic I can identify which forms go with actual instances and which require instances to be created. So that does work. I just somehow got bound and determined to make the modelFormSets work - but I think that's not meant to be. I do think that a nice model would be to allow initial data and querysets to work together in the modelFormSet. For example, suppose you had a queryset containing 5 items and you wanted 8 forms, with the first 5 mimicing the existing 5 instances and the last 3 being created from initial data. It seems like a nice intuitive user interface would be to create initial data for all 8 instances, possibly with the first 5 being empty dicts, and the last 3 containing your initial data. In other words, in order to provide your initial data for the last 3, you would have to provide initial data for all, so you wold just provide "empty" intiial data. Then the next step would for the modelformset to be able identify that when you save each of the forms, that the first 5 save to the existing 5 instances provided in the queryset and that the last 3 save to new instances. Obviously a big source change, just throwing it out there in case there s work in this area in the future. Anyway, thanks for all the clarification. I definitely learned a lot in the process of debugging this all and I think I know enough to be able to work this out using the standard formsets. Margie On Mar 4, 8:15 pm, Malcolm Tredinnick wrote: > On Wed, 2009-03-04 at 19:47 -0800, Margie wrote: > > Yes, I agree with what you are saying about self._initial_form_count > > being set to a number greater than zero due to me using initial in my > > code that creates the formset, as follows: > > > def makeTaskDetailFormSetForCreate(tileList, data=None): > > TaskDetailFormSet = modelformset_factory(TaskDetail, > > form=TaskDetailForm, > > > formset=TaskDetailCustomBaseFormSetForCreate) > > > taskDetailFormSet = TaskDetailFormSet(data=data, > > tiles=tileList, > > initial=[{"tile":tile.id} > > for tile in tileList]) > > > return taskDetailFormSet > > > But if I don't use initial - how do I create the initial values for > > the forms? I thought using initial is the "right" way to do it? > > I mentioned before that initial data doesn't necessarily make sense for > new models in a modelformset, in some ways (in other ways it does -- but > it's not really practical to handle every single possibility, so > sometimes you just have to deal with it). The thing is that initial data > always results in a populated form -- so data is submitted and a new > entry will be created. That doesn't work for "extra" forms, in the > formset sense, where you're only going to enter new data and, if you > don't, they won't have any effect on things. > > If you really, really want to prepopulate fields and can also have some > way to work out whether the data is "new" or the "initial" stuff, then > you'll be able to use it, but you'll have to do some of the form > handling yourself. Reading the source and thinking very hard about > things is the solution to that problem. I'm sure it's possible, but it > will take some thinking. At some point, you just have to say it's not a > standard modelformset case and let go of that particular aid. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: formset initialization question
Here's a "book" analogy to what I am doing. I am sending out a bunch of forms to the user. Each form contains the title of a book (my "tile") and an input field where the user is being asked to input the author of the book. When the view.py code receives the post data, for each form where the user has input the author, the view.py code will create a book object with the title from the form and the author that the user input. So when I get an author, I need to identify which title it goes with. When I was writing the code I felt uncertain about identifying which title the form was for based on index. I thought that would work, but it seemed somehow safer to simply have it encoded in the same form. That way I don't have to match up indexes - instead I just ask the form what the title is. So that's why I sent the title as a hidden input. The reason that has_changed() was false was simply that in my debugging, on the client side I was not filling out the form. I was just leaving it blank. Then in view.py I was looking at the form to verify that I could get back the book title, and that's when I encountered the fact that cleaned_data was empty. What can I say ... I've been trying a lot of different things to really get a handle on this and it's taken me down a lot of strange paths. I'm sure that you are right that I can identify the "book" based on its index in the formset. Once again, thanks for your insights. Margie On Mar 4, 8:42 pm, Malcolm Tredinnick wrote: > On Wed, 2009-03-04 at 00:28 -0800,Margiewrote: > > [...] > > > After debugging into the source some more, I'm finding that my the > > problem is related to the fact that empty_permitted is getting set to > > True when all of my forms are considered "extra. > > Which is reasonable. "Extra" here means "optional". > > > Specifically, in site- > > packages/django/forms/forms.py, in the full_clean() function, I find > > that when empty_permitted is set to True, this code executes, which > > drops me out of the code without setting cleaned_data at all: > > > # If the form is permitted to be empty, and none of the form > > data has > > # changed from the initial data, short circuit any validation. > > if self.empty_permitted and not self.has_changed(): > > return > > This will only happen if none of the data has changed. That's the point > of the call to has_changed(). > > > > > It seems to me that if I pass in initial when I create the > > TaskTileDetailFormSet, ie, like this: > > > initial = [] > > for tile in tileList: > > initial.append({'tile': tile.id}) > > > taskTileDetailFormSet = TaskTileDetailFormSet(data, > > tiles=tileList, initial=initial) > > > then empty_permitted gets set to False ibecause my initial_form_count > > is non-zero. IE, in site-packages/django/forms/formsets.py, in > > _construct_form(), in thh code that looks like this: > > > # Allow extra forms to be empty. > > if i >= self._initial_form_count: > > defaults['empty_permitted'] = True > > > But if I pass initial in via my own _construct_form() function as you > > suggested, then I have no initial data, so all of my forms are > > "extra". IN this case self._initial_form_count is 0, and it seems > > that the result is that cleaned_data doesn't get set correctly. > > That would only be the case if none of the data for the form has > changed. If you've changed something on the form (from the initial > data's perspective), has_changed() should be returning True. > > > > > I am probably far from undrestanding this, but if what I said is > > atually true, it seems like this is actually a bug? The bug being > > that cleaned_data is not getting set correctly when the forms are > > created as "extra" forms. Perhaps cleaned_data is not supposed to get > > set in this case? > > Formsets are not entirely broken. Let's not think of zebras in > preference to horses when we hear the hoof-beats. If formsets and empty > forms didn't work, the entire admin application would be broken in > interesting ways, for example. > > You've found the right pieces of code, but you aren't examining why they > are falling through to skipping validation. The conditional test is > important. Why isn't has_changed() returning True for your particular > setup? Do you have to also subclass that based on the data changes > you're making, perhaps? > > > The whole reason that I happened upon this is > > beac
Re: formset initialization question
app, the user is creating tasks. They put in a description of the task and each task has 1 or more results, one per "tile". Associated with each tile is an optional set of "special instructions", and a location for the tile owner to input their result. When creating the task, I create the formset to give the user a way to identify which tiles are associated with the task. When the user creates the task, they need to choose which tiles it is for, but they may not have any special tile instructions and they definitely don't have the result. So I had a situation where I did need to be able to save empty forms. IE, once the user submits the task, I want a tile object to exist for each tile they selected. I found that when my formset forms were empty, the existing framework gave me no cleaned data and in fact would not let me save the form to an object. I got around this by simply creating a dummy field, which I set to a value in the view.py POST code. After setting that dummy field in the postdict, I created the formset and having that dummy field caused has_changed() to be true, which allowed the cleaned_data to be created and allowed the form.save() to actually do a save. Anyway, that's it. It's been a long haul (took me about 3 days to really grock what is going on) but it's cool now that it is working. Malcolm, thanks for all your help. I don't think I could have gotten it working without your pointers and high level review. Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Odd integrity error behavior when saving data
I have a Tile model that contains a foreign to a Chip: class Tile(models.Model): name=models.CharField(max_length=NAME_LENGTH) chip = models.ForeignKey(Chip) I find that I get an integrity error if I create a tile that refers to a chip that has not yet been saved: >>> c = Chip(name="chip") >>> t = Tile(name="tile", chip=c) >>> t.save() [stack trace omitted] IntegrityError: chipvision_tile.chip_id may not be NULL This is reasonable. So I then saved the chip and then tried to save the tile, but I still get the integrity error: >>> c.save() >>> t.chip >>> t.chip.id 5 >>> t.save() [stack trace omitted] IntegrityError: chipvision_tile.chip_id may not be NULL However, if I then reset the chip field of the tile (just by reassigning t.chip = t.chip) and then save the tile, the save now works fine: >>> t.chip = t.chip >>> t.save() # this save works! This seems odd. Is this expected behavior? Margie --~--~-~--~~~---~--~~ 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: Odd integrity error behavior when saving data
Gotcha, thanks Malcolm. On Mar 11, 8:26 pm, Malcolm Tredinnick wrote: > On Wed, 2009-03-11 at 19:21 -0700, Margie wrote: > > I have a Tile model that contains a foreign to a Chip: > > > class Tile(models.Model): > > name=models.CharField(max_length=NAME_LENGTH) > > chip = models.ForeignKey(Chip) > > > I find that I get an integrity error if I create a tile that refers to > > a chip that has not yet been saved: > > > >>> c = Chip(name="chip") > > >>> t = Tile(name="tile", chip=c) > > >>> t.save() > > [stack trace omitted] > > IntegrityError: chipvision_tile.chip_id may not be NULL > > > This is reasonable. So I then saved the chip and then tried to save > > the tile, but I still get the integrity error: > > >>> c.save() > > >>> t.chip > > > > >>> t.chip.id > > 5 > > >>> t.save() > > [stack trace omitted] > > IntegrityError: chipvision_tile.chip_id may not be NULL > > There are some implementation details going on here and we should > probably try to raise an error a bit earlier. The behaviour is expected > and the solution is to not assign unsaved objects. > > What's going on, if you care, is that there are two attributes involved. > The t.chip attribute is a copy of the Python object (the Chip instance). > The t.chip_id attribute holds the value of foreign key and when you > first assigned to t.chip, t.chip_id was set to None. That "None" isn't a > reference to anything, so when t.chip was updated (since it's a > reference), the t.chip_id value was not. > > There are a couple of potential things Django could do better here, > including resetting the chip_id value just before saving (a little risky > -- I think I worked out a way to do stupid things once, but I can't > remember what it is now) or just reporting an error when you wrote > t.chip = chip originally. > > Regards, > Malcolm > > > > > However, if I then reset the chip field of the tile (just by > > reassigning t.chip = t.chip) and then save the tile, the save now > > works fine: > > > >>> t.chip = t.chip > > >>> t.save() # this save works! > > That's because setting the 'chip' attribute calls a setter method that > also updates t.chip_id. Odd if you don't realise what's going on. > Consistent in an implementation sense, but, as I mention, we can do > better. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
inconsistency between remove() and clear()?
It seems to me there is an inconsistency between clear() and remove (). After a remove() I find that the related object set no longer contains the specified object (as expected), and the specified object also no longer points to the related set (this also is what I'd expect). However, in the case of clear(), I find that the related object set is now cleared out (as I'd expect), but the objects that used to be in the set still point to the set (not what I'd expect). Is this difference intentional? I also find that after exiting the shell and then going back in, now the objects that used to be in the set no longer point to the set. IE, the inconsistent clear behavior goes away if I exit the django shell and then re-enter. class Publisher(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher, blank=True, null=True) >>> pub = Publisher.objects.create(name="pub1") >>> book1 = pub.book_set.create(title="title1") >>> pub.book_set.all() [] >>> book2 = pub.book_set.create(title="title2") >>> pub.book_set.all() [, ] >>> book1.publisher >>> book2.publisher # after using remove() to remove book1, book1.publisher is empty >>> pub.book_set.remove(book1) >>> book1.publisher >>> pub.book_set.all() [] # Now book2 references pub. After using clear(), book2.publisher still references pub # This seems inconsistent with the remove() behavior above. >>> pub.book_set.clear() >>> book2.publisher Any comments from those in-the-know? Margie --~--~-~--~~~---~--~~ 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: inconsistency between remove() and clear()?
Ok, yes, this all makes sense now. Thanks for the explanation! Margie On Mar 24, 3:32 am, Russell Keith-Magee wrote: > On Tue, Mar 24, 2009 at 6:10 PM, Thomas Guettler wrote: > > > Hi, > > > book2.publisher is an attribute which was created before you deleted it. > > If you get book2 again from Book.objects, this attribute would not exist > > anymore. > > > I have not looked at the underlaying django source, but I guess that > > remove(obj) removes the attribute from obj. > > > But clear() can't do this, since it does not have a reference to all > > affected objects. > > Your guess at the implementation is correct. In the implementation of > remove(), we have a handle to the object that is being removed, so we > are able to update the value of the publisher attribute on the object. > In the case of clear(), we don't have a handle to the object being > updated, so we can't update the publisher attribute. > > Two other interesting manifestations/side effects of this behaviour > that are worth note: > > * If you have a second reference to book2, it won't be updated in the > case of remove(): > > >>> book1 = pub.book_set.create(title="title1") > >>> otherbook1 = Book.objects.get(title="title1") > ... > >>> otherbook1.publisher > > >>> pub.book_set.remove(book1) > >>> book1.publisher > >>> otherbook1.publisher > > > > * If you re-retrieve book2, the publisher attribute will be correct:>>> > pub.book_set.clear() > >>> book2.publisher > > >>> otherbook2 = Book.objects.get(title="title2") > >>> otherbook2.publisher > > # value is none, as expected > > Yours, > Russ Magee %-) --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
django apps that implement ticket filtering?
I am trying to implement a specialized ticketing system in django. At a high level, it has many similarities to the django bug tracking system, which I believe is implemented using trac. I have coded the models models and the associated django code that lets people create their tickets. Now I'm at the point where I want to implement queries. IE, let the user choose filters (and and or them together hopefully) that let you, for example, "find all tickets owned by Joe, created after 6/15/09, with status open". Nothing too new here. In looking for models of this functionality, I find the trac system to be fairly straighforward, from a user perspective. But of course, it isn't written in django. I looked at their html and javascript templates and found them very hard to wade through. I'm wondering if anyone knows of any open source django apps that do something similar? In particular, I'm interested in the html templates and associated javascript/jquery to make the filters "dynamic", as that is the area I am sort of weak in. Thanks for any pointers! Margie --~--~-~--~~~---~--~~ 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: django apps that implement ticket filtering?
Yeah, I just thought maybe I could leverage some existing code that would support AND and OR of filters and provide an interface where the user can add filters as needed. It seems to me that creating an interface where you AND and OR filters is not so simple. But that's not really a django issue - just thought someone here might have some ideas. Margie On Jun 25, 3:27 pm, lzantal wrote: > Hi, > > You could submit all the filters from an html form and in your view > function loop through the request.Post and build the queries if the > Post value is not empty.Using django.db.models.Q > > Laszlo Antalhttp://www.antalconsulting.com > Office: 208-699-7508 > > On Jun 25, 2009, at 2:32 PM, Margie wrote: > > > > > I am trying to implement a specialized ticketing system in django. At > > a high level, it has many similarities to the django bug tracking > > system, which I believe is implemented using trac. > > > I have coded the models models and the associated django code that > > lets people create their tickets. Now I'm at the point where I want > > to implement queries. IE, let the user choose filters (and and or > > them together hopefully) that let you, for example, "find all tickets > > owned by Joe, created after 6/15/09, with status open". Nothing too > > new here. In looking for models of this functionality, I find the > > trac system to be fairly straighforward, from a user perspective. But > > of course, it isn't written in django. I looked at their html and > > javascript templates and found them very hard to wade through. I'm > > wondering if anyone knows of any open source django apps that do > > something similar? In particular, I'm interested in the html > > templates and associated javascript/jquery to make the filters > > "dynamic", as that is the area I am sort of weak in. > > > Thanks for any pointers! > > > Margie > > --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Bug when creating Q object from string representation of another Q object?
I have a situation where I want to do the following: take a bunch of POST params and from them create a Q object urlencode that Q object and turn it into a GET param, redirect using that param process the GET that contains the urlencoded Q object, create a Q object from it, and use it in a filter I think this should all be possible, however, I am having trouble recreating the new Q object from the string representation of the original Q object. Here's an example of the problem: >>> filter_orig = Q(owner__username='mlevine') >>> print filter_orig (AND: ('owner__username', 'mlevine')) >>> filter_new = Q("%s" % orig) >>> print filter_new (AND: (AND: ('owner__username', 'mlevine'))) >>> Task.objects.filter(filter_orig) [, ] >>> Task.objects.filter(filter_new) Traceback (most recent call last): ... File "/home/mlevine/django/django_libs/django-admin-ui-july8/lib/ python2.6/site-packages/django/db/models/sql/query.py", line 1520, in add_filter arg, value = filter_expr Note that in the above log, when I print filter_new, there is an extra AND at the front. Logically this shouldn't be be a problem, but I suspect that it is indicative of the problem. Is what I'm doing above supposed to work? Is this a bug? This is using 1.1 beta. Margie --~--~-~--~~~---~--~~ 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: Bug when creating Q object from string representation of another Q object?
Yes - sorry about the typo. As you say, the "orig" should be filter_orig - that was a cut and paste mistake. I was playing around and I think I just mistakenly assumed that I could create a Q from the string representation of another Q. Sounds like that was a mistaken assumption. What I have is a string representation that is a prefix notation that is very similar to what you get when you print a Q. IE, it is easy for me to generate something like this: (OR (AND: ('owner__username', 'mlevine'), ('status', 'open')), ('priority', 'critical')) Where this means (Q(owner_username='mlevine') & Q(status='open')) | Q (priority='critical') Actually, what I have is just plain xml. Through basic regexp substitution I am able to turn it into the above prefix notation with minimal effort. So I was trying to figure out if there was a way I could easily create a Q without loading my prefix notation into a tree and recursing into the tree to create the Q from the leaves up. I was pleasantly surprised when I was able to construct a Q off of the string rep of another Q, but it looks like that it is not really doing what I thought it was doing. Ok, back to the drawing board. Margie On Jul 22, 5:02 am, Russell Keith-Magee wrote: > On Wed, Jul 22, 2009 at 5:52 AM, Margie wrote: > > > I have a situation where I want to do the following: > > take a bunch of POST params and from them create a Q object > > urlencode that Q object and turn it into a GET param, redirect > > using that param > > process the GET that contains the urlencoded Q object, create a > > Q object from it, and use it in a filter > > > I think this should all be possible, however, I am having trouble > > recreating the new Q object from the string representation of the > > original Q object. Here's an example of the problem: > > >>>> filter_orig = Q(owner__username='mlevine') > >>>> print filter_orig > > (AND: ('owner__username', 'mlevine')) > >>>> filter_new = Q("%s" % orig) > > This is the line that looks a bit suspect to me. Firstly - I'm > assuming `orig` should actually be `filter_orig` - in which case... > > >>>> print filter_new > > (AND: (AND: ('owner__username', 'mlevine'))) > > This isn't quite what you think it is. You are reading it as an AND > whose first term is an AND. I suspect what you are actually getting is > an AND clause whose first term is a string that starts "(AND:" > > When you construct filter_new, you don't pass in a string - you're > passing in a dictionary of kwargs. The owner__username='mlevine' > syntax is a keyword argument, not a string. > > Your original problem descriptions seems to suggest that you think you > will be able to pass a string into Q() and have it interpreted as a > query. This isn't the case - the arguments to Q() are no different to > the arguments to filter(). If you want to serialize a query for use in > a GET request, you'll need to find a different way to serialize your > query. > > Yours, > Russ Magee %-) --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Where are the admin app icons from?
Hi, I'm wondering if the icons in the admin app (for example, the addlink.gif icon) come from some standard icon (free) icon package where there are more goodies of the same sort? Anyone have any pointers for where those came from? Margie --~--~-~--~~~---~--~~ 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: Where are the admin app icons from?
Thanks Alex - I will check those out. But if anyone knows where the admin icons came from, I'd still love to know ... Margie On Jul 24, 4:01 pm, Alex Gaynor wrote: > On Fri, Jul 24, 2009 at 5:12 PM, Margie wrote: > > > Hi, > > > I'm wondering if the icons in the admin app (for example, the > > addlink.gif icon) come from some standard icon (free) icon package > > where there are more goodies of the same sort? Anyone have any > > pointers for where those came from? > > > Margie > > I don't know where the Django ones came from (they may have been > custom designed for all I know), but if you're looking for good free > icons I'm quite fond of the famfamfam silk icon > set:http://www.famfamfam.com/lab/icons/silk/ > > Alex > > -- > "I disapprove of what you say, but I will defend to the death your > right to say it." -- Voltaire > "The people's good is the highest law." -- Cicero > "Code can always be simpler than you think, but never as simple as you > want" -- Me --~--~-~--~~~---~--~~ 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: Where are the admin app icons from?
Yeah ... I know where the icons used in the admin app are. And I'm using them in my own app (which is derived from the admin app). So I was just trying to figure out if they came from some general package of icons where there were more with the same look and feel. Based on Daniel's reply, it sounds like they were designed specifically for django, or that I should talk to Wilson Miner about it. (Thanks, Daniel). Margie On Jul 25, 6:38 pm, Asinox wrote: > The icons : > > site-packages\django\contrib\admin\media\img\admin > > :) > > On Jul 25, 1:46 pm, Margie wrote: > > > Thanks Alex - I will check those out. But if anyone knows where the > > admin icons came from, I'd still love to know ... > > > Margie > > > On Jul 24, 4:01 pm, Alex Gaynor wrote: > > > > On Fri, Jul 24, 2009 at 5:12 PM, Margie wrote: > > > > > Hi, > > > > > I'm wondering if the icons in the admin app (for example, the > > > > addlink.gificon) come from some standardicon(free)iconpackage > > > > where there are more goodies of the same sort? Anyone have any > > > > pointers for where those came from? > > > > > Margie > > > > I don't know where the Django ones came from (they may have been > > > custom designed for all I know), but if you're looking for good free > > > icons I'm quite fond of the famfamfam > > > silkiconset:http://www.famfamfam.com/lab/icons/silk/ > > > > Alex > > > > -- > > > "I disapprove of what you say, but I will defend to the death your > > > right to say it." -- Voltaire > > > "The people's good is the highest law." -- Cicero > > > "Code can always be simpler than you think, but never as simple as you > > > want" -- Me --~--~-~--~~~---~--~~ 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: Where are the admin app icons from?
Yeah, I looked at those and they are very nice, but not quite the same, and the size differences seem to be a problem. My graphic design skills are pretty minimal. I tried scaling them down to the size I need in gimp, but they didn't look very good after that. Tried the "minis" in that set as well, but they were *too* small! Arrgh! It ain't easy designing a web app with no graphic design skills! Margie On Jul 27, 11:11 am, Luke Seelenbinder wrote: > I think they are the FamFamFam Icon pack. > > http://www.famfamfam.com/ > > Luke S. > > On 07/27/2009 02:10 PM, Margie wrote: > > > > > Yeah ... I know where the icons used in the admin app are. And I'm > > using them in my own app (which is derived from the admin app). So I > > was just trying to figure out if they came from some general package > > of icons where there were more with the same look and feel. Based on > > Daniel's reply, it sounds like they were designed specifically for > > django, or that I should talk to Wilson Miner about it. (Thanks, > > Daniel). > > > Margie > > > On Jul 25, 6:38 pm, Asinox wrote: > >> The icons : > > >> site-packages\django\contrib\admin\media\img\admin > > >> :) > > >> On Jul 25, 1:46 pm, Margie wrote: > > >>> Thanks Alex - I will check those out. But if anyone knows where the > >>> admin icons came from, I'd still love to know ... > > >>> Margie > > >>> On Jul 24, 4:01 pm, Alex Gaynor wrote: > > >>>> On Fri, Jul 24, 2009 at 5:12 PM, Margie wrote: > > >>>>> Hi, > > >>>>> I'm wondering if the icons in the admin app (for example, the > >>>>> addlink.gificon) come from some standardicon(free)iconpackage > >>>>> where there are more goodies of the same sort? Anyone have any > >>>>> pointers for where those came from? > > >>>>> Margie > > >>>> I don't know where the Django ones came from (they may have been > >>>> custom designed for all I know), but if you're looking for good free > >>>> icons I'm quite fond of the famfamfam > >>>> silkiconset:http://www.famfamfam.com/lab/icons/silk/ > > >>>> Alex > > >>>> -- > >>>> "I disapprove of what you say, but I will defend to the death your > >>>> right to say it." -- Voltaire > >>>> "The people's good is the highest law." -- Cicero > >>>> "Code can always be simpler than you think, but never as simple as you > >>>> want" -- Me > > > > > > smime.p7s > 4KViewDownload --~--~-~--~~~---~--~~ 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: Where are the admin app icons from?
I'll try the css idea, but I suspect that things this small just can't be resized well. I actually contacted Wilson Miner, and he said that he did create those especially for the admin site. When I asked him about scaling other images (like the famfam ones, which he also pointed me to), he said: "No at those sizes, you have to design the icons at the size they'll be used. Not enough pixels in such a small image to scale properly." Between the famfam stuff and various other random "finds" on the web, I think I can get by. Thanks for the pointers to that other grey scale library as well. I can see that being useful in the future. Margie On Jul 27, 12:15 pm, Luke Seelenbinder wrote: > Could you resize them simply with CSS? > CSS handles resizing quite well. > > I did find one set of icons sized at 10x10 > here:http://www.brandspankingnew.net/archive/2006/12/hohoho.html > But they are greyscale. > > Luke S. > > On Mon, Jul 27, 2009 at 3:07 PM, Margie wrote: > > > Yeah, I looked at those and they are very nice, but not quite the > > same, and the size differences seem to be a problem. My graphic > > design skills are pretty minimal. I tried scaling them down to the > > size I need in gimp, but they didn't look very good after that. > > Tried the "minis" in that set as well, but they were *too* small! > > > Arrgh! It ain't easy designing a web app with no graphic design > > skills! > > > Margie > > > On Jul 27, 11:11 am, Luke Seelenbinder > > wrote: > > > I think they are the FamFamFam Icon pack. > > > >http://www.famfamfam.com/ > > > > Luke S. > > > > On 07/27/2009 02:10 PM, Margie wrote: > > > > > Yeah ... I know where the icons used in the admin app are. And I'm > > > > using them in my own app (which is derived from the admin app). So I > > > > was just trying to figure out if they came from some general package > > > > of icons where there were more with the same look and feel. Based on > > > > Daniel's reply, it sounds like they were designed specifically for > > > > django, or that I should talk to Wilson Miner about it. (Thanks, > > > > Daniel). > > > > > Margie > > > > > On Jul 25, 6:38 pm, Asinox wrote: > > > >> The icons : > > > > >> site-packages\django\contrib\admin\media\img\admin > > > > >> :) > > > > >> On Jul 25, 1:46 pm, Margie wrote: > > > > >>> Thanks Alex - I will check those out. But if anyone knows where the > > > >>> admin icons came from, I'd still love to know ... > > > > >>> Margie > > > > >>> On Jul 24, 4:01 pm, Alex Gaynor wrote: > > > > >>>> On Fri, Jul 24, 2009 at 5:12 PM, Margie > > > >>>> wrote: > > > > >>>>> Hi, > > > > >>>>> I'm wondering if the icons in the admin app (for example, the > > > >>>>> addlink.gificon) come from some standardicon(free)iconpackage > > > >>>>> where there are more goodies of the same sort? Anyone have any > > > >>>>> pointers for where those came from? > > > > >>>>> Margie > > > > >>>> I don't know where the Django ones came from (they may have been > > > >>>> custom designed for all I know), but if you're looking for good free > > > >>>> icons I'm quite fond of the famfamfam > > > >>>> silkiconset:http://www.famfamfam.com/lab/icons/silk/ > > > > >>>> Alex > > > > >>>> -- > > > >>>> "I disapprove of what you say, but I will defend to the death your > > > >>>> right to say it." -- Voltaire > > > >>>> "The people's good is the highest law." -- Cicero > > > >>>> "Code can always be simpler than you think, but never as simple as > > > >>>> you > > > >>>> want" -- Me > > > > smime.p7s > > > 4KViewDownload --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Possible to add to a queryset?
Is it possible to add to a queryset? Say I have a Book model and qset is an existing queryset of books. If I want to create a new queryset that contains everything in qset, plus books that have ids 1, 2, and 3, do I do this: Book.objects.filter(Q(id__in=[obj.id for obj in qset]) | Q(id__in= [1,2,3])) Is there some more efficient way to do this? Margie --~--~-~--~~~---~--~~ 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: Possible to add to a queryset?
Ah, right. I knew there had to be a way. Thanks Alex! Margie On Jul 28, 12:54 pm, Alex Gaynor wrote: > You ca use the | operator o querysets themselves. So qser | > model.objects.filter(id__i=[1,2,3]) > > Alex > > On Jul 28, 2009 3:49 PM, "Margie" wrote: > > Is it possible to add to a queryset? > > Say I have a Book model and qset is an existing queryset of books. If > I want to create a new queryset that contains everything in qset, plus > books that have ids 1, 2, and 3, do I do this: > > Book.objects.filter(Q(id__in=[obj.id for obj in qset]) | Q(id__in= > [1,2,3])) > > Is there some more efficient way to do this? > > Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
django-users@googlegroups.com
I have a question about what people recommend when rendering custom widgets. My question relates to whether the rendered widgets should contain their own scripts. Let me use an example. Say I have a table and each row in the table has a date input. To the right of each date input I want to render a little jquery calendar. What I've been doing is creating a DateWidget and in that widget I override the render method such that it contains a script tag that calls the datePicker() jquery function that element, like this: def render(self, name, value, attrs=None): rendered = super(DateWidget, self).render(name, value, attrs) return rendered + mark_safe(u''' Date.firstDayOfWeek = 0; Date.format = 'mm/dd/'; $ ('#id_%s').datePicker();''' % (name)) >From a code point of view I like this - it keeps the special jquery date code right with the widget, which I like. However, I notice that when the page is displayed, that it seems to scroll all the way to the bottom before redisplaying with the focus at the top of the page. I think that perhaps as the javascript executes in each row of my table, the browser sort of scrolls down, leaving the user with this slighly annoying look of it scrolling all the way down and then flashing back to the top. Would I be better off just having the render() method assign a special "date" class to my widget and then have a global jquery function that finds all objects with the date class and calls datePicker on them? Would this avoid the screen flash problem that I see? Is there a generally accepted strategy that others are using? Margie Margie --~--~-~--~~~---~--~~ 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:
Ok - yes, that works great for my date widget. So now I have just a tiny .js file that contains this: $(document).ready(function() { Date.firstDayOfWeek = 0; Date.format = 'mm/dd/'; $('.chipvision_date_widget').datePicker(); }); And my Media class for DateWidget refers to it (as well as the other related .js files), ie: class DateWidget(widgets.DateInput): class Media: js = ('js/jquery.js', "js/date.js", "js/jquery.datePicker.min-2.1.2.js", "widget_js/date_widget.js", ) But what do you do for a widget where the jquery function being called requires an argument. For example, I have an autocomplete widget that takes as a "prePopulate" argument that contains the value it should initialized with. Currently my render function for this widget looks like this: def render(self, name, value, attrs=None): context = { 'base_widget': super(OwnerWidget, self).render(name, value, attrs), 'name': name, 'value': value, 'prePopulateString':mark_safe(self.prePopulateString), } return mark_safe(render_to_string(self.template, context)) self.template is an html snippet that looks like this: {{ base_widget }} $(document).ready(function() { $('#id_{{ name }}').tokenInput( '/taskmanager/get_matching_users/', { prePopulate: [{{prePopulateString}}], } ); }); Currently each of my autocomplete fields ends up rendering with this long script containing the contents of that html snippet (but longer since there are a bunch of other arguments). Is there a way for me to use the model that you're describing for this? IE, I'd like to just render the input field with a special class and then have a small .js file that finds all fields with that class and calls .tokenInput() on them. However, I don't understand how to pass the prePopulate argument in that case. Margie On Jul 29, 12:49 pm, Vasil Vangelovski wrote: > > The way I do it is what you allude to at the end, have a special class > > on the inputs and then use the inner Media class of the widget > > (http://docs.djangoproject.com/en/dev/topics/forms/media/) to provide > > a javascript file that'll automatically add the widget to all of the > > items with that class. > > Besides having less code this has another benefit, you keep your js > code in js files and outside of your html markup. --~--~-~--~~~---~--~~ 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:
> > There's no easy way of passing dynamic javascript in the Media class. > However, you can fake it, with a bit of work, by passing the parameter > to the script in a querystring. So, for example, in the list of js > files to be included you would have > 'js/myfile.js?renderclass=%s' % self.prePopulateString > > Then your js can find its own
Re:
Hi Vasil, Could you clarify how I access the variable from the javascript? For example, using my DateWidget as an example, say in my wdigets.py I have this (note I've added ?myVar='xyz' in second line: class DateWidget(widgets.DateInput): class Media: js = ("js/jquery.datePicker.min-2.1.2.js", "js_custom/date_widget.js?myVar='xyz''") The complete contents of date_widget.js is currently: $(document).ready(function() { Date.firstDayOfWeek = 0; Date.format = 'mm/dd/'; $('.chipvision_date_widget').datePicker(); }); How do I access myVar from inside date_widget.js? I know the .js files listed in the Media class get output into my html via my inclusion of {{ media }} in my template. So I see that I get this in my html But I seem to have some missing piece - I don't get how to get access to xyz from the .js script itself. Sorry if this is a dumb question - I've written various bits of javascript/jquery but haven't encountered this. Margie On Jul 29, 5:51 pm, Vasil Vangelovski wrote: > Of course that the files specified in the class Media are accessed via > GET. How else would they be accessed? It's possible to fetch a js file > with additional get arguments and access those values from the js. So > you can pass prePopulateString as a get parameter to the js file in > class Media for example: > > class Media: > js = ('myAutoCompleteInit.js?prepopString=%s'%prePopulateString) > > Then pass that parameter to the js method you need inside > myAutoCompleteInit.js. > > On Thu, Jul 30, 2009 at 1:53 AM, Margie wrote: > > >> There's no easy way of passing dynamic javascript in the Media class. > >> However, you can fake it, with a bit of work, by passing the parameter > >> to the script in a querystring. So, for example, in the list of js > >> files to be included you would have > >> 'js/myfile.js?renderclass=%s' % self.prePopulateString > > >> Then your js can find its own
Re:
Ah - ok, I finally see what you are saying. Sorry, I somehow began thinking there was some additional "GET" happening that I just really didn't understand. I didn't understand that "src" was referring to the "src" in the tag. My world had become very confused. Ok, the world is back to one that I understand. Yes, I agree this is too complicated for my case (especially since I am calling my autocomplete jquery function multiple times per single html page, and each time it has a different initial input). Anyway, thanks for the clarification. It was just bugging me that I didn't understand! Margie On Jul 30, 12:25 pm, Daniel Roseman <dan...@roseman.org.uk> wrote: > On Jul 30, 7:41 pm, Margie <margierogin...@yahoo.com> wrote: > > > > > Hi Vasil, > > > Could you clarify how I access the variable from the javascript? For > > example, using my DateWidget as an example, say in my wdigets.py I > > have this (note I've added ?myVar='xyz' in second line: > > > class DateWidget(widgets.DateInput): > > class Media: > > js = ("js/jquery.datePicker.min-2.1.2.js", > > "js_custom/date_widget.js?myVar='xyz''") > > > The complete contents of date_widget.js is currently: > > > $(document).ready(function() { > > Date.firstDayOfWeek = 0; > > Date.format = 'mm/dd/'; > > $('.chipvision_date_widget').datePicker(); > > }); > > > How do I access myVar from inside date_widget.js? > > > I know the .js files listed in the Media class get output into my html > > via my inclusion of {{ media }} in my template. So I see that I get > > this in my html > > > <script type="text/javascript" src="/site_media/js_custom/ > > date_widget.js?myVar=%27xyz%27"> > > > > > But I seem to have some missing piece - I don't get how to get access > > to xyz from the .js script itself. Sorry if this is a dumb question - > > I've written various bits of javascript/jquery but haven't encountered > > this. > > > Margie > > The only way, as I said originally, is to query the DOM. That is, look > for the
Re:
Are you referring to $.data()? I think that's a great solution. I could attach my data to the tag that the autocomplete is associated with, and then in my jquery function that finds all of those tags and then calls the autocomplete plugin on them, just pull off the stored initialization data and then call the autocomplete plugin using that as the argument. Very nice. I have seen $.data() used, but haven't used it myself yet, so it wasn't on the top of my brain. It seems like a great solution here. Thanks for that idea! Margie On Jul 30, 11:46 am, Jim Garrison wrote: > > But what do you do for a widget where the jquery function being called > > requires an argument. For example, I have an autocomplete widget that > > takes as a "prePopulate" argument that contains the value it should > > initialized with. > > Have you considered using the jquery metadata plugin? It should allow > you to store the information you need right in the DOM, and then > access it from javascript. --~--~-~--~~~---~--~~ 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:
Hi Vasil. Thanks for the snippets, those are useful. I was somehow just very confused on the mechanism that was being described, but it all makes sense now. Margie On Jul 30, 11:41 am, Margie wrote: > Hi Vasil, > > Could you clarify how I access the variable from the javascript? For > example, using my DateWidget as an example, say in my wdigets.py I > have this (note I've added ?myVar='xyz' in second line: > > class DateWidget(widgets.DateInput): > class Media: > js = ("js/jquery.datePicker.min-2.1.2.js", > "js_custom/date_widget.js?myVar='xyz''") > > The complete contents of date_widget.js is currently: > > $(document).ready(function() { > Date.firstDayOfWeek = 0; > Date.format = 'mm/dd/'; > $('.chipvision_date_widget').datePicker(); > }); > > How do I access myVar from inside date_widget.js? > > I know the .js files listed in the Media class get output into my html > via my inclusion of {{ media }} in my template. So I see that I get > this in my html > > > > > But I seem to have some missing piece - I don't get how to get access > to xyz from the .js script itself. Sorry if this is a dumb question - > I've written various bits of javascript/jquery but haven't encountered > this. > > Margie > > On Jul 29, 5:51 pm, Vasil Vangelovski wrote: > > > Of course that the files specified in the class Media are accessed via > > GET. How else would they be accessed? It's possible to fetch a js file > > with additional get arguments and access those values from the js. So > > you can pass prePopulateString as a get parameter to the js file in > > class Media for example: > > > class Media: > > js = ('myAutoCompleteInit.js?prepopString=%s'%prePopulateString) > > > Then pass that parameter to the js method you need inside > > myAutoCompleteInit.js. > > > On Thu, Jul 30, 2009 at 1:53 AM, Margie wrote: > > > >> There's no easy way of passing dynamic javascript in the Media class. > > >> However, you can fake it, with a bit of work, by passing the parameter > > >> to the script in a querystring. So, for example, in the list of js > > >> files to be included you would have > > >> 'js/myfile.js?renderclass=%s' % self.prePopulateString > > > >> Then your js can find its own
odd behavior with session variable that contains a list
I am seeing some behavior with session that I don't understand. If I have a session variable called recentAddIds that contains a list. I find that if I append to that list, like this: request.session['recentAddIds'].append(newlySavedId) Then when I next receive a GET, I find that request.session ['recentAddIds'] does not contain the appended data (but does contain the data that was there prior to the append). If I instead make a copy of the list and put that copy into the session variable, then when I next receive a GET, my session variable does not contain the newly appended data. request.session['recentAddIds'] = [x for x in request.session ['recentAddIds']] + [newlySavedId] Can anyone explain why this is and if it is expected behavior? Is it ok for sesion variables to contain lists or other complex structures, or should they just be simple strings? Margie --~--~-~--~~~---~--~~ 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: odd behavior with session variable that contains a list
Makes perfect sense, thanks for that pointer! On Jul 31, 11:17 am, Alex Gaynor wrote: > On Fri, Jul 31, 2009 at 1:15 PM, Margie wrote: > > > I am seeing some behavior with session that I don't understand. If I > > have a session variable called recentAddIds that contains a list. I > > find that if I append to that list, like this: > > > request.session['recentAddIds'].append(newlySavedId) > > > Then when I next receive a GET, I find that request.session > > ['recentAddIds'] does not contain the appended data (but does contain > > the data that was there prior to the append). > > > If I instead make a copy of the list and put that copy into the > > session variable, then when I next receive a GET, my session variable > > does not contain the newly appended data. > > > request.session['recentAddIds'] = [x for x in request.session > > ['recentAddIds']] + [newlySavedId] > > > Can anyone explain why this is and if it is expected behavior? Is it > > ok for sesion variables to contain lists or other complex structures, > > or should they just be simple strings? > > > Margie > > The reason this is is because of how some of python's magic methods > work. doing request.SESSION['key'].append() uses the __getitem__ > method on request.SESSION and calls append on the result, whereas > doing request.SESSION['key'] = val uses the __setitem__ > method.http://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessi... > describes how to work with this behavior. > > Alex > > -- > "I disapprove of what you say, but I will defend to the death your > right to say it." -- Voltaire > "The people's good is the highest law." -- Cicero > "Code can always be simpler than you think, but never as simple as you > want" -- Me --~--~-~--~~~---~--~~ 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: Date format in modelform.
I did this with a combination of a DateWidget and a small .js file that calls the jquery datepicker on each widget. I don't use the same date format as you, but you should be able to modify it to fit your need. It's amazing how easy the code below looks, but I can tell you it took me most of a day to figure out how to use the jquery datepicker, how to create widgets, and how to just put it all together so that it works! class DateWidget(widgets.DateInput): class Media: js = ('js/jquery.js', "js/date.js", "js/jquery.datePicker.min-2.1.2.js", "js_custom/date_widget.js", ) css = {'all' : ('css/date_picker.css', 'css/ date_picker_chipvision.css') } def __init__(self, attrs={}): attrs['class'] = 'my_class_to_identify_datewidget' super(DateWidget, self).__init__(format='%m/%d/%Y', attrs=attrs) Then I have a small .js file (js_custom/date_widget.js) that has this: $(document).ready(function() { Date.firstDayOfWeek = 0; Date.format = 'mm/dd/'; $('.my_class_to_identify_datewidget').datePicker(); }); I'm not sure if settings Date.firstDayOfWeek and Date.format the way I do is the best way to do it, but I could not figure out how to do it via params to datePicker. Anyway, hope this helps. Margie On Aug 3, 11:08 am, zayatzz wrote: > Hello. > > I have this in my form (modelform) for birth_date field: > birth_date = forms.DateField(('%d/%m/%Y',), label='Birth Date', > required=False ), which overrides this in model: > > birth_date = models.DateField(help_text="birth date", > verbose_name="Birth date", blank=True, null=True, ) > > I also have jquery datepicker on the page which sets date in the same > format (%d/%m/%Y). But the form saves date in %Y-%m-%d format in > database, which means that when user returns to reedit the data, the > form wont validate and the user has to set the date again. > > Can anyone tell me what causes such behaviour and how to fix/change > it? My database in mysql - no idea if this is relevant. > > Alan --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Email interface to django app
I have an app that is similar in many ways to the django admin app. My users are requesting access via email. IE, when an object (task in my case) gets created, they want it to send them an email and then they want to be able to respond to that email to update various fields associated with the task. I'm interested in any insights folks have as to the preferable way to implement this. It seems to me there are a few obvious choices: 1. The guy that manages our IT side of things says I can have a script get executed whenever an email request comes in. This sendmail interface would provide my program with the contents of the email, and my program could be a 'manage.py shell' program that processes the request, opening my database and modifying it accordingly. 2. Similar to 1 above, I could have a script get executed whenever an email request comes in, but instead of actually doing the processing and modifying the database, it could contact the server via a POST and have the server do the work 3. I saw an example of the way jutda does it - they seem to use cron to run their script, and the script is basically in line with 1) above. The cron job runs the script periodically it grabs the email (eithe rvia pop or imap) and them modifies the db via the standard django ORM interface. Maybe there are other ways. Can anyone comment on the pros/cons of these methods of interfacing to my django web app via email? Is there anything I am missing here that I should be looking into? Thanks for any insights, Margie --~--~-~--~~~---~--~~ 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: Simultaneous use of the admin interface
I posted this same issue to the issue tracker a couple months ago, here is the report: http://code.djangoproject.com/ticket/11313 I do believe this is a shortcoming of the admin interface. I think that when fields became editable in 1.1, this was not handled and needs to be adressed in order for multiple people to modify at once. Currently the changelist is imlemented such that the ids of the forms in the changelist are just numerically ordered (first form is 1, second is 2, etc). Thus, if the database changes under you, when you then save your data, the forms that are generated (which are the result of a filter based on your current filter params) do not have the same numbering as the forms you just posted. This just doesn't work. I think that instead the implementation needs to be changed so that when an edited changelist is posted, each form carries with it the id of the object that it is for. Then, instead of filtering when the POST is received, the code needs to just extract the ids and use those as the queryest. This may be more detail than anyone wants - but I figured I'd post it just in case. In my own app, which has a lot of similarites to the admin app, I have done what I described above, and for me it has worked well. Margie On Aug 5, 12:06 pm, David wrote: > Using Django 1.1 if I do: > > 1) sign into admin as user A in one browser and begin to edit a record > 2) sign into admin as user B in another browser and begin to edit the > SAME record > 3) make a change as user A and press Save > 4) make a different change as user B and press Save > > The result is that A's change is silently overwritten with user B's > change. > > How do I make it so that user B gets an error telling them the record > has been changed by someone else since they started editing it? That's > what I would have expected to be the default behaviour. > > I did some searching of the documentation but didn't find anything > obviously related. I also looked here at past posts and saw some > people asking similar questions but no obvious solutions. There was > some talk of adding SELECT FOR UPDATE functionality to Django 1.1, but > I don't know if that made it in, or how to use it if it did. > > Can I perhaps add hooks to save a copy of the model object at the HTTP > GET time, and at HTTP POST pull another copy of the model back from > the db (distinct from the copy that is about to be saved) and compare > to the previous one from the HTTP GET then error if they're different? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
How to specify site's domain dynamically in development environment
My app needs to create a public url for its objects in order to send that out via email. My code does this by prefixing site.domain to the relative portion of the url. When working in my development environment (using runserver), the machine I am running the server on frequently changes. I was thinking of putting some code into admin.py that figures out the ip address and the port on the fly and creates a Site object from that. I can get from ip address via socket.gethostbyname(), but I'm not sure how to identify the port I am running on. Is there any way to get that information from the development server? Is there some typical way that folks handle this? Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
django-threadedcomments app
Anyone know any status on the django-threadedcomments app? The google group on it seems to be inactive. The last update I see about it is: March 31, 2009: Released version 0.5 of the application and moved. This is the last of this line--the next release will be a large rewrite to use the comment extension hooks provided in Django 1.1 and will be backwards incompatible. Anyway, just wondering if anyone here knows anything more? Margie --~--~-~--~~~---~--~~ 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: django-threadedcomments app
Hi Eric, Thanks for the info. A couple questions: * Does the .5 version work with django 1.1? * Do you have any sort of ETA on when you think the GitHub version will be ready for public use? Is it in a form now that it could actually be used? IE, if I am willing to dive in and look at the code, does the GitHub code have a reasonable level of functionality or is it completley torn up and non-working? Just trying to get an idea if I should go for the new or stick with the old. I'm fine with diving in and trying to fix bugs as needed, but obviously it is better if there is a base level of functionality working. Thanks very much for the package, it seems very nice. My goal is to provide a comment interface to my users that is similar to the google groups interface - it seems that threadedcomments is very well suited to that, do you agree? Margie On Aug 6, 4:40 pm, Margie wrote: > Anyone know any status on the django-threadedcomments app? The google > group on it seems to be inactive. The last update I see about it is: > > March 31, 2009: Released version 0.5 of the application and moved. > This is the last of this line--the next release will be a large > rewrite to use the comment extension hooks provided in Django 1.1 and > will be backwards incompatible. > > Anyway, just wondering if anyone here knows anything more? > > Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Bug with model get_*_display() methods?
I see inconsistencies in how get_*_display() works based on whether the object is a recently saved object. Probably an example describes this best: My model contains this: class Task(models.Model): STATUS_CHOICES = ( (OPEN_STATUS, 'Open'), (CLOSED_STATUS, 'Closed'), (STALLED_STATUS, 'Stalled'),) status = models.IntegerField(choices=STATUS_CHOICES, blank=True, null=True) If I get a Task object from the database (via a .get() or .filter()), then my status field contains an integer and I can call the .get_status_display() method, ie: (Pdb) type(t) (Pdb) t.status 3 (Pdb) t.get_status_display() u'Stalled' However, if I have recently saved a modelForm associated with my Task model and now have a handle to the object that that save() returned, the status is in unicode, and get_status_display() doesn't return a useful string: (Pdb) type(self) (Pdb) self.status u'3' (Pdb) self.get_status_display() u'3' Is this expected behavior? Margie --~--~-~--~~~---~--~~ 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: django-threadedcomments app
Ok, gotcha, thanks! One final question - on your web page you have a tutorial and it references a link to the final product of the tutorial at: http://www.eflorenzano.com/threadedcomments/example/ However that link seems to be broken. If this is something easy to fix, that would be nice! Margie On Aug 7, 3:02 pm, Eric Florenzano wrote: > > * Does the .5 version work with django 1.1? > > Yes, it should work just fine. > > > * Do you have any sort of ETA on when you think the GitHub version > > will be ready for public use? Is it in a form now that it could > > actually be used? IE, if I am willing to dive in and look at the > > code, does the GitHub code have a reasonable level of functionality or > > is it completley torn up and non-working? > > It is in working condition right now, and can be used, but no I'm > sorry I don't have an ETA on when it will be in a releasable state > right now with docs and examples. > > > Just trying to get an idea if I should go for the new or stick with > > the old. I'm fine with diving in and trying to fix bugs as needed, > > but obviously it is better if there is a base level of functionality > > working. > > Don't worry, the base functionality is working just fine. I haven't > used it in production yet, but I got some prototypes up and running > and I think it's pretty solid. > > > Thanks very much for the package, it seems very nice. My goal is to > > provide a comment interface to my users that is similar to the google > > groups interface - it seems that threadedcomments is very well suited > > to that, do you agree? > > Seems like a good fit to me! > > For what it's worth, I recommend just using the 0.5.X release for now, > because it works just fine and other people in the community have > familiarity with it besides just myself (for example, most people > using the comments in Pinax use threadedcomments 0.5.X). When I do > finally release the new version, I'll definitely provide a migration > script. > > Thanks, > Eric Florenzano --~--~-~--~~~---~--~~ 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: Bug with model get_*_display() methods?
Hmmm, ok, after digging around I realize that full_clean was not setting cleaned_data for the status field to an integer value; cleaned_data['status'] was just getting set to something like u'1'. I am in fact using sqllite, and yes, my status fields are just integers: OPEN_STATUS = 1 CLOSED_STATUS = 2 STALLED_STATUS = 3 I think the problem has to do with the way I created the status field, which is like this: self.fields["status"] = forms.ChoiceField (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), required=False) I tried moving to TypedChoiceField(), but that didn't help. I debugged into it in the case where I used TypedChoiceField() and I can see that when coerce is called it isn't doing anything, it is just returning the unicode value. I find that if I do this instead, that it does do the coerce correctly: self.fields["status"].widget = StatusWidget(task=instance) In looking at the doc it looks like the purpose of TypedChoiceField() is to allow me to create my own coerce function, is that right? And of course I wasn't doing that so it was behaving the same as ChoiceField, and it looks like the default there is to just return the unicode. When I don't declare the status field at all (ie, just let django do it's default thing), my guess is that it is choosing a coerce function based on the integer type of my choices, is that true? I have never used anything but sqlite3 so far, so I guess that was masking the error and I would have run into this in a more serious way when I moved to a different db? Ok, cool, learn something new every day. Thanks for you pointers, if you can just yay or nay my hypotheses above, that'd be cool. Margie On Aug 7, 7:39 pm, Malcolm Tredinnick wrote: > On Fri, 2009-08-07 at 11:40 -0700, Margie wrote: > > I see inconsistencies in how get_*_display() works based on whether > > the object is a recently saved object. Probably an example describes > > this best: > > > My model contains this: > > > class Task(models.Model): > > > STATUS_CHOICES = ( > > (OPEN_STATUS, 'Open'), > > (CLOSED_STATUS, 'Closed'), > > (STALLED_STATUS, 'Stalled'),) > > > status = models.IntegerField(choices=STATUS_CHOICES, blank=True, > > null=True) > > I'm assuming OPEN_STATUS and friends are integers here (and not '1' or > other strings that contain integers). > > [...] > > > However, if I have recently saved a modelForm associated with my Task > > model and now have a handle to the object that that save() returned, > > the status is in unicode, and get_status_display() doesn't return a > > useful string: > > > (Pdb) type(self) > > > > (Pdb) self.status > > u'3' > > (Pdb) self.get_status_display() > > u'3' > > If I create a standard ModelForm subclass for your task model and then > submit some data to it (just using {"status": "1"} as the POST data > dictionary), I cannot replicate your problem. > > The devil is in the details here. What does your ModelForm look like? > > The results you are seeing are consistent with the form somehow saving a > string value for the "status" field. Which means (a) you're using > SQLite, since other databases will complain about the type mismatch, and > (b) something is going funky in your particular ModelForm. > > The get_FOO_display() method requires an exact match the choice value > and the value of the field, otherwise it just returns the field value. > Since 3 != u'3' in Python, it is returning the correct result, given the > value of the status field. The question is how did you manage to get a > string into the status field. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: Bug with model get_*_display() methods?
Ok, still slightly confused. First - a high level description. I have a field that contains choices, but when I display the select, I want to display some extra html below the select box, so I am creating a custom widget that displays the standard select followed by my html. Question: If want to use a special widget for a ChoiceField, is it true that I need to instantiate the ChoiceField (or TypedChoiceField), rather than just setting the .widget attribute on the one that is by default created for me (due to it being a modelForm)? I find that if I just do this: self.fields["status"].widget = StatusWidget(task=instance) then my widget's select does not contain any choices. My widget doesn't do anything special to the select, it looks like this: class StatusWidget(widgets.Select): def __init__(self, task, attrs={}): self.task = task super(StatusWidget, self).__init__(attrs) def render(self, name, value, attrs=None): rendered = super(StatusWidget, self).render(name, value, attrs) rendered = rendered + add a bunch of stuff to the end return rendered Because I seem unable to display the choices correctly in the select box when I just set the field's widget attribute to my StatusWidget, I am instantiating the field itself. That now looks like this: self.fields["status"] = forms.TypedChoiceField (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), required=False, coerce=IntegerField.to_python) However, I see when debugging that IntegerField.to_python is an unbound method: (Pdb) self.coerce What is the right thing to set coerce to if I just want it to do whatever it would "normally" do for the corresponding model field if I wasn't trying to override the widget? In my case I have verified that if I set coerce=int that does work, but that doesn't seem very general. I'd much rather use whatever the standard coerce method would have been if I hadn't overridden the widget. Margie On Aug 8, 12:11 am, Malcolm Tredinnick wrote: > Hi Margie, > > > > On Fri, 2009-08-07 at 23:17 -0700, Margie wrote: > > > Hmmm, ok, after digging around I realize that full_clean was not > > setting cleaned_data for the status field to an integer value; > > cleaned_data['status'] was just getting set to something like u'1'. > > > I am in fact using sqllite, and yes, my status fields are just > > integers: > > > OPEN_STATUS = 1 > > CLOSED_STATUS = 2 > > STALLED_STATUS = 3 > > > I think the problem has to do with the way I created the status field, > > which is like this: > > > self.fields["status"] = forms.ChoiceField > > (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), > > required=False) > > Right, that won't do what you want. ChoiceField normalizes to a unicode > object. > > > > > I tried moving to TypedChoiceField(), but that didn't help. I > > debugged into it in the case where I used TypedChoiceField() and I can > > see that when coerce is called it isn't doing anything, it is just > > returning the unicode value. > > > I find that if I do this instead, that it does do the coerce > > correctly: > > > self.fields["status"].widget = StatusWidget(task=instance) > > > In looking at the doc it looks like the purpose of TypedChoiceField() > > is to allow me to create my own coerce function, is that right? > > Correct. > > > And > > of course I wasn't doing that so it was behaving the same as > > ChoiceField, and it looks like the default there is to just return the > > unicode. > > Also correct. The documentation says "Defaults to an identity function" > and all the data coming from a form submission are strings (Python > unicode objects), so if you don't supply the coerce parameter, it does > nothing. > > It's probably a slight API wart that TypedChoiceField doesn't just raise > an exception if you don't supply coerce(). The default is slightly > dangerous, as it almost always means you're misusing the field. Not a > fatal flaw in the design, however. > > > > > When I don't declare the status field at all (ie, just let django do > > it's default thing), my guess is that it is choosing a coerce function > > based on the integer type of my choices, is that true? > > Yes. The django.db.models.fields.Field.formfield() method detects if you > have specified "choices" in the field and uses the Field subclass's > to_python() function as the coerce method. > > > I have never > > used anything but sqlite3 so f
Re: Bug with model get_*_display() methods?
Right - of course. Don't ask me why didn't realize to use IntegerField ().to_python myself ... Margie On Aug 8, 12:32 pm, Alex Gaynor wrote: > On Sat, Aug 8, 2009 at 2:09 PM, Margie wrote: > > > Ok, still slightly confused. First - a high level description. I > > have a field that contains choices, but when I display the select, I > > want to display some extra html below the select box, so I am creating > > a custom widget that displays the standard select followed by my html. > > > Question: If want to use a special widget for a ChoiceField, is it > > true that I need to instantiate the ChoiceField (or TypedChoiceField), > > rather than just setting the .widget attribute on the one that is by > > default created for me (due to it being a modelForm)? > > > I find that if I just do this: > > > self.fields["status"].widget = StatusWidget(task=instance) > > > then my widget's select does not contain any choices. My widget > > doesn't do anything special to the select, it looks like this: > > > class StatusWidget(widgets.Select): > > def __init__(self, task, attrs={}): > > self.task = task > > super(StatusWidget, self).__init__(attrs) > > > def render(self, name, value, attrs=None): > > rendered = super(StatusWidget, self).render(name, value, > > attrs) > > rendered = rendered + add a bunch of stuff to the end > > return rendered > > > Because I seem unable to display the choices correctly in the select > > box when I just set the field's widget attribute to my StatusWidget, I > > am instantiating the field itself. That now looks like this: > > > self.fields["status"] = forms.TypedChoiceField > > (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), > > required=False, coerce=IntegerField.to_python) > > > However, I see when debugging that IntegerField.to_python is an > > unbound method: > > > (Pdb) self.coerce > > > > > What is the right thing to set coerce to if I just want it to do > > whatever it would "normally" do for the corresponding model field if I > > wasn't trying to override the widget? In my case I have verified that > > if I set coerce=int that does work, but that doesn't seem very > > general. I'd much rather use whatever the standard coerce method > > would have been if I hadn't overridden the widget. > > > Margie > > > On Aug 8, 12:11 am, Malcolm Tredinnick > > wrote: > >> Hi Margie, > > >> On Fri, 2009-08-07 at 23:17 -0700, Margie wrote: > > >> > Hmmm, ok, after digging around I realize that full_clean was not > >> > setting cleaned_data for the status field to an integer value; > >> > cleaned_data['status'] was just getting set to something like u'1'. > > >> > I am in fact using sqllite, and yes, my status fields are just > >> > integers: > > >> > OPEN_STATUS = 1 > >> > CLOSED_STATUS = 2 > >> > STALLED_STATUS = 3 > > >> > I think the problem has to do with the way I created the status field, > >> > which is like this: > > >> > self.fields["status"] = forms.ChoiceField > >> > (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), > >> > required=False) > > >> Right, that won't do what you want. ChoiceField normalizes to a unicode > >> object. > > >> > I tried moving to TypedChoiceField(), but that didn't help. I > >> > debugged into it in the case where I used TypedChoiceField() and I can > >> > see that when coerce is called it isn't doing anything, it is just > >> > returning the unicode value. > > >> > I find that if I do this instead, that it does do the coerce > >> > correctly: > > >> > self.fields["status"].widget = StatusWidget(task=instance) > > >> > In looking at the doc it looks like the purpose of TypedChoiceField() > >> > is to allow me to create my own coerce function, is that right? > > >> Correct. > > >> > And > >> > of course I wasn't doing that so it was behaving the same as > >> > ChoiceField, and it looks like the default there is to just return the > >> > unicode. > > >> Also correct. The documentation says "Defaults to an identity function" > >> and all the data coming from a form submission are strings (Pytho
Re: Bug with model get_*_display() methods?
Thanks for the pointers, that all make sense now. Margie On Aug 8, 6:47 pm, Malcolm Tredinnick wrote: > On Sat, 2009-08-08 at 12:09 -0700, Margie wrote: > > [...] > > > Question: If want to use a special widget for a ChoiceField, is it > > true that I need to instantiate the ChoiceField (or TypedChoiceField), > > rather than just setting the .widget attribute on the one that is by > > default created for me (due to it being a modelForm)? > > > I find that if I just do this: > > > self.fields["status"].widget = StatusWidget(task=instance) > > Grep'ing for "choices" in django/forms/*.py would reveal the answer to > this. Have a look at how the Select widget handles choices, since that > is what you're subclassing. > > The "choices" attribute of all the classes in widgets.py is set in the > __init__() method of each widget. In fields.py, have a look at > ChoiceField and you'll see that when you set choices on a field, they > are also set on the associated widget (there's a _set_choices() method > that is part of the "choices" property on ChoiceField). > > What you're doing in your above code is not setting any choices at all. > You need to tell the widget which choices it can use. > > [...] > > > However, I see when debugging that IntegerField.to_python is an > > unbound method: > > > (Pdb) self.coerce > > > > > What is the right thing to set coerce to if I just want it to do > > whatever it would "normally" do for the corresponding model field if I > > wasn't trying to override the widget? In my case I have verified that > > if I set coerce=int that does work, but that doesn't seem very > > general. I'd much rather use whatever the standard coerce method > > would have been if I hadn't overridden the widget. > > I'm not completely convinced this is a great plan, since if you are only > overriding the widget in __init__, then the coerce function will already > have been set up when the TypedChoiceField was created (it's a feature > of the forms.Field subclass, not the widget). If you are overriding the > form field entirely then you know better than Django what the correct > type to use is, so it's actually easier and arguably clearer to just put > in the right thing. > > However, you also have access to the model, so just use the > model._meta.fields[...] entry for the field and use the to_python() > method on that instance. Look at things like > django.db.models.options.Options.get_field_by_name(). > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: Reloading a page with new data
I have been able to mimic the admin behavior in my own app. I started off with the admin js functions showAddAnotherPopup and dismissAddAnotherPopup. Study these in the context of how they are used in the admin app and they should get you going. The best method for me was to use firebug and put breakpoints at the begninning of showAddAnotherPopup and dismissAddAnotherPopup and then print the variables in those functions. They basically encode the id of the input that you need filled in in the window name of of the popup window, and then when the popup is closed, then return an httpResponse that calls dismissAddAnotherPopup() and that extracts the window name of the popup, uses it to identify the id where to place the result, and then fills in the input appropriately. It is also useful to put a pdb breakpoint into the admin code in the response_add() function, ie: import pdb pdb.set_trace() This will make your server drop into pdb right before sending back the response that calls dismissAddAnother(). If you do all of this and then click on an "add another" (green "+") in the admin you should be able to trace the process they use. I thought it was all pretty slick myself. I don't have a ton of javascript experience, so am not sure if this is the best way to do things or not. There might be something simpler in jquery, please post if you do identify something simpler! This is not really in the realm of "django", since django doesn't really have much to do with the javascript side of things, but still, I'd be interested to know how others in this django community are creating popup windows that fill in information and then pass it back to some "main" window. Margie On Aug 13, 9:40 am, Thomas Scrace wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > Hi all, > > My app has a page where you can enter new data into the database through > a form. All is working well, except that some of the fields require a > choice from a drop down menu. If the choice for these fields the user > wants is not already in the database then they have to enter that new > choice. To facilitate that I have added a little '+' sign next the the > drop down which opens a new page where they can enter the new choice, > click save, and go back to the old page. > > It does work, but my problem is that, as you would expect, when they go > back to the original page the new choice does not show up in the drop > down menu. You have to refresh the page in order to get it to show up. > In addition, my new page shows up in a new tab, rather than a new > window as I intended (using 'target='_blank'). > > So, I need a way to: > > 1. Open a new window with a specified view. > 2. On clicking 'submit' in the new window, have the new window close > down and auto-reload the original page while retaining the information > already entered in other fields. > > It seems like this should be relatively simple, but I cannot find a way > to do it. I notice that Django's admin interface allows exactly this > functionality, and I have attempted to figure out their javascript but > with no success. Is there a more simple 'Djangofied' way to do this. > > Thanks very much for any help you can offer, > > - -- > Tom > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.9 (Darwin) > Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org/ > > iEYEARECAAYFAkqEQgsACgkQqeeO1ChsKHTOrgCg6W7JnbQEJsAXlwI0iYfAJuat > xe4An36q7vGtGFTzuM+IOF0xQJF10XEe > =7avd > -END PGP SIGNATURE- --~--~-~--~~~---~--~~ 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: Easy question
When you pass in an instance, when you later use the form.save() method, it will save any new data back to that instance. IE, if you pass in both an instance and POST data, it will basically give you a form that merges the instance data with the POST data, and now you can just save back to the instance. If you give just initial data, then I believe when you save it just creates a new object, since it is not bound to any existing object. If you give initial and POST data, then it will merge those together (with the post data winning) and create your new object based on that. Margie On Aug 13, 10:01 am, George Laskowsky wrote: > Hi, > > I was wondering about forms (and modelforms), what is the difference > between passing it an object (in the 'instance' attribute) and passing it an > dictionary with the same data (in the 'initial' attribute)? > > Thanks > -- > George Laskowsky Ziguilinsky --~--~-~--~~~---~--~~ 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: Success at using "reusable apps"?
That's a good idea. So you are suggesting, for example, that when the threadedcomment gets saved, that my app catch the post save signal and take its action then? I like that idea, I'm going to play around with that today. I hadn't thought about using signals before, but I guess that is the obvious solution to finding a way to do things in my own code without messing with the "reusable" app. Thanks for that suggestion! Margie On Aug 16, 10:41 pm, Andy McKay wrote: > On 16-Aug-09, at 8:50 PM, Margie Roginski wrote: > > > * modify the threadedcomments views.py code to take a callback > > function as an argument - that callback function could do my Task > > specific stuff as described above, but this would keep it more > > encapsulated within my Task app (but of course I would still have to > > modify threadecomments to take the callback arg) > > Or sounds like you could write a signal in your own code. > -- > Andy McKay > Clearwind Consulting:www.clearwind.ca > Blog:www.agmweb.ca/blog/andy > Twitter: twitter.com/clearwind --~--~-~--~~~---~--~~ 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: template syntax
I would convert your dictionary to a list of tuples. IE, in your views.py code studentTuples = [(student, dictionary.student.id) for student in students] Now in your template, to print out lines containing: student name: student id you can do this: {% for studentTuple in studentTuples %} {{studentTuple.0}} {{studentTuple.1}} {% endfor %} Margie On Aug 18, 8:48 am, elminio wrote: > I iterate through all students and have distionary containing students > ids as key and for example grade as a value. I pass this dictionary to > the view and then while iterating through all students I though that > it would be simple to get appropriate value for current student. I > dont know how I could make it simplier in template :/ If You think so > maybe any ideas? but please with sample code --~--~-~--~~~---~--~~ 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: explanation of: {{ action.action_time|date:_("DATETIME_FORMAT") }}
Ah, thank you very much! That makes more sense now. Margie On Aug 18, 4:30 pm, Ramiro Morales wrote: > On Tue, Aug 18, 2009 at 7:08 PM, Margie > > Roginski wrote: > > > I was trying to figure out how to run the date filter, using > > SETTINGS.DATETIME_FORMAT as an argument. > > > When I grepped in the admin app I found this in object_history.html: > > > {{ action.action_time|date:_("DATETIME_FORMAT") }} > > > Can anyone give me a pointer as to how this works? What is '_' in > > this case, and where is it defined? I see {% load il8n %}, but it is > > very hard to grep for '_', can seem to see where it is being defined > > there. > > Sure, the "DATETIME_FORMAT" literal is what we call a technical > message: A clever idea to give translators a way to determine > a few local-dependant info bits (usually date/time output formatting) > using the same infrastructure and tools used for translations > (hence the _()): > > http://docs.djangoproject.com/en/dev/topics/i18n/#id2 > > (last item in the list). > > If I understand things correctly, if/when Marc's GSoC work on this > front gets merged, in 1.2 this will be replaced by similar but > more explicit ways to specify the same info. > > HTH > > -- > Ramiro Moraleshttp://rmorales.net > > PyCon 2009 Argentina - Vie 4 y Sab 5 Setiembre > Buenos Aires, Argentinahttp://ar.pycon.org/2009/about/ --~--~-~--~~~---~--~~ 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 return an html snippet using ajax $.post()?
Ah - thank you! Yes, sorry, in the process of my debugging the issue and trying to simplify it, I unintentionally introduced even more errors, and then when posting it, even more! But you somehow despite that, managed to identify my real error, which was that I hadn't put the single quotes around {% get_my_url %}. I was clearly doing a spiral downward - thanks very much for your save! Margie On Aug 20, 2:40 pm, Matthias Kestenholz wrote: > On Thu, Aug 20, 2009 at 11:34 PM, Margie > > > > Roginski wrote: > > > Could someone give me a hand with a very simple ajax problem? I want > > to post some data and have the server just return a small snippet of > > html, which I then want to insert into my dom at a particular id. > > > Let's say the html snippet to be returned is just a string: hello > > world. > > > Does my views.py function just return it like this? > > > return HttpResponse("hello world") > > > I have some jquery on client side that is just trying trying to have > > the callback function throw the returned snippet up in an alert box, > > like this: > > > > > > I find that I never hit my callback function (the alert(data)). > > Instead the browser just replaces my with a page containing > > > hello > > > Could someone give me a pointer as to what I'm doing wrong? > > I'd say you get a javascript error in your onclick handler, this does > not look like a server error at all. You should probably add quotes > around the {% get_my_url %} stuff; or does this template tag add the > quotes itself? > > After reading the snippet for a second time, I've got to say it looks > quite messed up. This won't work. Try something like that: > > > > (Parentheses in $.post removed, # added in $('#id_comment'), added > quotes around {% get_my_url %} ) > > Matthias > > -- > FeinCMS Django CMS building toolkit:http://spinlock.ch/pub/feincms/ --~--~-~--~~~---~--~~ 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 return an html snippet using ajax $.post()?
Thanks for that example, Steve. I think I have made it past my problem, but it is always good to see what others are doing. In your example you have this: target.innerHTML = (eval(data)); Why do you use eval there? Isn't data just a string, something like '2009-08-21 11:41'? Margie On Aug 20, 3:59 pm, Steve Holden wrote: > Margie: > > Here's some code I Use to send the current date-time from a Django view into > a client-side form using AJAX (in this case jQuery, but I guess you can > substitute your Javascript extensions of choice. > > In the template: > > {% for report in my_reports %} > > {{ report.Name }} > {{report.ReportType.name}} > href="/generate/html/{{report.id}}/" > target="_blank">html > href="/generate/csv/{{report.id}}/">csv > href="/generate/pdf/{{report.id}}/" > target="_blank">pdf > {% if report.RunTime %}{{ > report.RunTime|floatformat:2}}{% endif %} > > Edit > href="/reports/delete/{{report.id}}/">Delete > > {{ report.ManualRunTS|date:"Y-m-d > H:i" }} > {% if report.NextRunDate %}{{ report.NextRunDate }}{% endif %} > > {% endfor %} > > Report NNN's runtime is displayed as the content of a id="runtime_NNN"/> element. > > The following jQuery code associates a click-processor with each of the > links: > > $("a[class^='rpt_']").click(function(){ > target = $(this).parent().parent().children().eq(8).children("span")[0]; > $.get("/reports/json/timestamp/", function(data) { > target.innerHTML = (eval(data)); > }); > }); > > When a link is clicked the jQuery expression assigns to target the span > element whose > content must be updated (to correctly show the new "last run time"). It then > uses the > jQuery $.get function to receive the (JSON) output of a call to the server > for its > current timestamp. This request is dispatched in the usual Django way, > connecting the > JavaScript to the following method: > > def timestamp(request,): > rdata = datetime.datetime.today().strftime("%Y-%m-%d %H:%M") > json = simplejson.dumps(rdata) > return HttpResponse(json, mimetype="application/json") > > The JavaScript dutifully evaluates the returned JSON [phobic security risk: > it would be > much better to use a JSON library for this] and replaces any current content > content > of the target span. > > Hope this helps. > > regards > Steve > > On Thu, Aug 20, 2009 at 5:34 PM, Margie Roginski > wrote: > > > > > > > Could someone give me a hand with a very simple ajax problem? I want > > to post some data and have the server just return a small snippet of > > html, which I then want to insert into my dom at a particular id. > > > Let's say the html snippet to be returned is just a string: hello > > world. > > > Does my views.py function just return it like this? > > > return HttpResponse("hello world") > > > I have some jquery on client side that is just trying trying to have > > the callback function throw the returned snippet up in an alert box, > > like this: > > > > > > I find that I never hit my callback function (the alert(data)). > > Instead the browser just replaces my with a page containing > > > hello > > > Could someone give me a pointer as to what I'm doing wrong? > > > Margie > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ --~--~-~--~~~---~--~~ 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 return an html snippet using ajax $.post()?
Yes, I have been learning and using jquery a lot lately. I find it really makes traversing around in the dom easy. Also, I have found some excellent plugins such as the cluetip pluging and datepicker plugins. All good stuff! Margie On Aug 20, 3:16 pm, Matthias Kestenholz wrote: > On Thu, Aug 20, 2009 at 11:53 PM, Margie wrote: > > > Ah - thank you! Yes, sorry, in the process of my debugging the issue > > and trying to simplify it, I unintentionally introduced even more > > errors, and then when posting it, even more! But you somehow despite > > that, managed to identify my real error, which was that I hadn't put > > the single quotes around {% get_my_url %}. > > > I was clearly doing a spiral downward - thanks very much for your > > save! > > No problem! I don't know if you know about it, but if you are doing > lots of ajax with forms, you should take a look at the jquery form > plugin[1]; I use it (nearly) all the time. (No disclaimer, it's not my > project and I'm not affiliated with it in any way.) > > Matthias > > [1]:http://malsup.com/jquery/form/ --~--~-~--~~~---~--~~ 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 deploy an app that gets used by people in multiple time zones
Thanks for the input. I have a couple questions. Both of you talk about saving the date/time in UTC format. What is the default when using a django DateTimeField? Does it not save it in UTC? If it is not saving it in UTC, what is it saving it in? I thought that one of the things the DateTimeField did for you was convert your input (whether form a user typed input or from a server call to datetime.datetime.now ()) into some sort of internal representation (UTC?). I thought that when I was using the date filter, that it was simply converting that internal representation into my specificied text format. Am I confused here? I thought about putting the timezone in the profile but that does have the disadvantage that if the user travels, they would have to update their profile to get dates displayed in whatever location they are at. I really don't like that since the people that will be using my app are management, and they often travel (and probably won't want to modify their profile all the time). One thing I thought about is trying to save the timezone info in the session. It seems like there should be a way to set a session variable at login time that reflects the current time zone and then have template tags that access that variable and generate the correct format based on the session variable.Is this a viable option? Since this is an internal site within a company, it is ok for me to require my users to have javascript on. Tim - i assume that with respect to your comment about javascript you are suggesting that identify the timezone via client javascript code and send it with every request? I thought I had read there was something going on in this area, possibly for django 1.2 but I can't remember what I saw about that ... Would be curious if there is anything planned for develpment in this area as I could possibly wait a few months to implement this if there was going to be some additional support coming on the django side. Margie On Sep 3, 3:02 pm, Tim Chase wrote: > > I've created a django app and I soon am going to have users that are > > in multiple timezones. My app is a task management system and it is > > important for users to see dates and times with respect to their own > > time zone. IE, if here in California I create a task at 3PM on Sept > > 3, I want someone in India to see it as being created at 1AM on Sept > > 4. Optimally, if that India employee travels to the US and looks at > > the task creation date, they should see 3PM on Sept 3. Is there a > > "best" way to handle this? Things that come to mind are: > > > 1. Create a deployment for each of my time zones where TIME_ZONE and > > DATE_FORMAT are set appropriately for the time zone associated with > > the deployment. This seems painful ... > > agreed...yuck! > > > 2. Have a single deployment and whenever I display dates, use some > > sort of tag that can figure out how to display the date correctly > > based on the user's time zone > > Best that I've found. It's best to store everything in the > database as UTC and then adjust the display for whatever the > relative timezone is. > > > 3. I see there is a reusable app called django-timezones. There is > > not much doc with it, but I'm guessing this is targeted at what I am > > trying to do. > > Not familiar with this one. > > The catch is that HTTP doesn't require the requester to send > their timezone information in the request. So you either have to > store the user's TZ in their user profile information, or you > have to use some client-side JavaScript to get the local TZ. > Both have problems -- If the client has JavaScript turned off (I > tend to fly with NoScript, only white-listing those sites I care > about to be able to run JS) you don't get this information back > from them. On the other side, if your customers travel from TZ > to TZ, they will have to update their profile each time they > move. Neither is a horrible solution, just with their own set of > hiccups. The two solutions can be combined to keep an "expected > TZ" in the user profile, but then take advantage of JS when > available to sniff the local PC's time-zone to override. > > Python's stock TZ handling is a little weak last I experimented > with it, expecting a single TZ for the entire running instance. > There's a library at pytz.sf.net that simplifies a lot of the TZ > pain I've experienced with Python's native datetime libraries. > It also gives good examples and cautions on things that can screw > you up (such as notifications set during a DST rollback time-slot). > > Hope this helps, > > -tim --~--~-~--~~~---~--~~ You received this m
Re: how to deploy an app that gets used by people in multiple time zones
I am using mysql. Can someone clarify what format dates and times are stored in when using just a standard DateTimeField? Is my timezone encoded in the database or is some generic, non-timezone-specific date/time stored? I don't understand why I would want to save my timezone along with my date/time. It seems to me that I should just be saving the generic form of the date/time and then rendering it in the format approriate for the user that it is being rendered for. IE, use the timezone only when rendering, not when saving. Margie On Sep 4, 12:22 am, Maksymus007 wrote: > On Thu, Sep 3, 2009 at 11:36 PM, Margie > > > > Roginski wrote: > > > I've created a django app and I soon am going to have users that are > > in multiple timezones. My app is a task management system and it is > > important for users to see dates and times with respect to their own > > time zone. IE, if here in California I create a task at 3PM on Sept > > 3, I want someone in India to see it as being created at 1AM on Sept > > 4. Optimally, if that India employee travels to the US and looks at > > the task creation date, they should see 3PM on Sept 3. Is there a > > "best" way to handle this? Things that come to mind are: > > > 1. Create a deployment for each of my time zones where TIME_ZONE and > > DATE_FORMAT are set appropriately for the time zone associated with > > the deployment. This seems painful ... > > > 2. Have a single deployment and whenever I display dates, use some > > sort of tag that can figure out how to display the date correctly > > based on the user's time zone > > > 3. I see there is a reusable app called django-timezones. There is > > not much doc with it, but I'm guessing this is targeted at what I am > > trying to do. > > > Can anyone give any recommendations? I'm happy to dive in and read > > source (ie, for django-timezones app), but I just want to make sure > > I'm heading in the right direction. > > > Thanks, > > have you tried to use postgres timestamp with time zone field? It has > ability to make such a conversion on the fly and every date can be > stored with timezone --~--~-~--~~~---~--~~ 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 deploy an app that gets used by people in multiple time zones
Tracy, Sorry for the delay, just got back from a short vacation. Thanks very much for your clarification. I think I now understand how to proceed! On Sep 7, 8:06 pm, Tracy Reed wrote: > On Thu, Sep 03, 2009 at 03:48:14PM -0700, Margie spake thusly: > > > What is the default when using a django DateTimeField? Does it not > > save it in UTC? If it is not saving it in UTC, what is it saving it > > in? > > Python has two kinds of DateTime objects: naive and > non-naive. Non-naive has timezone information with it. But the Django > DateTimeField can only handle naive DateTime objects since MySQL > cannot store time zones. So anytime you assign a time to a > DateTimeField you have to convert it to a standard timezone and UTC is > the most logical choice. > > > I thought that one of the things the DateTimeField did for you > > was convert your input (whether form a user typed input or from a > > server call to datetime.datetime.now ()) into some sort of internal > > representation (UTC?). > > I think it would be nice if it did this automatically since that is > the only thing that makes sense but it does not. Maybe someone out > there is able to be 100% sure that their data will always be the same > timezone so they don't want to inconvenience them by forcing > everything to UTC so they have to do a conversion to localtime when > they get their data back out. But I think such cases are exceedingly > rare. So we are all stuck converting to UTC before doing a .save() on > our models. > > > I thought that when I was using the date filter, that it was simply > > converting that internal representation into my specificied text > > format. Am I confused here? > > It does that but it does not do any timezone conversions. > > > I thought about putting the timezone in the profile but that does have > > the disadvantage that if the user travels, they would have to update > > their profile to get dates displayed in whatever location they are > > at. I really don't like that since the people that will be using my > > app are management, and they often travel (and probably won't want to > > modify their profile all the time). > > There is no way around this afaik. They need to learn to do timezone > conversions in their head or set a timezone in their profile. I label > the timezone displayed prominently so they know to make the adjustment > or change their profile. > > -- > Tracy Reedhttp://tracyreed.org > > application_pgp-signature_part > < 1KViewDownload --~--~-~--~~~---~--~~ 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 deploy an app that gets used by people in multiple time zones
Sorry for the delay in response - was on vacation for a few days. After reading up more on naive and aware timezones in python, this all makes more sense now. Thanks for your pointers, they were helpful. Margie On Sep 4, 9:03 am, Brian Neal wrote: > On Sep 4, 10:47 am, Margie wrote: > > > > > Can someone clarify what format dates and times are stored in when > > using just a standard DateTimeField? Is mytimezoneencoded in the > > database or is some generic, non-timezone-specific date/time stored? > > There is notimezoneencoded. The dates/times are said to be "naive". > > It is up to you to assign meaning to the time and to convert to the > appropriatetimezonefor your users. > > You should probably review this: > > http://docs.python.org/library/datetime.html > > Regards, > BN > > PS. The pytz library is useful for performing conversions between > timezones.http://pytz.sourceforge.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-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 -~--~~~~--~~--~--~---
problem altering a model and the corresponding table
I am trying to add an integer 'priority' field to one of my models I added the field like this in models.py: class Task(models.Model): PRIORITY_CHOICES = ( (1, _('1 (Critical)')), (2, _('2 (High)')), (3, _('3 (Normal)')), (4, _('4 (Low)')), (5, _('5 (Very Low)')), ) priority = models.IntegerField(choices=PRIORITY_CHOICES, default=3, blank=3, help_text=_('1 = Highest Priority, 5 = Low Priority'),) Then I modified the .db file (sqlite3) like this: > ALTER TABLE chipvision_task ADD COLUMN priority integer; But when I run syncdb (using a fixture generated off the the original db) I get an error: File "/tools/aticad/1.0/external/python-2.5.1/lib/python2.5/site- packages/django/utils/simplejson/decoder.py", line 208, in JSONObject raise ValueError(errmsg("Expecting property name", s, end - 1)) ValueError: Expecting property name: line 2178 column 3 (char 41357) Anyone know what I am doing wrong? I also tried adding the priority field to my .json fixture, but still get this error. Margie --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
deletion of "distant" related objects
I am having some trouble with the deletion of related objects that are multiple levels away from the object being deleted. I've read a bunch of stuff written on deletion of related objects, but nothing on this particular problem - hoping someone can help. Say I have a model like this: class Publisher(models.Model): name = models.CharField(max_length=100) class Book(models.Model): publisher = models.ForeignKey(Publisher, blank=True, null=True) class Reader(models.Model): book = models.ForeignKey(Book, blank=True, null=True) When a publisher is deleted, I would its book_set to be deleted, and this happens by default. However, when a book is deleted, either by deleting the book explicitely or due to its related publisher being deleted, I don't want the book's reader_set to be deleted. In Book I have this: class Book(models.Model): def delete(self): self.reader_set.clear() # make any readers of the book no longer reference the book to be deleted super(Book, self).delete() This works if I explicitly delete a book (ie, by "works", I mean that the book's readers stay around). However, if I delete a publisher, it seems that during Model::delete(), when _collect_sub_objects() runs, it runs through all of the related objects finds the related books, and then runs through the books' related objects and find the related readers. It targets them for deletion and then at some point they get deleted. It seems to me (I don't fully grock this code, so I could be wrong here) that by the time my Book::delete() code runs, the readers of the book have already been targeted for deletion and the self.reader_set.clear() is not having the effect I want. So I'm trying to figure out how I should avoid the readers getting deleted in this case? Thanks for any insights! Margie --~--~-~--~~~---~--~~ 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: deletion of "distant" related objects
I see. So then I think what you are saying is that if I want to avoid these "readers" getting deleted, prior to deleting my publisher I need to find all readers of the books publised by that publisher, and clear them out so that they are no longer readers of those books. Let's say that my Publisher and Book classes are in one app, and that app doesn't know anything about the readers. Is there any simple way to find all related object fields that point to book and clear them out, without having to know their names? One other thought - let me know if you see any issue with this. Let's say I just never want my reader objects to get deleted based on related object deletions. I think I can just define class Reader: def delete(self): pass Then delete will do nothing and if I really want to delete my reader I can call some other method that I define that then calls super(Reader, self).delete(). The actual object that is my "reader" (the above example was used just for simplicity) is really my UserProfile object. I would think that this is a common problem - not wanting one's userProfiles to ever get deleted. In my case my UserProfile contains a ForeignKey to a particular "Chip" object, identifying it as the "current chip" (ie, the one they want to be looking at). If that Chip gets deleted, I don't want my UserProfile to get deleted. As I write this, it occurs to me that another option would be to make the UserProfile contain a manytomany field that identifies the current chip (rather than a foreingKey). I think if I did that, I would not have this problem, right? Is there a down side to making it a ManyToMany field rather than a ForeignKey? It's misleading (since there can be only one current chip pointed at by the userprofile), but it seems to solve the problem. Margie On Apr 12, 12:06 am, Malcolm Tredinnick wrote: > On Sat, 2009-04-11 at 23:29 -0700, Margie wrote: > > I am having some trouble with the deletion of related objects that are > > multiple levels away from the object being deleted. I've read a bunch > > of stuff written on deletion of related objects, but nothing on this > > particular problem - hoping someone can help. > > > Say I have a model like this: > > > class Publisher(models.Model): > > name = models.CharField(max_length=100) > > > class Book(models.Model): > > publisher = models.ForeignKey(Publisher, blank=True, null=True) > > > class Reader(models.Model): > > book = models.ForeignKey(Book, blank=True, null=True) > > > When a publisher is deleted, I would its book_set to be deleted, and > > this happens by default. However, when a book is deleted, either by > > deleting the book explicitely or due to its related publisher being > > deleted, I don't want the book's reader_set to be deleted. In Book I > > have this: > > > class Book(models.Model): > > def delete(self): > > self.reader_set.clear() # make any readers of the book no longer > > reference the book to be deleted > > super(Book, self).delete() > > The basic problem you're up against here is that a model's delete() > method is not necessarily going to be run when it is deleted indirectly. > Django tries to optimise deletes and updates so that they are single (or > minimal numbers of) SQL queries, which means not calling a method on > each instance, but, rather, doing a bulk delete at the database level. > > This is documented, although it's one of those things that doesn't > immediately jump > out:http://docs.djangoproject.com/en/dev/topics/db/queries/#topics-db-que... > > (The queryset and model documentation is a bit all over the place at the > moment -- we need a few more links between places.) > > I think that's really going to be the showstopper here. You can't hope > to control the bulk delete (which includes related object deletion) at > that sort of level. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: deletion of "distant" related objects
> For a model such as Book, you could iterate through > Book._meta.get_all_field_names(), call Book._meta.get_field_by_name() > for each name and look at the "direct" component of the returned result > to see which are the reverse relations. Those are then the things > pointing to your model. > > There are docstrings on get_field_by_name() and get_all_field_names() in > django/db/models/options.py that will help you out there. > Great, this was very helpful. > > One other thought - let me know if you see any issue with this. Let's > > say I just never want my reader objects to get deleted based on > > related object deletions. I think I can just define > > > class Reader: > > def delete(self): > > pass > > > Then delete will do nothing and if I really want to delete my reader I > > can call some other method that I define that then calls super(Reader, > > self).delete(). > > That will work for a direct call. Isn't there going to be some related > object deletion cases that still won't be caught, though? Isn't this > exactly the case that you were examining in the initial post? Yes, of course you are right. I still hadn't fully grocked that delete () never get called in this case. I get that now. > Ultimately, Python is a language for consenting adults. If you don't > want the object to be deleted, don't call delete on things involving > that object. > Well, that seems a little heavy handed. I mean, when trying to create db driven web app, I think it is important to allow the users to delete the objects and not have bad side effects. That said, I understand that django is a developer's tool and there is always a workaround that a developer can come up with. I found one that works fine for my particular app. > It's understood that delete behaviour is something that has a few > different options. Coming up with a save API for controlling those which > doesn't leak SQL-juice all over the Python level code or make things > horribly an untenably inefficient, has been something we've been > wrestling with for quite a while. So far without really having a great > solution that we're happy committing. This isn't for want of actual hard > thinking on the problem by a number of people. > > For now, it's a matter of being careful and trusting your users to not > do crazy stuff. > > It's not optimal, but it is survivable. yup, agreed it is a hard problem. I appreciate that you guys no doubt have your hands full and am absolutely fine with dealing with it as is. Thanks for your pointers, they were very helpful and I've dug my self out of my hole. Margie --~--~-~--~~~---~--~~ 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: Send validation error message to the screen
Not sure if this is what you are looking for, but I use the notifications app to add some extra info to my html, to alert the user that there are errors in the form below or to let them know that there was no error and the form was submitted successfully. In view.py: request.notifications.create('Invalid data in form', 'error') # render form again In your html: {% if notifications %} {% for notification in notifications %} {{ notification.content }} {% endfor %} {% endif %} If you put this html in your base html (or some html that gets rendered for every page), then you can just create notifications in your view.py and they will always get displayed in the next page the user gets sent to. To make this work you need (in settings.py): MIDDLEWARE_CLASSES = ( 'notifications.middleware.NotificationMiddleware', TEMPLATE_CONTEXT_PROCESSORS = ( "notifications.context_processors.notifications", I believe I downloaded this from: http://code.google.com/p/django-notification/ Margie On Apr 12, 6:37 am, Joshua Partogi wrote: > Dear all, > > I want to send and display validation error message from the view to > the template, how do I do this in Django? I tried searching on the > documents but could not find any topics on error message. Could anyone > give me a hint on how to do this? > > Thank you very much > > -- > If you can't believe in God the chances are your God is too small. > > Read my blog:http://joshuajava.wordpress.com/ > Follow us on twitter:http://twitter.com/scrum8 --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
possible filter bug with manytomany fields and slice?
I am seeing some inconsistent behavior with a filter. It seems like when I filter a manytomany field out of a slice, I don't get correct filter results. Perhaps I am misunderstanding how to use filters with manytomany fields. I have a small program that shows an example. Here are the relevant parts of my model. class PdTask(models.Model): tiles = models.ManyToManyField('chipmanager.Tile') class Tile(models.Model): name=models.CharField(max_length=NAME_LENGTH) # There are 8 tiles in the db (Pdb) Tile.objects.all() [, , , , , , , ] # Create a pdtask named 'bar' (Pdb) pdtask = PdTask.objects.create(name="bar") # Add tile ll_1 to its tiles field (Pdb) pdtask.tiles.add(Tile.objects.get(name="ll_1")) # Confirm ll_1 was added (Pdb) pdtask.tiles.all() [] # Find all pdtasks that have an entry in tiles that is in Tile.objects.all() - should return bar and it does (Pdb) PdTask.objects.filter(tiles__in=Tile.objects.all()) [] # PROBLEM IS HERE # Find all pdtasks that have an entry in tiles that is in slice 0:4 of Tile.objects.all() # I think this should return bar as well, but it returns an empty list. WHY??? (Pdb) PdTask.objects.filter(tiles__in=Tile.objects.all()[0:4]) [] # Find all pdtasks that have an entry in tiles that is in the filtered list of Tile objects that start with 'll'. # I think this should return bar - and it does (Pdb) PdTask.objects.filter(tiles__in=Tile.objects.filter (name__startswith="ll")) [] # Find all pdtasks that have an entry in tiles that is in slice 0:4 of the the filtered list of Tile objects that # start with 'll'. I think this should return bar - and it does (Pdb) PdTask.objects.filter(tiles__in=Tile.objects.filter (name__startswith="ll")[0:4]) [] (Pdb) Am I using the __in filter correctly for a manytomany field? Margie --~--~-~--~~~---~--~~ 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: possible filter bug with manytomany fields and slice?
Ah - ok, cool, good to know. I am on 1.1 pre-alpha SVN-9814. Am moving soon to the 1.1. beta. I originally encountered this on a case that wasn't quite what I posted. I had a situation where I was guaranteed that my Task had only a single tile in the tiles field. So I was trying to filter like this: PdTask.objects.filter(tiles__in=pdTask.objects.all()[0]) IE, I was trying to find all PdTasks that contained a tile that was the same as the single tile in pdTask. Then I started experimenting and began to think that maybe I just didn't understand the manytomany queries at all - thought maybe I was doing it wrong. Anyway, your answer allayed my concerns - I have a workaround, no problem there, just didn't want to find that I was using the queries wrong in general. Malcolm - monitoring this group must be a full time job for you. Thank you so much for all of your responses. Margie On Apr 15, 11:39 pm, Malcolm Tredinnick wrote: > On Wed, 2009-04-15 at 23:13 -0700, Margie wrote: > > [...] > > > # PROBLEM IS HERE > > # Find all pdtasks that have an entry in tiles that is in slice 0:4 of > > Tile.objects.all() > > # I think this should return bar as well, but it returns an empty > > list. WHY??? > > (Pdb) PdTask.objects.filter(tiles__in=Tile.objects.all()[0:4]) > > [] > > Are you using Django 1.0.X here? Because nested queryset support only > exists in 1.1-beta and later. Tile.objects.all()[0:4] is a queryset in > that expression and so won't make sense as an rvalue in 1.0.X. > > If you are using 1.0.X, you could write that as: > > values = Tile.objects.values_list("id", flat=True)[0:4] > PdTask.objects.filter(tiles__in=values) > > or you could use the slightly ugly hack involving ".query" described in > [1] > > [1]http://docs.djangoproject.com/en/dev/ref/models/querysets/#in > > Also, I hope your Tasks model has a Meta.ordering specification, > otherwise you could well start seeing all sorts of unexpected (but > completely correct) results when using slices. Database servers are not > required to serve up results in any particular order (or even the same > order on successive queries) unless you specify an ordering. > > Regards, > Malcolm --~--~-~--~~~---~--~~ 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: setting a model field to null
blah.foo = None should do the trick On Apr 15, 8:01 pm, rvr wrote: > How can I set a model field to null after it has had a non-null value? > > -- > class Blah(models.Model): > foo = models.IntegerField(null=True) > > blah = Blah() > blah.foo = 5 > > # now set it to null > blah.foo = ??? > -- > > None doesn't seem to work and I don't seem to be able to figure this > out from the documentation. Thanks for your help. > > ~rvr --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---