Re: Dictionaries, templates and best practices
Couldn't you do: test = [] test.append({'title': 'My First Title', 'post': 'My First Post'}); test.append({'title': 'My Second Title', 'post': 'My Second Post'}); ? On Jun 18, 2008, at 4:11 PM, Juan Hernandez wrote: > it does not return any values. > > I did post.0.title because the dictionary is established like this: > > >>> test > {0: {'post': 'My First Post', 'title': 'My First Title'}, 1: > {'post': 'My Second Post', 'title': 'My Second Title'}} > > and it goes on and on > > If I could iterate over it, like post.0.title, then post.1.title and > so forth, it would be perfect > > Thanks for your help > > > On Wed, Jun 18, 2008 at 2:42 PM, Joel Bernstein <[EMAIL PROTECTED]> > wrote: > > I could be completely mistaken, but can't you replace 'post.0.title' > and 'post.0.post' with 'x.title' and 'x.post', respectively? > > On Jun 17, 1:50 pm, "Juan Hernandez" <[EMAIL PROTECTED]> wrote: > > Hey there > > > > I've been practicing for a while with the template system and I > have some > > questions: > > > > Lets say that I create this dictionary: > > > > test = dict() > > test[0] = {'title': 'My First Title', 'post': 'My First Post'} > > test[1] = {'title': 'My Second Title', 'post': 'My Second Post'} > > etc... til 10 for example > > > > If i want to display that information, the best way would be to > iterate over > > each number and show 'title' and 'post'. > > > > My question is: How can I actually iterate over a dictionary like > this > > inside a template? If i do this (assuming that the shown > dictionary has been > > assigned to 'post' in render_to_response) > > > > {% for x in post%} > > {{ post.0.title }}^M > > > > > >{{ post.0.post }}^M > > > > It will only show the first part of the dictionary and 'x' as a > number > > cannot be handled. I haven't found a way to have an increasing > number to > > iterate with... Something to replace the zero that increases until > is > > finished by hte condition > > > > What would be the best way to display the whole dictionary in a > template?? > > > > Thank you very much as usual > > jhv > > > > > --- David Zhou [EMAIL PROTECTED] --~--~-~--~~~---~--~~ 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: Template Tag caveat
A quick follow up on this post. I forgot to explain how to avoid the problem. To avoid the problem is to treat self as read only. So to fix the ReprNode, you'd simply do the following: class ReprNode(template.Node): def __init__(self, obj_expression) # Let's name this more accurately self.obj_expression = obj_expression def render(self, context): # Use a local variable instead of a object attribute obj = template.resolve_variable(self.obj_expression, context) return str(obj) On Jun 17, 6:14 pm, Eric <[EMAIL PROTECTED]> wrote: > This isn't a bug but it's something that might need to be documented > to prevent folks from doing something that may hurt them later: > > In the Django template system. There is a small caveat that you need > to > recognize when developing your own template tags. > > When Django parses the Node tree it creates a template.Node instance > for > each template tag in the template. The node tree is just like our > beloved > HTML DOM. > > So for instance take the following:: > > > 1 > 2 > 3 > 4 > 5 > > > That turns into something like this:: > > > > > > > > > The indention shows that the li's are child nodes of the ul tag. Each > li in a > different instance of an HTMLElement, each with their own state. > > So for a Django Template take the following:: > > {% block content %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% endblock %} > > The node tree would look like this:: > > > > > > > > So we have a block node with four FirstOfNode instances > > In python this would translate roughly to:: > > f1 = FirstOfNode(...) > f2 = FirstOfNode(...) > f3 = FirstOfNode(...) > f4 = FirstOfNode(...) > > f1.render() > f2.render() > f3.render() > f4.render() > > Everything looks fine here. Render is called once per node instance. > > Now, check this out:: > > {% block content %} > {% for i in value_list %} In the Django template system. There > is a small caveat that you need to > recognize when developing your own template tags. > > When Django parses the Node tree it creates a template.Node instance > for > each template tag in the template. The node tree is just like our > beloved > HTML DOM. > > So for instance take the following:: > > > 1 > 2 > 3 > 4 > 5 > > > That turns into something like this:: > > > > > > > > > The indention shows that the li's are child nodes of the ul tag. Each > li in a > different instance of an HTMLElement, each with their own state. > > So for a Django Template take the following:: > > {% block content %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% firstof var1 var2 var3 %} > {% endblock %} > > The node tree would look like this:: > > > > > > > > So we have a block node with four FirstOfNode instances > > In python this would translate roughly to:: > > f1 = FirstOfNode(...) > f2 = FirstOfNode(...) > f3 = FirstOfNode(...) > f4 = FirstOfNode(...) > > f1.render() > f2.render() > f3.render() > f4.render() > > Everything looks fine here. Render is called once per node instance. > > Now, check this out:: > > {% block content %} > {% for i in value_list %} > {% repr obj %} > {% endfor %} > {% endblock %} > > The node tree that django builds would look something like this:: > > > > > > Now each node in that tree is it's own object instance with it's own > state. This can be an issue if you don't realize one thing, each node > is persistent while the template is rendering. > > Let me write out how the template rendering of the a loop would look > in python with the ReprNode:: > > repr_node = ReprNode("obj") > > for i in range(10): > repr_node.render(context) > > Can you tell what the problem? We're calling the render method > on the same instance of the Node. > > Let's peek under the covers and look at ReprNode's definition:: > > class ReprNode(template.Node): > def __init__(self, obj) > self.obj = obj > > def render(self, context): > self.obj = template.resolve_variable(self.obj, context) > return str(self.obj) > > def do_repr(parser, token): > tag_name, obj = token.split_contents() > return ReprNode(obj) > > Now look at what's going on. self.obj is assumed to be the name of > the > variable in the context. That's fine when render is called once. > When render > called a second time, self.obj is now the actual value of obj from the >
Using FileField and existing files
Newbie alert. I have a model which contains a FileField. The standard way I'd like this field to be 'filled' is in code, rather than by user interaction but there are circumstances where it needs to have a standard 'upload- from-form' behaviour. The code method generates a file in an accessible place on the file system. My question, after some time searching Google and this group and failing to find an answer, is: how do I manipulate the FileField so that it is properly set to my existing file? That is, I want it to behave as if a user uploaded the file, except I've done it in code instead. For what it's worth, I'm using the SVN version, current as of about a week ago. Thanks in advance, Anthony. --~--~-~--~~~---~--~~ 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: Start server
Molly: When you get through, mind if you could share the code? Thank you, Joseph http://www.jjude.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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: correct list for newforms admin questions? named urls / replacing admin root page
Hi Norman, On Jun 17, 2008, at 3:49 PM, Norman Harman wrote: > > I want to use {% url %} to point into portions of the admin site(and > change the default url structure). I hacked this generally > unfullfilling but working version with old admin. This is not yet supported in the newforms-admin branch. See ticket #6470 [1]. At this point your best bet is to hardcode the URLs. [1]:http://code.djangoproject.com/ticket/6470 Brian Rosner http://oebfare.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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: serve static files
I think I may have figured out the problem.. I needed my admin_media folder to be in my media folder Thanks for the help :) I appreciate both of your responses! Molly On Jun 17, 1:37 pm, "Norman Harman" <[EMAIL PROTECTED]> wrote: > Molly wrote: > > How would I call the static file in my browser?? > > By typing in the url to the static file directly in the address bar. > > For example if your server is example.com, root of django app is myapp, > and images are in img dir, and image is named myjp.jpg the url would be > > http:://example.com/myapp/media/img/myjpg.jpg > > From your description it sounds like the css is not being found. I'd > look in the HTML source(as seen by browser, with firefox ctrl-u, with IE > install Firefox) find line(s) that include css. They probably look > something like this. > > href="http://yui.yahooapis.com/2.3.1/build/calendar/assets/calendar.css; /> > > then see if you access(copy it to address bar, hit > return)http://yui.yahooapis.com/2.3.1/build/calendar/assets/calendar.css > > Either the url(s) in your templates point to wrong place, or the > urls/document_roots in urlpatterns are wrong, or something else is wrong ;) > > btw hard coding a path "C:\dev\incidents\admin_media" in your > urlpatterns is probably a bad thing to do. As whoever uses your > app/where ever you deploy it for production is unlikely to install the > app in the same place you do on your dev machine. > > -- > Norman J. Harman Jr. > Senior Web Specialist, Austin American-Statesman > ___ > You've got fun! Check out Austin360.com for all the entertainment > info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
TextField default String problem
I have two fields in a model, a name (CharField) and a description (TextField). I'm trying to set the default description to be something simple like: default="hello, I'm the description of the %s" % name (To my surprise) this validates, but the description includes a reference to the name field, not it's value, resulting in: "hello, I'm the description of the " I want to get an affect similar to that of prepopulate_from, but Django's documentation isn't being that useful. Is there no [field].value property? Can anyone help me out? 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: unit testing and comparing dictionaries
sorry, omitted 'self' by accident. There are a couple things going on here. One is that type-o. The other is more of an open question as to what should be tested, and how. I'm coming around to the this. for each model I'll will 1) assume that clients that use the model code will test it indirectly. 2) test that nullable fields accept nulls (Perhaps this isn't necessary - see 1) 3) test that unique constraints can't be violated. 4) test that all business methods function properly (with probably the exception of __unicode__ Basically, if I can forget to state that model field should be unique, then I can accidently remove that too. I'd like to have a test cover it. But, if you leave off a whole field, some other test should fail, or perhaps your app doesn't need the field. (Note this is somewhat stream of thinking, and I'm not an expert at Python or Django!) On Wed, Jun 18, 2008 at 10:06 AM, Paul Winkler <[EMAIL PROTECTED]> wrote: > > On Jun 17, 1:46 am, "Gene Campbell" <[EMAIL PROTECTED]> wrote: >> Hello Djangonauts >> >> I'm a noob on both Django and Python, so this question might be easy >> for the experts out there. I am trying to do test first development >> during the development of my model code. (I have lots of experience >> with test first coding in the Java world, no practical experience in >> the Py world.) >> >> I want to do something like this >> >> class ModelTest(TestCase): >> >> def test_crud_modelone(self): >> mo = ModelOne( name="A name" ) >> mo.save() >> >> saved_mo = mo.objects.get(pk=mo.id) >> >> assertEqual( vars(mo), vars(saved_mo),"Something not getting saved") >> >> That assertEqual line fails. I wrote this > > You didn't say what exactly happens. If it's failing with a NameError, > notice that you forgot to specify self.assertEqual(). > There's no implicit "this" like in Java. > > And as others have mentioned, vars() is rarely used in practice. > And if there's a problem, it'll be hard to see what's wrong. > It's more tedious but ultimately more helpful to specify everything: > >self.assertEqual(mo.foo, saved_mo.foo) >self.assertEqual(mo.bar, saved_mo.bar) > > ... and so forth. > > Also, as a fellow django noob I'm not sure about this, but I seem to > recall that mo and saved_mo should be exactly the same object? > If that's true (hopefully somebody will correct me if not), it's kind > of a silly test; you might instead just do > > self.failUnless(mo is saved_mo) > > > -- PW > > > --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Template Tag caveat
This isn't a bug but it's something that might need to be documented to prevent folks from doing something that may hurt them later: In the Django template system. There is a small caveat that you need to recognize when developing your own template tags. When Django parses the Node tree it creates a template.Node instance for each template tag in the template. The node tree is just like our beloved HTML DOM. So for instance take the following:: 1 2 3 4 5 That turns into something like this:: The indention shows that the li's are child nodes of the ul tag. Each li in a different instance of an HTMLElement, each with their own state. So for a Django Template take the following:: {% block content %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% endblock %} The node tree would look like this:: So we have a block node with four FirstOfNode instances In python this would translate roughly to:: f1 = FirstOfNode(...) f2 = FirstOfNode(...) f3 = FirstOfNode(...) f4 = FirstOfNode(...) f1.render() f2.render() f3.render() f4.render() Everything looks fine here. Render is called once per node instance. Now, check this out:: {% block content %} {% for i in value_list %} In the Django template system. There is a small caveat that you need to recognize when developing your own template tags. When Django parses the Node tree it creates a template.Node instance for each template tag in the template. The node tree is just like our beloved HTML DOM. So for instance take the following:: 1 2 3 4 5 That turns into something like this:: The indention shows that the li's are child nodes of the ul tag. Each li in a different instance of an HTMLElement, each with their own state. So for a Django Template take the following:: {% block content %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% firstof var1 var2 var3 %} {% endblock %} The node tree would look like this:: So we have a block node with four FirstOfNode instances In python this would translate roughly to:: f1 = FirstOfNode(...) f2 = FirstOfNode(...) f3 = FirstOfNode(...) f4 = FirstOfNode(...) f1.render() f2.render() f3.render() f4.render() Everything looks fine here. Render is called once per node instance. Now, check this out:: {% block content %} {% for i in value_list %} {% repr obj %} {% endfor %} {% endblock %} The node tree that django builds would look something like this:: Now each node in that tree is it's own object instance with it's own state. This can be an issue if you don't realize one thing, each node is persistent while the template is rendering. Let me write out how the template rendering of the a loop would look in python with the ReprNode:: repr_node = ReprNode("obj") for i in range(10): repr_node.render(context) Can you tell what the problem? We're calling the render method on the same instance of the Node. Let's peek under the covers and look at ReprNode's definition:: class ReprNode(template.Node): def __init__(self, obj) self.obj = obj def render(self, context): self.obj = template.resolve_variable(self.obj, context) return str(self.obj) def do_repr(parser, token): tag_name, obj = token.split_contents() return ReprNode(obj) Now look at what's going on. self.obj is assumed to be the name of the variable in the context. That's fine when render is called once. When render called a second time, self.obj is now the actual value of obj from the context. What happens when you try to resolve that? You get a VariableDoesNotExist error, uh oh! The assumption that render() is only called once. You don't realize that inside a for tag, the render method is called repeatedly. This can cause issues if you assume render will only be called once. I don't know if this is technically a bug in the Django templating system, bad design, bad documentation, or just simply poor assumptions on my part. {% repr obj %} {% endfor %} {% endblock %} The node tree that django builds would look something like this:: Now each node in that tree is it's own object instance with it's own state. This can be an issue if you don't realize one thing, each node is persistent while the template is rendering. Let me write out how the template rendering of the a loop would look in python with the ReprNode:: repr_node = ReprNode("obj") for i in range(10):
Re: unit testing and comparing dictionaries
On Jun 17, 1:46 am, "Gene Campbell" <[EMAIL PROTECTED]> wrote: > Hello Djangonauts > > I'm a noob on both Django and Python, so this question might be easy > for the experts out there. I am trying to do test first development > during the development of my model code. (I have lots of experience > with test first coding in the Java world, no practical experience in > the Py world.) > > I want to do something like this > > class ModelTest(TestCase): > > def test_crud_modelone(self): > mo = ModelOne( name="A name" ) > mo.save() > > saved_mo = mo.objects.get(pk=mo.id) > > assertEqual( vars(mo), vars(saved_mo),"Something not getting saved") > > That assertEqual line fails. I wrote this You didn't say what exactly happens. If it's failing with a NameError, notice that you forgot to specify self.assertEqual(). There's no implicit "this" like in Java. And as others have mentioned, vars() is rarely used in practice. And if there's a problem, it'll be hard to see what's wrong. It's more tedious but ultimately more helpful to specify everything: self.assertEqual(mo.foo, saved_mo.foo) self.assertEqual(mo.bar, saved_mo.bar) ... and so forth. Also, as a fellow django noob I'm not sure about this, but I seem to recall that mo and saved_mo should be exactly the same object? If that's true (hopefully somebody will correct me if not), it's kind of a silly test; you might instead just do self.failUnless(mo is saved_mo) -- PW --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
correct list for newforms admin questions? named urls / replacing admin root page
I want to use {% url %} to point into portions of the admin site(and change the default url structure). I hacked this generally unfullfilling but working version with old admin. model = dict(app_label="specials", model_name="adspecial") urlpatterns += patterns("django.contrib.admin.views.main", url(r"^$", "change_list", name="ts_admin_special_list", kwargs=model), url(r"^add/$", "add_stage", name="ts_admin_special_add", kwargs=model), url(r"^(?P\d+)/$", "change_stage", name="ts_admin_special_edit", kwargs=model), ... ) Not sure how to do this with newforms. I got this to work, but I really don't want to make wrappers to get the dynamic urls to work. url(r"^$", site.root, name="ts_admin", kwargs={"url":"specials/adspecial"}), Actually, I'd really love to learn a cleaner way to do this. Main goals are to have a custom admin "index" page, and not hard code urls. Thanks, -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: Dictionaries, templates and best practices
Oops, I totally missed that 'test' was a dictionary. This should work then: {% for key, x in posts.items %} {{ x.title }} {{ x.post }} {% endfor %} Alternately, if your keys are just going to be sequential integers, you could just put this stuff into a list and use my first suggestion. On Jun 17, 3:41 pm, "Juan Hernandez" <[EMAIL PROTECTED]> wrote: > it does not return any values. > > I did post.0.title because the dictionary is established like this: > > >>> test > > {0: {'post': 'My First Post', 'title': 'My First Title'}, 1: {'post': 'My > Second Post', 'title': 'My Second Title'}} > > and it goes on and on > > If I could iterate over it, like post.0.title, then post.1.title and so > forth, it would be perfect > > Thanks for your help > > On Wed, Jun 18, 2008 at 2:42 PM, Joel Bernstein <[EMAIL PROTECTED]> wrote: > > > I could be completely mistaken, but can't you replace 'post.0.title' > > and 'post.0.post' with 'x.title' and 'x.post', respectively? > > > On Jun 17, 1:50 pm, "Juan Hernandez" <[EMAIL PROTECTED]> wrote: > > > Hey there > > > > I've been practicing for a while with the template system and I have some > > > questions: > > > > Lets say that I create this dictionary: > > > > test = dict() > > > test[0] = {'title': 'My First Title', 'post': 'My First Post'} > > > test[1] = {'title': 'My Second Title', 'post': 'My Second Post'} > > > etc... til 10 for example > > > > If i want to display that information, the best way would be to iterate > > over > > > each number and show 'title' and 'post'. > > > > My question is: How can I actually iterate over a dictionary like this > > > inside a template? If i do this (assuming that the shown dictionary has > > been > > > assigned to 'post' in render_to_response) > > > > {% for x in post%} > > > {{ post.0.title }}^M > > > > > > > > > {{ post.0.post }}^M > > > > It will only show the first part of the dictionary and 'x' as a number > > > cannot be handled. I haven't found a way to have an increasing number to > > > iterate with... Something to replace the zero that increases until is > > > finished by hte condition > > > > What would be the best way to display the whole dictionary in a > > template?? > > > > Thank you very much as usual > > > jhv --~--~-~--~~~---~--~~ 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: Adding suggest / accept functionality to models
Dan wrote: > There is a functionality which I am interested in and I wonder what is > the cleanest and most foward compatible way of doing things. > > I want models to sprout a suggest() method which would work like > save() but keep the data in some structure elsewhere that do not > modify the original data. Any regular call to that object would work > as if it wasn't modified. I also want a accept() method that would > commit the changes (and obviously a reject() method to discard them > and some way to explore the suggested changes). > > I am not interested in history at all. > > How would you go about implementing those functionalities? First guess, curious if others think its good idea. Create model with one2one nullable field "suggestion" and Boolean field "is_suggestion". If suggestion is Null then there is no suggestion. If suggestion is not Null it is id of suggested data. The idea is to avoid maintaining two duplicate schemas. Proly change the default Manager to only show is_suggestion == False rows. def suggest(self, obj): """obj is original obj self is suggestion for"" self.is_suggestion = True self.suggestion = obj self.save() def accept(self): "accept this suggestion" assert self.is_suggestion # need more logic if model has foriegn relationships self.suggestion.delete() self.suggestion = None self.is_suggestion = False def reject(self): assert self.is_suggestion # not sure how to delete relation # self.suggestion.suggestion = None ??? self.delete() -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: Dictionaries, templates and best practices
Juan Hernandez wrote: > it does not return any values. > > I did post.0.title because the dictionary is established like this: > > >>> test > {0: {'post': 'My First Post', 'title': 'My First Title'}, 1: {'post': > 'My Second Post', 'title': 'My Second Title'}} > > and it goes on and on > > If I could iterate over it, like post.0.title, then post.1.title and so > forth, it would be perfect > > Thanks for your help Don't construct dict like that, make a list instead. [ {'post': 'My First Post', 'title': 'My First Title'}, {'post': ... ] Or, if you don't have control over dict construction, munge it into list. If order isn't important: list_o_dicts = dict_that_should_be_list.values() If order is important: list_o_dicts = [ dict_that_should_be_list[k] for k in sorted(dict_that_should_be_list.keys()) ] Then you can use the template for loop construct normally {% for dict in list_o_dicts %} {{ dict.post }} {{ dict.title }} {% endfor %} -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: unit testing and comparing dictionaries
Gene Campbell wrote: > Thanks for the insight! Do you write tests to check for constraints > that are optional in definitions, for example? > > address4= models.CharField(max_length=45, null=True, blank=True) > > could be written as > > address4= models.CharField(max_length=45) > > Were is the most reasonable place to test this is correct (not regressing) I'm not sure. I'm distraught over having validations in two places the model and forms that "feed" that model. And form_from_model or whatever it is called is never what I want. I tend to test the forms as I tend to manipulate models through forms and the forms support much richer validations than FooFields do. Blank is an admin thing and I typically don't test those. Testing Nullable field(s) would be data point(s) in creation/save test. > What about uniqueness, and composite field uniqueness? > # unique_together = (("field1", "field2","field3"),) > > I'm thinking it would make sense to try to > create 2 of an object and save them, and check that it fails Yep two of the objects whose 3 fields are not unique together. -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: Media variables confusion
Generally, Django could not care less where you put most of your static media files. There are two main exceptions, though: 1. Django needs to know the URL to the media files for its admin application (ADMIN_MEDIA_PREFIX) 2. Django needs to know where in the server's filesystem it should put newly uploaded files (MEDIA_ROOT) and what URL they'll show up at afterward (MEDIA_URL). If you don't use the admin application, you can safely ignore ADMIN_MEDIA_PREFIX. If none of your applications' models include any file-upload fields, you can safely ignore MEDIA_ROOT and MEDIA_URL. On Jun 17, 2:27 pm, "Alaa Salman" <[EMAIL PROTECTED]> wrote: > Hey guys, > > So i am a little confused by the MEDIA_ROOT, MEDIA_URL, and > ADMIN_MEDIA_PREFIX variables. > > I understand that the ADMIN_MEDIA_PREFIX provides the prefix. But so what if > it was on another url? I am assuming that the common use case is to serve > them from the same domain, which is what i am doing. But just in case... > > Also, why do we need a MEDIA_ROOT as a path to a directory if we can use the > static.serve view during development? And then so why are both the MEDIA_URL > and MEDIA_ROOT needed? > > As you can see, I'm a little confused by these settings and have managed to > develop with using them this far. So any explanation is appreciated. I find > the documentation a little lacking in explaining these vars. > > Regards, > Alaa Salmanhttp://www.codedemigod.com > FSF Member #6304 > "Never measure the height of a mountain until you have reached the top. Then > you will see how low it was." ---Dag Hammarskjold --~--~-~--~~~---~--~~ 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: Implementing a new idea
Did you take a look at Django Signals? You can intercept pre-save and post-save objects with them. You can use that to grab the data you want and fill your ProjectModification object. I don't know if there is a way you could tell if it was done in the admin or not though... --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Adding suggest / accept functionality to models
There is a functionality which I am interested in and I wonder what is the cleanest and most foward compatible way of doing things. I want models to sprout a suggest() method which would work like save() but keep the data in some structure elsewhere that do not modify the original data. Any regular call to that object would work as if it wasn't modified. I also want a accept() method that would commit the changes (and obviously a reject() method to discard them and some way to explore the suggested changes). I am not interested in history at all. How would you go about implementing those functionalities? --~--~-~--~~~---~--~~ 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: Dictionaries, templates and best practices
it does not return any values. I did post.0.title because the dictionary is established like this: >>> test {0: {'post': 'My First Post', 'title': 'My First Title'}, 1: {'post': 'My Second Post', 'title': 'My Second Title'}} and it goes on and on If I could iterate over it, like post.0.title, then post.1.title and so forth, it would be perfect Thanks for your help On Wed, Jun 18, 2008 at 2:42 PM, Joel Bernstein <[EMAIL PROTECTED]> wrote: > > I could be completely mistaken, but can't you replace 'post.0.title' > and 'post.0.post' with 'x.title' and 'x.post', respectively? > > On Jun 17, 1:50 pm, "Juan Hernandez" <[EMAIL PROTECTED]> wrote: > > Hey there > > > > I've been practicing for a while with the template system and I have some > > questions: > > > > Lets say that I create this dictionary: > > > > test = dict() > > test[0] = {'title': 'My First Title', 'post': 'My First Post'} > > test[1] = {'title': 'My Second Title', 'post': 'My Second Post'} > > etc... til 10 for example > > > > If i want to display that information, the best way would be to iterate > over > > each number and show 'title' and 'post'. > > > > My question is: How can I actually iterate over a dictionary like this > > inside a template? If i do this (assuming that the shown dictionary has > been > > assigned to 'post' in render_to_response) > > > > {% for x in post%} > > {{ post.0.title }}^M > > > > > >{{ post.0.post }}^M > > > > It will only show the first part of the dictionary and 'x' as a number > > cannot be handled. I haven't found a way to have an increasing number to > > iterate with... Something to replace the zero that increases until is > > finished by hte condition > > > > What would be the best way to display the whole dictionary in a > template?? > > > > Thank you very much as usual > > jhv > > > --~--~-~--~~~---~--~~ 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: unit testing and comparing dictionaries
Thanks for the insight! Do you write tests to check for constraints that are optional in definitions, for example? address4= models.CharField(max_length=45, null=True, blank=True) could be written as address4= models.CharField(max_length=45) Were is the most reasonable place to test this is correct (not regressing) What about uniqueness, and composite field uniqueness? # unique_together = (("field1", "field2","field3"),) I'm thinking it would make sense to try to create 2 of an object and save them, and check that it fails On Wed, Jun 18, 2008 at 7:59 AM, John <[EMAIL PROTECTED]> wrote: > > Dictionaries compare equal if they contain the same data, regardless > of key order. There is no need to convert to sorted sequences unless > you need to compare the serialized output (such as in doctests). > > I would guess that one of the models has additional fields added to > its __dict__, perhaps through some caching mechanism. Try printing > ``vars(mo)`` and ``vars(saved_mo)``, and then examine the output > manually. If you truly wish to examine two model objects for equality, > you could try the appended code[1] > > However, I would advise that you remove your test entirely. It is > without point, as Django's unit testing already covers the behavior of > ``Model.send()``. Restrict testing to your own code, before you go mad > "sanity checking" the massive pile of third-party code underlying > yours. > > [1] > -- > assertEqual (type (mo), type (saved_mo)) > > # Retrieve a list of database model field names > attrs = [f.attname for f in mo._meta.fields] > > # Construct lists based on the model attributes, and compare them > mo_attrs = [getattr (mo, a) for a in attrs] > saved_mo_attrs = [getattr (saved_mo, a) for a in attrs] > assertEqual (mo_attrs, saved_mo_attrs) > -- > > > --~--~-~--~~~---~--~~ 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: Media variables confusion
You need MEDIA_ROOT because yes, you serve it from static.serve view during development but when you launch you do not want to be using the devserver to display your site. MEDIA_URL is essentially the same url you map through Apache, lighthttpd, whatever you use But you are right, you can use the dev server to setup where your media is but once you go onto a more public launch viewing you will want to switch using Apache / mod_python combo or something else. This describes it pretty well: http://www.djangoproject.com/documentation/modpython/#serving-media-files On Tue, Jun 17, 2008 at 3:27 PM, Alaa Salman <[EMAIL PROTECTED]> wrote: > Hey guys, > > So i am a little confused by the MEDIA_ROOT, MEDIA_URL, and > ADMIN_MEDIA_PREFIX variables. > > I understand that the ADMIN_MEDIA_PREFIX provides the prefix. But so what > if it was on another url? I am assuming that the common use case is to serve > them from the same domain, which is what i am doing. But just in case... > > Also, why do we need a MEDIA_ROOT as a path to a directory if we can use > the static.serve view during development? And then so why are both the > MEDIA_URL and MEDIA_ROOT needed? > > As you can see, I'm a little confused by these settings and have managed to > develop with using them this far. So any explanation is appreciated. I find > the documentation a little lacking in explaining these vars. > > > Regards, > Alaa Salman > http://www.codedemigod.com > FSF Member #6304 > "Never measure the height of a mountain until you have reached the top. > Then you will see how low it was." ---Dag Hammarskjold > > > --~--~-~--~~~---~--~~ 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: unit testing and comparing dictionaries
Thanks. In this case, I'm doing a bit extra in work order to learn Python and Django. And, I do see how testing models such that all the fields are equal is a waste on the basis that Django should be testing that that functionality works. On Wed, Jun 18, 2008 at 2:48 AM, Norman Harman <[EMAIL PROTECTED]> wrote: > > Gene Campbell wrote: >> Hello Djangonauts >> >> I'm a noob on both Django and Python, so this question might be easy >> for the experts out there. I am trying to do test first development >> during the development of my model code. (I have lots of experience >> with test first coding in the Java world, no practical experience in >> the Py world.) >> >> I want to do something like this >> >> class ModelTest(TestCase): >> >> def test_crud_modelone(self): >> mo = ModelOne( name="A name" ) >> mo.save() >> >> saved_mo = mo.objects.get(pk=mo.id) >> >> assertEqual( vars(mo), vars(saved_mo),"Something not getting saved") >> >> That assertEqual line fails. I wrote this >> >> def compare(self, obj1, obj2, verbose = False): >> other = vars(obj2) >> for d,v in vars(obj1).items(): >> if isinstance(other.get(d,None),datetime.date): >> if not other.get(d,None) == v.date(): >> return False >> elif not other.get(d,None) == v: >> return False >> >> return True >> >> This is probably horrible python, I'm still learning (unlearning >> Java), but it compares correctly for strings and dates so far that >> I've tested. > I've been using python since 1.5, I had to look up what vars() did. > Probably not idiomatic Python. (I've always just looked at __dict__ > directly, which I do rarely). > > The assertEqual line (probably) fails because the order of dictionary > keys is not defined. > > > Some might be asking why I'm testing if my models can be saved, as > > most of that functionality is tested when Django is tested. But, I > > still feel there's a enough that I have to write to warrant a simple > > sanity test like this. > > FWIW I believe testing what you're testing is a waste of time and > violates unit testing. Really the db should be mocked, but that is > fairly hard. If you didn't write save(), you shouldn't be testing it. > > > But, if I were testing this I think I'd do something like this > assertEqual( db_mo, mo, "local and db versions of %s not > identical" % mo.__class__) > > In general, I trust == (either Python's or the object's author's) more > than poking into the internals of an object, encapsulation and all that :) > > > When I compare dictionaries I either convert them to sorted tuples (to > put keys in proper order) > > expected = dict(var1="dog", var2="cat") > answer = something_that_return_dict() > assertEqual( sorted(expected.items()), sorted(answer.items()) ) > > Or check only certain keys are equal (for instance if the answer dict > has other stuff in it I don't care about) > > check_these = ["key1", "key3"] # = expected_dict.keys() > answer = something_that_return_dict() > for k in check_these: > self.assertEqual( expected_dict[k], answer[k], > "expected[%(key)s] != answer[%(key)s]" % {"key":k} ) > > > For Models in which I write a custom save method this is how I usually > structure it. > > def save(self): > if self.value is None: > self.value = self._calc_value() > super(FooModel, self).save() > > def test_value_on_save(self): > test_data =( (dict(foo="", bar=""), 42 ), > (dict(foo="1", bar="3"), 37 ), > # test more edge cases, etc. >) > for (expected, data) in test_data > t = Model(**data) > t.save() > self.assertEqual( expected, t.value ) > > If I had another custom value I'd write another test for it. > > Good luck with your continued Python adventures, > -- > Norman J. Harman Jr. > Senior Web Specialist, Austin American-Statesman > ___ > You've got fun! Check out Austin360.com for all the entertainment > info you need to live it up in the big city! > > > --~--~-~--~~~---~--~~ 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: HTML Escaping JSON data?
If the part of the page being changed is complex, the easiest way to do this is to call render_to_response as usual, but with the template containing only a instead of a full HTML page. Handle any escaping needed in the template. If you only want to update the text without adding any markup, use jQuery.fn.text instead of jQuery.fn.html. --~--~-~--~~~---~--~~ 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: unit testing and comparing dictionaries
Dictionaries compare equal if they contain the same data, regardless of key order. There is no need to convert to sorted sequences unless you need to compare the serialized output (such as in doctests). I would guess that one of the models has additional fields added to its __dict__, perhaps through some caching mechanism. Try printing ``vars(mo)`` and ``vars(saved_mo)``, and then examine the output manually. If you truly wish to examine two model objects for equality, you could try the appended code[1] However, I would advise that you remove your test entirely. It is without point, as Django's unit testing already covers the behavior of ``Model.send()``. Restrict testing to your own code, before you go mad "sanity checking" the massive pile of third-party code underlying yours. [1] -- assertEqual (type (mo), type (saved_mo)) # Retrieve a list of database model field names attrs = [f.attname for f in mo._meta.fields] # Construct lists based on the model attributes, and compare them mo_attrs = [getattr (mo, a) for a in attrs] saved_mo_attrs = [getattr (saved_mo, a) for a in attrs] assertEqual (mo_attrs, saved_mo_attrs) -- --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Implementing a new idea
Hello, I am currently using Django to keep track of "Timecards" submitted towards work on different "Projects". What I would like to do, is to track when "Modifications" are made on projects (via the project admin page). (I'm quoting words that are represented literally in the data model.) For example: Someone logged in might want to change the "status" of a particular project from 'assay development' to 'completed'. What I would like to do, is create a new "ProjectModification" every time something like this happens. class ProjectModification(models.Model): project = models.ForeignKey(Project) user = models.ForeignKey(User) date = models.DateField() change_field = models.CharField(max_length=200) change_from = models.CharField(max_length=200) change_to = models.CharField(max_length=200) Does anyone have an idea of how I could accomplish this? I am already using a specialized version of the 'change_form.html' template for Projects, so modifications could be made here without affecting other admin change_forms. Any help would be greatly appreciated. -Adam --~--~-~--~~~---~--~~ 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: iterate over alphabet in template
If you wanted to keep the alphabet issue out of the view, you could also do this: {% for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" %} --Ned. http://nedbatchelder.com M.Ganesh wrote: > Joel Bernstein wrote: > >> For an easy (but locale-dependent) way to get a list of the uppercase >> characters in Python, try string.uppercase >> >> http://www.python.org/doc/2.3/lib/module-string.html >> >> Just add that list to your context, and you should be ready to go. >> >> On Jun 17, 12:03 pm, "Richard Dahl" <[EMAIL PROTECTED]> wrote: >> >> >>> I would probably just pass in a python list with all of the letters in the >>> alphabet, then just >>> {% for l in alphabet_list %} ... >>> -richard >>> >>> On 6/17/08, M.Ganesh <[EMAIL PROTECTED]> wrote: >>> >>> >>> >>> >>> Hi All, I am relatively new to both python and django. Please help me to do this : {% for letter in [A to Z] %} < how do I write this line in a template? {{letter}} {% endfor %} Thanks in advance Regards Ganesh > Hi Richard and Joel, > > Thanks for your lightning fast replies. I tried this and it worked : > > #my view function > return render_to_response(template, > {'object_name' : object.__name__, >'app_label' : object._meta.app_label, > object_list_name : object_list, >'base_template' : base_template, >'alphabet_string' : ascii_uppercase }, >RequestContext(request)) > > #my template > {% for letter in alphabet_string %} > {{ letter }} - > {% endfor %} > > Thanks once again > > Regards Ganesh > > > > > > -- Ned Batchelder, http://nedbatchelder.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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Media variables confusion
Hey guys, So i am a little confused by the MEDIA_ROOT, MEDIA_URL, and ADMIN_MEDIA_PREFIX variables. I understand that the ADMIN_MEDIA_PREFIX provides the prefix. But so what if it was on another url? I am assuming that the common use case is to serve them from the same domain, which is what i am doing. But just in case... Also, why do we need a MEDIA_ROOT as a path to a directory if we can use the static.serve view during development? And then so why are both the MEDIA_URL and MEDIA_ROOT needed? As you can see, I'm a little confused by these settings and have managed to develop with using them this far. So any explanation is appreciated. I find the documentation a little lacking in explaining these vars. Regards, Alaa Salman http://www.codedemigod.com FSF Member #6304 "Never measure the height of a mountain until you have reached the top. Then you will see how low it was." ---Dag Hammarskjold --~--~-~--~~~---~--~~ 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: Dictionaries, templates and best practices
I could be completely mistaken, but can't you replace 'post.0.title' and 'post.0.post' with 'x.title' and 'x.post', respectively? On Jun 17, 1:50 pm, "Juan Hernandez" <[EMAIL PROTECTED]> wrote: > Hey there > > I've been practicing for a while with the template system and I have some > questions: > > Lets say that I create this dictionary: > > test = dict() > test[0] = {'title': 'My First Title', 'post': 'My First Post'} > test[1] = {'title': 'My Second Title', 'post': 'My Second Post'} > etc... til 10 for example > > If i want to display that information, the best way would be to iterate over > each number and show 'title' and 'post'. > > My question is: How can I actually iterate over a dictionary like this > inside a template? If i do this (assuming that the shown dictionary has been > assigned to 'post' in render_to_response) > > {% for x in post%} > {{ post.0.title }}^M > > >{{ post.0.post }}^M > > It will only show the first part of the dictionary and 'x' as a number > cannot be handled. I haven't found a way to have an increasing number to > iterate with... Something to replace the zero that increases until is > finished by hte condition > > What would be the best way to display the whole dictionary in a template?? > > Thank you very much as usual > jhv --~--~-~--~~~---~--~~ 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: DjangoAMF vs. pyAMF - any opinions?
Chris, Thanks for the tricks. Some of them I already have in my code, that is working since the last weekend. I was in trouble with the class mapping, but with a great help from ThijsTriemstra ( http://pyamf.org/wiki/ThijsTriemstra) in the irc channel #pyamf at irc.collab.eu, I get my code working. ;) I'd like to say too, that using the last version of PyAMF (0.3.1), I didn't had any problem with simple objects. :) Thanks again Eder On 6/17/08, Krzysztof Ciesielski <[EMAIL PROTECTED]> wrote: > > > On Sat, Jun 14, 2008 at 11:52 PM, Ederson Mota Pereira <[EMAIL PROTECTED]> > wrote: > > Hi Cristopher, > > > > Thanks for you feedback. > > > > I'm working only with PyAMF now. My example application is working fine > > with Flex 3 and exposed methods in django side, but I'm having problem > with > > class mapping of the Django models. (More specifically, in the Flex side: > > TypeError: Error #1034: Type Coercion failed: cannot convert > [EMAIL PROTECTED] > > to cli.Client). I already tried in many ways, including using Flex 2 with > > the s2flex2 library. > > > > Do you (or anyone) already did anything similar? > > > > Thanks > > > > Well I haven't yet. When I started work with django+ PyAMF tandem > there was only support for simple objects so I decide to rely on them. > > Anyway in order get any django objects sent to flex (and the other > way) you'll need to write your own classes (on both sides) and > register them > - in python: pyamf.register_class > - in flex they need to implement IExtrenizable and need to be > registered with metetag > [RemoteClass(alias="flex.messaging.io.ObjectProxy")] > > It's really whole lots of work to do it right so I wouldn't bother doing > that. > > greets > Chris > > > > > On 6/14/08, Krzysztof Ciesielski <[EMAIL PROTECTED]> wrote: > >> > >> On 5/3/08, J Peyret <[EMAIL PROTECTED]> wrote: > >> > > >> > I am just starting out with Flex 3 and I'd like to know if anybody's > >> > got any strong opinions on which AMF<=>Python bridge is best for > using > >> > AMF to talk to Django. > >> > > >> > I do know Python and am somewhat familiar with Django. > >> > > >> > Things that make a difference to me, roughly in order of decreasing > >> > importance: > >> > > >> > - code maturity > >> > - how much activity there is on the project, by how many developers > >> > - absolute drop-dead bugs that prohibit using either under specific > >> > circumstances > >> > - documentation > >> > - ease of use and clean design > >> > - performance > >> > > >> > Far as I can tell from surfing around, DjangoAMF is more mature and > >> > perhaps easier to set up, but it is hosted in Japan and last time I > >> > checked I didn't speak Japanese so I am worried about missing out on > >> > the latest project "gossip". > >> > > >> > Neither seem to have much documentation going for them. That's OK to > >> > an extent, I'll probably try both, but I'd welcome some insight from > >> > people who have used them in anger. > >> > > >> > What I would like to do is to move data back and forth from a Django- > >> > based postgreSQL database backend to a GUI application with complex > >> > behavior requirements, using Apache to serve the SWFs. Not all of > the > >> > relational data will be housed in Django models either, as I will use > >> > some raw SQL to manipulate it as needed. > >> > > >> > Any opinions? > >> > > > >> > > >> > >> > >> Hi, I had same problem some time ago. My decision was to choose PyAMF. > >> So here's what I found out after couple months of work. > >> - code maturity > >> both projects are immature and still under heavy development, pyAmf is > >> considered as Beta > >> > >> > >> - how much activity there is on the project, by how many developers > >> > >> PyAMF has really strong community of European developers, (I reported > >> bug and it was fixed next day) > >> > >> > >> - absolute drop-dead bugs that prohibit using either under specific > >> circumstances > >> > >> > >> in PyAMF as for now I've seen only two really big issues and both are > >> fixed > >> > >> - documentation > >> both have barelly none, but as they are python OS projects you > >> shouldn't be suprised. Just like with django most info you can get by > >> reading code. And code is very clean and nice to read. > >> > >> > >> - ease of use and clean design > >> > >> PyAMF is very easy and clean, you just define DjangoGateway object > >> that is much alike mapping string function names to coresponding view > >> names/functions > >> > >> - performance > >> haven't tested it yet, but as django apps are easilly scalable it > >> shouldn't be any problem at all. > >> > >> > >> > >> -- > >> Greets > >> Christopher Ciesielski > >> -- > >> mob. +48 791457074 > >> email: [EMAIL PROTECTED] > >> skype: mi_yagi > >> jabber: [EMAIL PROTECTED] > >> www: http://www.pydev.pl/ > >> ASI: http://www.asi.pwr.wroc.pl/ > >> > >> > > > > > > > > > > > > > -- > > Pozdrawiam >
Re: User matching query does not exist.
Got it... noticed that there was a single invalid user_id in my timecard table in the database. Not sure how this could have happened. -Adam On Jun 17, 2:43 pm, Adam Fraser <[EMAIL PROTECTED]> wrote: > Suddenly, I am getting the following error when I try to look at my > Timecard objects, via Timecard.objects.all() > > >>> Timecard.objects.all() > > Traceback (most recent call last): > File "", line 1, in > File "/imaging/analysis/People/imageweb/python-packages/django/db/ > models/query.py", line 108, in __repr__ > return repr(self._get_data()) > File "/imaging/analysis/People/imageweb/python-packages/django/db/ > models/base.py", line 125, in __repr__ > return smart_str(u'<%s: %s>' % (self.__class__.__name__, > unicode(self))) > File "/home/radon01/afraser/projectprofiler/trunk/projectprofiler/../ > projectprofiler/projects/models.py", line 155, in __unicode__ > return "%d: %s %s" % (self.id, self.user, self.date) > File "/imaging/analysis/People/imageweb/python-packages/django/db/ > models/fields/related.py", line 209, in __get__ > rel_obj = self.field.rel.to._default_manager.get(**params) > File "/imaging/analysis/People/imageweb/python-packages/django/db/ > models/manager.py", line 69, in get > return self.get_query_set().get(*args, **kwargs) > File "/imaging/analysis/People/imageweb/python-packages/django/db/ > models/query.py", line 263, in get > raise self.model.DoesNotExist, "%s matching query does not exist." > % self.model._meta.object_name > DoesNotExist: User matching query does not exist. > > Here's my model: > class Timecard(models.Model): > user = models.ForeignKey(User) > date = models.DateField() > def __unicode__(self): > return "%d: %s %s" % (self.id, self.user, self.date) > class Meta: > unique_together = (("user", "date"),) > class Admin: > pass > > Does anyone have an idea why this may suddenly be happening? I > noticed that the MySQL column name corresponding to > models.ForeignKey(User), is actually "user_id"... this is correct > though right? > > -Adam --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Dictionaries, templates and best practices
Hey there I've been practicing for a while with the template system and I have some questions: Lets say that I create this dictionary: test = dict() test[0] = {'title': 'My First Title', 'post': 'My First Post'} test[1] = {'title': 'My Second Title', 'post': 'My Second Post'} etc... til 10 for example If i want to display that information, the best way would be to iterate over each number and show 'title' and 'post'. My question is: How can I actually iterate over a dictionary like this inside a template? If i do this (assuming that the shown dictionary has been assigned to 'post' in render_to_response) {% for x in post%} {{ post.0.title }}^M {{ post.0.post }}^M It will only show the first part of the dictionary and 'x' as a number cannot be handled. I haven't found a way to have an increasing number to iterate with... Something to replace the zero that increases until is finished by hte condition What would be the best way to display the whole dictionary in a template?? Thank you very much as usual jhv --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
User matching query does not exist.
Suddenly, I am getting the following error when I try to look at my Timecard objects, via Timecard.objects.all() >>> Timecard.objects.all() Traceback (most recent call last): File "", line 1, in File "/imaging/analysis/People/imageweb/python-packages/django/db/ models/query.py", line 108, in __repr__ return repr(self._get_data()) File "/imaging/analysis/People/imageweb/python-packages/django/db/ models/base.py", line 125, in __repr__ return smart_str(u'<%s: %s>' % (self.__class__.__name__, unicode(self))) File "/home/radon01/afraser/projectprofiler/trunk/projectprofiler/../ projectprofiler/projects/models.py", line 155, in __unicode__ return "%d: %s %s" % (self.id, self.user, self.date) File "/imaging/analysis/People/imageweb/python-packages/django/db/ models/fields/related.py", line 209, in __get__ rel_obj = self.field.rel.to._default_manager.get(**params) File "/imaging/analysis/People/imageweb/python-packages/django/db/ models/manager.py", line 69, in get return self.get_query_set().get(*args, **kwargs) File "/imaging/analysis/People/imageweb/python-packages/django/db/ models/query.py", line 263, in get raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name DoesNotExist: User matching query does not exist. Here's my model: class Timecard(models.Model): user = models.ForeignKey(User) date = models.DateField() def __unicode__(self): return "%d: %s %s" % (self.id, self.user, self.date) class Meta: unique_together = (("user", "date"),) class Admin: pass Does anyone have an idea why this may suddenly be happening? I noticed that the MySQL column name corresponding to models.ForeignKey(User), is actually "user_id"... this is correct though right? -Adam --~--~-~--~~~---~--~~ 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: iterate over alphabet in template
Joel Bernstein wrote: > For an easy (but locale-dependent) way to get a list of the uppercase > characters in Python, try string.uppercase > > http://www.python.org/doc/2.3/lib/module-string.html > > Just add that list to your context, and you should be ready to go. > > On Jun 17, 12:03 pm, "Richard Dahl" <[EMAIL PROTECTED]> wrote: > >> I would probably just pass in a python list with all of the letters in the >> alphabet, then just >> {% for l in alphabet_list %} ... >> -richard >> >> On 6/17/08, M.Ganesh <[EMAIL PROTECTED]> wrote: >> >> >> >> >>> Hi All, >>> >>> I am relatively new to both python and django. Please help me to do this : >>> >>> {% for letter in [A to Z] %} < how do I write this line in a template? >>>{{letter}} >>> {% endfor %} >>> >>> Thanks in advance >>> Regards Ganesh >>> Hi Richard and Joel, Thanks for your lightning fast replies. I tried this and it worked : #my view function return render_to_response(template, {'object_name' : object.__name__, 'app_label' : object._meta.app_label, object_list_name : object_list, 'base_template' : base_template, 'alphabet_string' : ascii_uppercase }, RequestContext(request)) #my template {% for letter in alphabet_string %} {{ letter }} - {% endfor %} Thanks once again Regards Ganesh --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Overriding the JOIN type in contrib.admin's search forms?
Bear with me, I'm a Django novice, still reading docs... I'm trying to build my first app using django admin (release 0.96), because it's a good match to the requirements (a quick and simple CRUD application). I found a thread from last year http://groups.google.com/group/django-users/browse_thread/thread/b0866749612aaeae/135d13ce40c33aa7?lnk=gst=admin+search_fields+join#135d13ce40c33aa7 where the last post describes the same problem I'm having, but there were no further replies. All was coming along nicely until I started using 'the lookup API “follow” notation' to get a foreign key into my search_fields, like this: class FilmClip(models.Model): ... class Admin: ... search_fields = ('clip_id', 'label', 'description', 'filmcliplog__description' # This is the line that causes problems ) class FilmClipLog(models.Model): clip = models.ForeignKey(FilmClip, edit_inline=models.TABULAR, num_in_admin=3) ... There are two problems with the resulting behavior: 1) Any matching FilmClip thas has at least one FilmClipLog will show up in the results twice. 2) Any matching FilmClip that has no FilmClipLogs will not show up at all. From the mysql query log, I've found that the query looks like: SELECT ... FROM `filmy_filmclip` INNER JOIN `filmy_filmcliplog` ... But what I want is this: SELECT DISTINCT ... FROM `filmy_filmclip` LEFT OUTER JOIN `filmy_filmcliplog` ... So, my questions: 1) Is this a Django bug? When would the existing behavior be desirable? 2) Is there a way to specify the type of join in the search query? 3) Is there a way to add DISTINCT to the search query? 4) If no, what's the quickest way to get the behavior I want? Thanks, - PW --~--~-~--~~~---~--~~ 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: serve static files
Molly wrote: > How would I call the static file in my browser?? By typing in the url to the static file directly in the address bar. For example if your server is example.com, root of django app is myapp, and images are in img dir, and image is named myjp.jpg the url would be http:://example.com/myapp/media/img/myjpg.jpg From your description it sounds like the css is not being found. I'd look in the HTML source(as seen by browser, with firefox ctrl-u, with IE install Firefox) find line(s) that include css. They probably look something like this. http://yui.yahooapis.com/2.3.1/build/calendar/assets/calendar.css; /> then see if you access(copy it to address bar, hit return) http://yui.yahooapis.com/2.3.1/build/calendar/assets/calendar.css Either the url(s) in your templates point to wrong place, or the urls/document_roots in urlpatterns are wrong, or something else is wrong ;) btw hard coding a path "C:\dev\incidents\admin_media" in your urlpatterns is probably a bad thing to do. As whoever uses your app/where ever you deploy it for production is unlikely to install the app in the same place you do on your dev machine. -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: redirect with post parameters
MarcoX wrote: > Peter and Daniel, thanks for the reply. > I must use the POST method because the external site WANT a post > method. > parameter2 is a "stupid" info that the external site required. > I try with your (simple) solution, a hidden html form with a > javascript redirect... I had to do something similar for PayPal. I did it by changing the action="" in a confirmation form to point to PayPal. Instead of form POSTing back to me and trying to redirect POST which doesn't work, it POSTs directly to PayPal. The form was constructed to contain all the things PayPal wanted in hidden fields. In PayPal's instance it doesn't matter that user can change values(they are checked elsewhere, when PP notifies us of payment) but it may in your situation. Depending on what 3rd party site does/wants another way to do this is to use something like urllib2 and POST to 3rdpary in your view code, slurp the response and send it back to user. It will have 3rdparty content but come from your server, which is probably gonna cause problems. -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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: Freelance Django Developers Urgently Needed
Hey, there, django-users subscribers! This is your periodic friendly reminder that the place for job listings is http://djangogigs.com/, which exists specifically to serve that purpose. -- "Bureaucrat Conrad, you are technically correct -- the best kind of correct." --~--~-~--~~~---~--~~ 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: iterate over alphabet in template
For an easy (but locale-dependent) way to get a list of the uppercase characters in Python, try string.uppercase http://www.python.org/doc/2.3/lib/module-string.html Just add that list to your context, and you should be ready to go. On Jun 17, 12:03 pm, "Richard Dahl" <[EMAIL PROTECTED]> wrote: > I would probably just pass in a python list with all of the letters in the > alphabet, then just > {% for l in alphabet_list %} ... > -richard > > On 6/17/08, M.Ganesh <[EMAIL PROTECTED]> wrote: > > > > > Hi All, > > > I am relatively new to both python and django. Please help me to do this : > > > {% for letter in [A to Z] %} < how do I write this line in a template? > >{{letter}} > > {% endfor %} > > > Thanks in advance > > Regards Ganesh --~--~-~--~~~---~--~~ 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: iterate over alphabet in template
I would probably just pass in a python list with all of the letters in the alphabet, then just {% for l in alphabet_list %} ... -richard On 6/17/08, M.Ganesh <[EMAIL PROTECTED]> wrote: > > > Hi All, > > I am relatively new to both python and django. Please help me to do this : > > {% for letter in [A to Z] %} < how do I write this line in a template? >{{letter}} > {% endfor %} > > > Thanks in advance > Regards Ganesh > > > > > > --~--~-~--~~~---~--~~ 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: redirect with post parameters
Peter and Daniel, thanks for the reply. I must use the POST method because the external site WANT a post method. parameter2 is a "stupid" info that the external site required. I try with your (simple) solution, a hidden html form with a javascript redirect... many thanks. On 17 Giu, 18:34, Daniel Hepper <[EMAIL PROTECTED]> wrote: > Hi > !> I must login a user in my site than redirect to another site with 2 > > parameters via post method. > > It's possible do that in my registration view? > > This is not how a redirect works. If your view returns a > HttpResponseRedirect, Django sends a HTTP 302 code back to the browser > along with the new URL. The browser of the user then requests the new URL. > > The only way you could force a POST, would be to return a HTML page with > a hidden Form and some JavaScript to submit it automatically. > > Why do you absolutely want to POST something? I hope 'parameter2' is not > something like 'authenticated', because that would be really really bad > securitywise. Just because you can't manipulate POST parameters through > URLs doesn't mean they are save to hide secrets. > > > my example code: > > > if request.POST: > > redirect_to = settings.REDIRECT_URL > > errors = manipulator.get_validation_errors(request.POST) > > if not errors: > > from django.contrib.auth import login > > login(request, manipulator.get_user()) > > request.session.delete_test_cookie() > > post_data = { > > 'parameter1': request.user.id, > > 'parameter2': 'yes' > > } > > #Redirect to another site with post_data parameter > > # > > # a simple redirect without parameter return > > HttpResponseRedirect(redirect_to) > > else: > > errors = {} > > > I tried with httplib e urllib but with no results > > > Thanks in advance... > > Marco --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
iterate over alphabet in template
Hi All, I am relatively new to both python and django. Please help me to do this : {% for letter in [A to Z] %} < how do I write this line in a template? {{letter}} {% endfor %} Thanks in advance Regards Ganesh --~--~-~--~~~---~--~~ 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: serve static files
How would I call the static file in my browser?? Sorry, i'm still a beginner! :P Thanks for the response :) Molly On Jun 17, 12:16 pm, chris vigelius <[EMAIL PROTECTED]> wrote: > Am Dienstag, 17. Juni 2008 17:22:46 schrieb Molly: > > > I created a django app and turned it into a stand alone app. > > > Everything is working, except for the look of the page is all messed > > up. > > what happens if you call one of the static files directly in your browser? > Does the path to the static files appear correctly in the source of your > page? > > 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: redirect with post parameters
Hi ! > I must login a user in my site than redirect to another site with 2 > parameters via post method. > It's possible do that in my registration view? This is not how a redirect works. If your view returns a HttpResponseRedirect, Django sends a HTTP 302 code back to the browser along with the new URL. The browser of the user then requests the new URL. The only way you could force a POST, would be to return a HTML page with a hidden Form and some JavaScript to submit it automatically. Why do you absolutely want to POST something? I hope 'parameter2' is not something like 'authenticated', because that would be really really bad securitywise. Just because you can't manipulate POST parameters through URLs doesn't mean they are save to hide secrets. > my example code: > > if request.POST: > redirect_to = settings.REDIRECT_URL > errors = manipulator.get_validation_errors(request.POST) > if not errors: > from django.contrib.auth import login > login(request, manipulator.get_user()) > request.session.delete_test_cookie() > post_data = { > 'parameter1': request.user.id, > 'parameter2': 'yes' > } > #Redirect to another site with post_data parameter > # > # a simple redirect without parameter return > HttpResponseRedirect(redirect_to) > else: > errors = {} > > I tried with httplib e urllib but with no results > > Thanks in advance... > Marco > > > > --~--~-~--~~~---~--~~ 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: redirect with post parameters
On 6/17/08, MarcoX <[EMAIL PROTECTED]> wrote: > I tried with httplib e urllib but with no results Technically, a redirection represents to return result code 301 or 302 and set field Location in the HTTP response header to absolute URL. HTTP Client then issue a new HTTP request to this URL. Hence you cannot "forward" any post parameter without client side cooperation. You could pass some parameters in query part of URL and/or perhaps via cookie thoroughly built for particular URL. HTH, Peter --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Nested Dictionaries in Django Templates
Hello, I have a question regarding displaying information in django templates. I would like to display a nested dictionary(Hash) in the templates. However the only problem is that the values in the dictionary are either strings or other dictionaries. If there a way of knowing the type of value in the template ? For eg: for key_value in dictionary.items: if key_value.1 isTYPE String: do something if key_value.1 isTYPE Dictionary: do something else Thanks in advance, Lezan --~--~-~--~~~---~--~~ 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: serve static files
Am Dienstag, 17. Juni 2008 17:22:46 schrieb Molly: > I created a django app and turned it into a stand alone app. > > Everything is working, except for the look of the page is all messed > up. what happens if you call one of the static files directly in your browser? Does the path to the static files appear correctly in the source of your page? 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
redirect with post parameters
Hi all django friends, I must login a user in my site than redirect to another site with 2 parameters via post method. It's possible do that in my registration view? my example code: if request.POST: redirect_to = settings.REDIRECT_URL errors = manipulator.get_validation_errors(request.POST) if not errors: from django.contrib.auth import login login(request, manipulator.get_user()) request.session.delete_test_cookie() post_data = { 'parameter1': request.user.id, 'parameter2': 'yes' } #Redirect to another site with post_data parameter # # a simple redirect without parameter return HttpResponseRedirect(redirect_to) else: errors = {} I tried with httplib e urllib but with no results Thanks in advance... Marco --~--~-~--~~~---~--~~ 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: SQL logic error or missing database
Replying to myself again, closing the issue at least for me for now: On Jun 17, 10:02 am, bobhaugen <[EMAIL PROTECTED]> wrote: > Replying to myself: maybe this is an instance of Ticket > #7411?http://code.djangoproject.com/ticket/7411 > > "Saving db object while iterating over a queryset larger than > ITER_CHUNK_SIZE breaks with sqlite" It is. Forcing evaluation of the queryset by wrapping it in list() solves the problem. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
serve static files
I created a django app and turned it into a stand alone app. Everything is working, except for the look of the page is all messed up. I need to serve static files (I think) in urls.py but somehow I am messing up my code: --- from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^admin/', include('django.contrib.admin.urls')), (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': r'C:\dev\incidents\media', 'show_indexes': True}), (r'^admin_media/(?P.*)$', 'django.views.static.serve', {'document_root': r'C:\dev\incidents\admin_media', 'show_indexes': True}), ) --- I can't see any problems.. I would appreciate any help you can give me! Thanks :) Molly --~--~-~--~~~---~--~~ 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: DjangoAMF vs. pyAMF - any opinions?
On Sat, Jun 14, 2008 at 11:52 PM, Ederson Mota Pereira <[EMAIL PROTECTED]> wrote: > Hi Cristopher, > > Thanks for you feedback. > > I'm working only with PyAMF now. My example application is working fine > with Flex 3 and exposed methods in django side, but I'm having problem with > class mapping of the Django models. (More specifically, in the Flex side: > TypeError: Error #1034: Type Coercion failed: cannot convert [EMAIL PROTECTED] > to cli.Client). I already tried in many ways, including using Flex 2 with > the s2flex2 library. > > Do you (or anyone) already did anything similar? > > Thanks Well I haven't yet. When I started work with django+ PyAMF tandem there was only support for simple objects so I decide to rely on them. Anyway in order get any django objects sent to flex (and the other way) you'll need to write your own classes (on both sides) and register them - in python: pyamf.register_class - in flex they need to implement IExtrenizable and need to be registered with metetag [RemoteClass(alias="flex.messaging.io.ObjectProxy")] It's really whole lots of work to do it right so I wouldn't bother doing that. greets Chris > > On 6/14/08, Krzysztof Ciesielski <[EMAIL PROTECTED]> wrote: >> >> On 5/3/08, J Peyret <[EMAIL PROTECTED]> wrote: >> > >> > I am just starting out with Flex 3 and I'd like to know if anybody's >> > got any strong opinions on which AMF<=>Python bridge is best for using >> > AMF to talk to Django. >> > >> > I do know Python and am somewhat familiar with Django. >> > >> > Things that make a difference to me, roughly in order of decreasing >> > importance: >> > >> > - code maturity >> > - how much activity there is on the project, by how many developers >> > - absolute drop-dead bugs that prohibit using either under specific >> > circumstances >> > - documentation >> > - ease of use and clean design >> > - performance >> > >> > Far as I can tell from surfing around, DjangoAMF is more mature and >> > perhaps easier to set up, but it is hosted in Japan and last time I >> > checked I didn't speak Japanese so I am worried about missing out on >> > the latest project "gossip". >> > >> > Neither seem to have much documentation going for them. That's OK to >> > an extent, I'll probably try both, but I'd welcome some insight from >> > people who have used them in anger. >> > >> > What I would like to do is to move data back and forth from a Django- >> > based postgreSQL database backend to a GUI application with complex >> > behavior requirements, using Apache to serve the SWFs. Not all of the >> > relational data will be housed in Django models either, as I will use >> > some raw SQL to manipulate it as needed. >> > >> > Any opinions? >> > > >> > >> >> >> Hi, I had same problem some time ago. My decision was to choose PyAMF. >> So here's what I found out after couple months of work. >> - code maturity >> both projects are immature and still under heavy development, pyAmf is >> considered as Beta >> >> >> - how much activity there is on the project, by how many developers >> >> PyAMF has really strong community of European developers, (I reported >> bug and it was fixed next day) >> >> >> - absolute drop-dead bugs that prohibit using either under specific >> circumstances >> >> >> in PyAMF as for now I've seen only two really big issues and both are >> fixed >> >> - documentation >> both have barelly none, but as they are python OS projects you >> shouldn't be suprised. Just like with django most info you can get by >> reading code. And code is very clean and nice to read. >> >> >> - ease of use and clean design >> >> PyAMF is very easy and clean, you just define DjangoGateway object >> that is much alike mapping string function names to coresponding view >> names/functions >> >> - performance >> haven't tested it yet, but as django apps are easilly scalable it >> shouldn't be any problem at all. >> >> >> >> -- >> Greets >> Christopher Ciesielski >> -- >> mob. +48 791457074 >> email: [EMAIL PROTECTED] >> skype: mi_yagi >> jabber: [EMAIL PROTECTED] >> www: http://www.pydev.pl/ >> ASI: http://www.asi.pwr.wroc.pl/ >> >> > > > > > -- Pozdrawiam Krzysiek Ciesielski -- mob. +48 791457074 email: [EMAIL PROTECTED] skype: mi_yagi jabber: [EMAIL PROTECTED] www: http://www.pydev.pl/ ASI: http://www.asi.pwr.wroc.pl/ --~--~-~--~~~---~--~~ 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: Overwriting the delete() Method in a Model
My fault, I must have skipped right over that part. It seems that it *does* send pre_delete and post_delete signals, but does not call custom delete methods On Jun 17, 9:51 am, Daniel Hepper <[EMAIL PROTECTED]> wrote: > > It isn't very clear from that sentence which of the two methods Django > > uses to delete those child records, but looking at the code, it seems > > to be method #2. Since it's using the more-efficient batch delete, no > > custom delete methods are being called, no signals are being sent, > > which is exactly the problem you're having. > > > The solution is to override the delete method (or respond to the > > pre_delete signal), on your *parent* model, in this case > > 'Participant'. That way, when you delete the Participant, you can > > delete all related Data records by hand. > > I had a quick glance at the code and I came to the opposite conclusion. > > A comment [1] in the delete() method in the QuerySet class says: > > "# Collect all the objects to be deleted in this chunk, and all the > # objects that are related to the objects that are to be deleted." > > This collection is then passed to the delete_objects [2] function where > the SQL magic happens and it definitely sends signals. > > Confused as I was, I just tried it. I have a Video model which haa a > VideoHost model as foreign key. I defined a function that prints its > parameter and attached it to the post_delete signal: > > >>> def print_sig(*args,**kwargs): > > ... for x in args: print str(x) > ... for k,v in kwargs.items(): print k,v > > >>> dispatcher.connect(print_sig, signal=signals.post_delete) > > Then I deleted one VideoHost[3]: > > >>> VideoHost.objects.all()[0].delete() > > All related Videos got deleted as well, and signals got sent: > > instance Video 1 on YouTube > signal > sender > instance Video 2 on YouTube > signal > sender > instance Video 3 on YouTube > signal > sender > instance YouTube > signal > sender > > It seems signals are the way to go, or did I miss something? > > Regards, > Daniel > > [1]http://code.djangoproject.com/browser/django/trunk/django/db/models/q... > [2]http://code.djangoproject.com/browser/django/trunk/django/db/models/q... > [3] OMG, I deleted YouTube! :) --~--~-~--~~~---~--~~ 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: SQL logic error or missing database
Replying to myself: maybe this is an instance of Ticket #7411? http://code.djangoproject.com/ticket/7411 "Saving db object while iterating over a queryset larger than ITER_CHUNK_SIZE breaks with sqlite" --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Freelance Django Developers Urgently Needed
We are currently looking for more Django developers to join us on a freelance basis. Location is irrelevant as long as you have a fast and reliable Internet access. You will be working from home, so you should be able to work independently, but also be able to demonstrate effective people and time management skills, so as to deliver work within our deadlines. Send us your daily/hourly rates, your availability as well as a few words about work you've done before. We also need samples/URLs of past projects, completed or still pending. Any questions? Just send me an email. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
SQL logic error or missing database
I just got a new OperationalError message (in the subject line). Exception Type: OperationalError Exception Value:SQL logic error or missing database Exception Location: /home/bob/django-trunk/django/db/backends/ __init__.py in _commit, line 20 The code below has been running fine before. I made some changes in other parts of the code, but not in the part that crashed. And everything else seems to work fine now. ===views.py=== def advance_dates(): orders = Order.objects.all() for order in orders: order.order_date = order.order_date + datetime.timedelta(days=7) order.save() items = InventoryItem.objects.all() for item in items: item.inventory_date = item.inventory_date + datetime.timedelta(days=7) item.save() The order.save() worked fine. The error occured on item.save(), the last line in the code excerpt, when saving InventoryItems. ===models.py=== class InventoryItem(models.Model): producer = models.ForeignKey(Producer) product = models.ForeignKey(Product) inventory_date = models.DateField() I'm using Sqlite3 and Django 0.97-pre-SVN-7519 on Ubunto 7.10. I can save InventoryItems fine from Admin and from other forms. Any clues? --~--~-~--~~~---~--~~ 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: Overwriting the delete() Method in a Model
> It isn't very clear from that sentence which of the two methods Django > uses to delete those child records, but looking at the code, it seems > to be method #2. Since it's using the more-efficient batch delete, no > custom delete methods are being called, no signals are being sent, > which is exactly the problem you're having. > > The solution is to override the delete method (or respond to the > pre_delete signal), on your *parent* model, in this case > 'Participant'. That way, when you delete the Participant, you can > delete all related Data records by hand. I had a quick glance at the code and I came to the opposite conclusion. A comment [1] in the delete() method in the QuerySet class says: "# Collect all the objects to be deleted in this chunk, and all the # objects that are related to the objects that are to be deleted." This collection is then passed to the delete_objects [2] function where the SQL magic happens and it definitely sends signals. Confused as I was, I just tried it. I have a Video model which haa a VideoHost model as foreign key. I defined a function that prints its parameter and attached it to the post_delete signal: >>> def print_sig(*args,**kwargs): ... for x in args: print str(x) ... for k,v in kwargs.items(): print k,v >>> dispatcher.connect(print_sig, signal=signals.post_delete) Then I deleted one VideoHost[3]: >>> VideoHost.objects.all()[0].delete() All related Videos got deleted as well, and signals got sent: instance Video 1 on YouTube signal sender instance Video 2 on YouTube signal sender instance Video 3 on YouTube signal sender instance YouTube signal sender It seems signals are the way to go, or did I miss something? Regards, Daniel [1] http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L276 [2] http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L680 [3] OMG, I deleted YouTube! :) --~--~-~--~~~---~--~~ 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: unit testing and comparing dictionaries
Gene Campbell wrote: > Hello Djangonauts > > I'm a noob on both Django and Python, so this question might be easy > for the experts out there. I am trying to do test first development > during the development of my model code. (I have lots of experience > with test first coding in the Java world, no practical experience in > the Py world.) > > I want to do something like this > > class ModelTest(TestCase): > > def test_crud_modelone(self): > mo = ModelOne( name="A name" ) > mo.save() > > saved_mo = mo.objects.get(pk=mo.id) > > assertEqual( vars(mo), vars(saved_mo),"Something not getting saved") > > That assertEqual line fails. I wrote this > > def compare(self, obj1, obj2, verbose = False): > other = vars(obj2) > for d,v in vars(obj1).items(): > if isinstance(other.get(d,None),datetime.date): > if not other.get(d,None) == v.date(): > return False > elif not other.get(d,None) == v: > return False > > return True > > This is probably horrible python, I'm still learning (unlearning > Java), but it compares correctly for strings and dates so far that > I've tested. I've been using python since 1.5, I had to look up what vars() did. Probably not idiomatic Python. (I've always just looked at __dict__ directly, which I do rarely). The assertEqual line (probably) fails because the order of dictionary keys is not defined. > Some might be asking why I'm testing if my models can be saved, as > most of that functionality is tested when Django is tested. But, I > still feel there's a enough that I have to write to warrant a simple > sanity test like this. FWIW I believe testing what you're testing is a waste of time and violates unit testing. Really the db should be mocked, but that is fairly hard. If you didn't write save(), you shouldn't be testing it. But, if I were testing this I think I'd do something like this assertEqual( db_mo, mo, "local and db versions of %s not identical" % mo.__class__) In general, I trust == (either Python's or the object's author's) more than poking into the internals of an object, encapsulation and all that :) When I compare dictionaries I either convert them to sorted tuples (to put keys in proper order) expected = dict(var1="dog", var2="cat") answer = something_that_return_dict() assertEqual( sorted(expected.items()), sorted(answer.items()) ) Or check only certain keys are equal (for instance if the answer dict has other stuff in it I don't care about) check_these = ["key1", "key3"] # = expected_dict.keys() answer = something_that_return_dict() for k in check_these: self.assertEqual( expected_dict[k], answer[k], "expected[%(key)s] != answer[%(key)s]" % {"key":k} ) For Models in which I write a custom save method this is how I usually structure it. def save(self): if self.value is None: self.value = self._calc_value() super(FooModel, self).save() def test_value_on_save(self): test_data =( (dict(foo="", bar=""), 42 ), (dict(foo="1", bar="3"), 37 ), # test more edge cases, etc. ) for (expected, data) in test_data t = Model(**data) t.save() self.assertEqual( expected, t.value ) If I had another custom value I'd write another test for it. Good luck with your continued Python adventures, -- Norman J. Harman Jr. Senior Web Specialist, Austin American-Statesman ___ You've got fun! Check out Austin360.com for all the entertainment info you need to live it up in the big city! --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Limiting the choices of ForeignKey objects in the admin filters
Hello everyone, I have a question for you all that has been discussed before but I cannot figure out the best way to go about implementing. I have the following model: class DesignSet(models.Model): priority=models.ForeignKey(Priority) status=models.ForeignKey(Status, default=2) concept=models.DateField() last_modified=models.DateField(auto_now = True) project=models.ForeignKey(Project) series=models.CharField(max_length=100) The last two lines are key. I want to be able to only see series (in the filter menu of the admin page) that are associated with a defined project. There has been talk of using something like: def choices_for__FIELD(self): return ModelClass.objects.filter(relation_name=self.relation) but I don't know whether this has been implemented yet and if it has I can't seem to get it to work!!! Any help would be much appreciated. Regards, Martin --~--~-~--~~~---~--~~ 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: Overwriting the delete() Method in a Model
The main issue here is that there are two types of batch deletes in Django: 1. You can query for the models you want to delete, loop through the queryset, and delete them each individually. Your custom delete methods (if any) will get called, and you'll get pre_delete and post_delete signals. That involves a lot of database communication, though. 2. A far more efficient method is to send a single delete command, and let the database do all the hard work on its end. This is what happens when you call delete() on a queryset. Of course, since all the important stuff happens on the database server, Django never hears about any of it. No custom delete methods get called, and no signals get sent. The documentation[1] says: 'When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE — in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.' It isn't very clear from that sentence which of the two methods Django uses to delete those child records, but looking at the code, it seems to be method #2. Since it's using the more-efficient batch delete, no custom delete methods are being called, no signals are being sent, which is exactly the problem you're having. The solution is to override the delete method (or respond to the pre_delete signal), on your *parent* model, in this case 'Participant'. That way, when you delete the Participant, you can delete all related Data records by hand. [1] http://www.djangoproject.com/documentation/db-api/#deleting-objects On Jun 17, 6:26 am, Daniel Austria <[EMAIL PROTECTED]> wrote: > Cool! > > Thank you very much for your response. i ll use signals! > > regards > Dan --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Problem listing with contrib.comments
I have a page: http://www.joshuajonah.com/blog2/200...rst-blog-post/ It has a comment_count and a comment_list, they are being called exactly the same way, however, comment_list has no items. post_detail.html (template for a wrapper around a date_based.object_detail): http://dpaste.com/57001/ The object.id is correct but when i trace {{ comment_list }}, it returns an empty list. The comment_count right above it works fine and the comments exist in the database(referenced to the right object_id) I have tried everything, restarting the server, updating to the latest trunk of Django, replacing the contrib.comments, nothing seems to work. If anybody has any idea I would love a response. --~--~-~--~~~---~--~~ 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: Error while importing URLconf 'mysite.urls': 'module' object has no attribute 'views'
Resolved. Don't know how. On Jun 14, 9:16 pm, Chris Haynes <[EMAIL PROTECTED]> wrote: > This error goes away if I remove the line > (r'^ptree/$', mysite.trees.views.parse_tree), > from the urlpatterns. But I can import trees.views from the shell > > ~/dj/mysite 144: manage.py shell > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > (InteractiveConsole)>>> import trees.views > >>> import urls > > Traceback (most recent call last): > File "", line 1, in > File "c:\Users\Chris\dj\mysite\urls.py", line 17, in > (r'^ptree/$', mysite.trees.views.parse_tree), > AttributeError: 'module' object has no attribute 'views' > > >>> # comment out line 17 in urls.py > >>> import urls > > Using django 0.97 pre. There's another app in the site created some > time ago that works, but I've just created mysite.trees. Both are > imported in the INSTALLED_APPS list. > The only significant difference I note is the lack of a database model > in mysite trees, but don't see what that would have to do with this > error. Any help appreciated! --~--~-~--~~~---~--~~ 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: library import issue.
On Tue, Jun 17, 2008 at 3:48 AM, James Matthews <[EMAIL PROTECTED]> wrote: > The server is running suExec therefore Apache executes as the user. So it > should be able to read my library. > SuEXEC cleans the environment before calling your code. According to Step 19 described here: http://httpd.apache.org/docs/2.0/suexec.html the only environment variables that will be preserved in the environment created for your code are those listed in the "safe environment list" that is set during Apache configuration. I'd guess that LD_LIBRARY_PATH is not in that list. You'd need to consult your hosting provider to be sure, but you could check the value of os.environ.get('LD_LIBRARY_PATH') as a first step to confirming this is the problem. I'm guessing you'll find it is None. 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: ModelForms
Michael, As it turned out, I just needed to set the Category queryset using the "form_instance.fields['fieldname'].queryset = myqueryset" syntax that you suggested. I'm still not sure what was going on there before, but it seems everything is working now. Thanks for the help. Eric On Jun 17, 7:35 am, Michael Elsdörfer <[EMAIL PROTECTED]> wrote: > > form.category.queryset = > > Category.objects.filter(blog__exact=request.user.author_set.all() > > [0].blog) print form.category.queryset > > I am somewhat surprised that this would work at all. The field objects > should be accessible via > > FormClass.base_fields['fieldname'] > > or > > form_instance.fields['fieldname'] > > so you should be able to say for example: > > form_instance.fields['fieldname'].queryset = myqueryset > > There is also: > > form_instance.fields['fieldname'].choices > form_instance.fields['fieldname'].widget.choices > > AFAIK, at some point in the past there were issues with choices not > being updated when the queryset was changed, but that should have been > fixed a long time ago. > > Michael --~--~-~--~~~---~--~~ 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: Start server
Thanks so much guys! :) On Jun 16, 7:43 pm, "Oscar Carlsson" <[EMAIL PROTECTED]> wrote: > No, you don't have to load everything by hand - there is another way :) > > http://superjared.com/entry/django-and-crontab-best-friends/ > > Oscar > > On Mon, Jun 16, 2008 at 11:33 PM, Karen Tracey <[EMAIL PROTECTED]> wrote: > > On Mon, Jun 16, 2008 at 3:50 PM, Molly <[EMAIL PROTECTED]> wrote: > > >> Hey guys, > > >> I created an app and I am trying to launch the server through my > >> pyweb.py code since I will eventually, when this gets working be > >> putting it on a different drive for other computers with different > >> servers to use. > > >> My code works, but when i create a py2exe and i run it, i get an > >> error. > > >> > >> My pyweb.py code: > > >> > >> import os > >> import sys > >> import time > >> from django.core.management import call_command > >> import threading > >> import thread > >> from django.core.management.commands.runserver import Command > >> import webbrowser > > >> sys.path += [r'c:\dev'] > >> sys.path += [r'p:\Hazard_Inventory'] > >> os.environ['DJANGO_SETTINGS_MODULE'] = 'incidents.settings' > > >> #t = thread.start_new_thread(os.system, (u'C:\\Python25\\python C:\\dev > >> incidents\\manage.py runserver > nul', )) > > >> class RunDevServer(threading.Thread): > >>def run(self): > >>s = Command() > >>s.execute(use_reloader=False) > > >> def start_dev_server(): > >>t = RunDevServer() > >>t.setDaemon(False) > >>t.start() > >>time.sleep(.2) > > >> start_dev_server() > > >> webbrowser.open('http://127.0.0.1:8000/admin/base/incident/add/') > > >> > >> The error I get: > > >> > >> Exception in thread Thread-1: > >> Traceback (most recent call last): > >> File "threading.pyo", line 486, in __bootstrap_inner > >> File "pyweb.py", line 20, in run > >> File "django\core\management\base.pyo", line 81, in execute > >> File "django\utils\translation\__init__.pyo", line 73, in activate > >> File "django\utils\translation\__init__.pyo", line 43, in > >> delayed_loader > >> File "django\utils\translation\trans_real.pyo", line 211, in activate > >> File "django\utils\translation\trans_real.pyo", line 200, in > >> translation > >> File "django\utils\translation\trans_real.pyo", line 183, in _fetch > >> AttributeError: 'module' object has no attribute 'auth' > > >> > > >> I don't see how it works before it is an exe. > > >> Any ideas or possibly I need to run the server a different way?? > > >> I would really appreciate any help, thanks :) > > > Here's a blog post from someone who's been down the same road: > > >http://www.jjude.com/index.php/archives/70 > > > Apparently you need to identify and explicitly import every Django module > > your code will need. > > > 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
problem with reverse lookup and multiple foreignKey definitions in abstract model classes
I have a postgres database (8.1.11) with > 200 tables that has regular minor changes(most of them adding fields or tables). So I want to use model inheritance to separate logic from model definition. Inspectdb creates the models which I then edit to make abstract base classes. I'm running Django 7673. Note: I cannot alter the schema without breaking other software that relies on it. The problem is in the reverse relations part. When using the models below I can do the following: f = mgdb_Features.objects.get(pk=10) #gives me a distinct feature fom the database, OK fl= f.mgdb_featureloc_set.all() #should give me all feature locations for 'f'. Looking at the querie that Django produces, it does exactly this, but it joins to the last ForeignKey definition 'srcfeature' in mgdb_Featureloc. However I want to have it joined on 'feature' instead of 'srcfeature'. According to the documentation i should set a unique 'related_name' atribute to force the join on the feature field instead of the srcfeature field of the featureloc table. When I change the definition of the feature foreignKey to: feature = models.ForeignKey('mgdb_Feature', related_name="floc_set") f.floc_set.all() #should give me all feature locations for 'f' but it gives an error message I get the following error: Traceback (most recent call last): File "", line 1, in ? AttributeError: 'QuerySet' object has no attribute 'featureloc_id' I guess this happens because it tries to look at the abstract class instead of the child class, despite the fact that I explicitly relate to the child class in the ForeignKey definition. Question: How can I use the related_name setting to get the desired functionality for the child classes reverse lookups? To cut things short, here is an example of the models stripped from irrelevant things: #abstract base classes class Feature(models.Model): feature_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.ForeignKey('mgdb_Cvterm') class Meta: abstract=True class Featureloc(models.Model): featureloc_id = models.IntegerField(primary_key=True) feature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here srcfeature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here fmin = models.IntegerField() fmax = models.IntegerField() class Meta: abstract=True # child classes class mgdb_Feature(Feature): class Meta(Feature.Meta): db_table = u'feature' def __unicode__(self): return self.name class mgdb_Featureloc(Featureloc): class Meta(Featureloc.Meta): db_table = u'featureloc' --~--~-~--~~~---~--~~ 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: ModelForms
> form.category.queryset = > Category.objects.filter(blog__exact=request.user.author_set.all() > [0].blog) print form.category.queryset I am somewhat surprised that this would work at all. The field objects should be accessible via FormClass.base_fields['fieldname'] or form_instance.fields['fieldname'] so you should be able to say for example: form_instance.fields['fieldname'].queryset = myqueryset There is also: form_instance.fields['fieldname'].choices form_instance.fields['fieldname'].widget.choices AFAIK, at some point in the past there were issues with choices not being updated when the queryset was changed, but that should have been fixed a long time ago. Michael --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Problem with multiple ForeignKey definitions and reverse relationships using abstract base classes
I have a postgres database (8.1.11) with > 200 tables that has regular minor changes(most of them adding fields or tables). So I want to use model inheritance to separate logic form model definition. Inspectdb creates the models which I then edit to make abstract base classes. I'm running Django 7673. Note: I cannot alter the schema without breaking other software that relies on it. The problem is in the reverse relations part. When using the models below I can do the following: f = mgdb_Features.objects.get(pk=10) #gives me a distinct feature fom the database, OK fl= f.mgdb_featureloc_set.all() #should give me all feature locations for 'f'. Looking at the querie that Django produces, it does exactly this, but it joins to the last ForeignKey definition 'srcfeature' in mgdb_Featureloc. However I want to have it joined on 'feature' instead of 'srcfeature'. According to the documentation i should set a unique 'related_name' atribute to force the join on the feature field instead of the srcfeature field of the featureloc table. When I change the definition of the feature foreignKey to: feature = models.ForeignKey('mgdb_Feature', related_name="floc_set") I get the folloing error: Traceback (most recent call last): File "", line 1, in ? AttributeError: 'QuerySet' object has no attribute 'featureloc_id' I guess this happens because it tries to look at the abstract class instead of the child class, despite the fact that I explicitly relate to the child class in the ForeignKey definition. Question: How can I use the related_name setting to get the desired functionality for the child classes reverse lookups? To cut things short, here is an example of the models stripped from irrelevant things: #abstract base classes class Feature(models.Model): feature_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.ForeignKey('mgdb_Cvterm') class Meta: abstract=True class Featureloc(models.Model): featureloc_id = models.IntegerField(primary_key=True) feature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here srcfeature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here fmin = models.IntegerField() fmax = models.IntegerField() class Meta: abstract=True # child classes class mgdb_Feature(Feature): class Meta(Feature.Meta): db_table = u'feature' def __unicode__(self): return self.name class mgdb_Featureloc(Featureloc): class Meta(Featureloc.Meta): db_table = u'featureloc' --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Problem with multiple ForeignKey definitions and reverse relationships using abstract base classes
I have a postgres database (8.1.11) with > 200 tables that has regular minor changes(most of them adding fields or tables). So I want to use model inheritance to separate logic form model definition. Inspectdb creates the models which I then edit to make abstract base classes. I'm running Django 7673. Note: I cannot alter the schema without breaking other software that relies on it. The problem is in the reverse relations part. When using the models below I can do the following: f = mgdb_Features.objects.get(pk=10) #gives me a distinct feature fom the database, OK fl= f.mgdb_featureloc_set.all() #should give me all feature locations for 'f'. Looking at the querie that Django produces, it does exactly this, but it joins to the last ForeignKey definition 'srcfeature' in mgdb_Featureloc. However I want to have it joined on 'feature' instead of 'srcfeature'. According to the documentation i should set a unique 'related_name' atribute to force the join on the feature field instead of the srcfeature field of the featureloc table. When I change the definition of the feature foreignKey to: feature = models.ForeignKey('mgdb_Feature', related_name="floc_set") I get the folloing error: Traceback (most recent call last): File "", line 1, in ? AttributeError: 'QuerySet' object has no attribute 'featureloc_id' To cut things short, here is an example of the models stripped from irrelevant things: #abstract base classes class Feature(models.Model): feature_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.ForeignKey('mgdb_Cvterm') class Meta: abstract=True class Featureloc(models.Model): featureloc_id = models.IntegerField(primary_key=True) feature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here srcfeature = models.ForeignKey('mgdb_Feature') # i'm linking to the non-abstract child class here fmin = models.IntegerField() fmax = models.IntegerField() class Meta: abstract=True # child classes class mgdb_Feature(Feature): class Meta(Feature.Meta): db_table = u'feature' def __unicode__(self): return self.name class mgdb_Featureloc(Featureloc): class Meta(Featureloc.Meta): db_table = u'featureloc' --~--~-~--~~~---~--~~ 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: Overwriting the delete() Method in a Model
Cool! Thank you very much for your response. i ll use signals! regards Dan --~--~-~--~~~---~--~~ 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: Model - Only allow One
On 16 juin, 22:23, ocgstyles <[EMAIL PROTECTED]> wrote: > The client wants certain parts of the site to be editable, I don't > particularly agree with the logic, simply because why take a DB hit > (although small) just to grab text from a database for an "About" page > when that text us USUALLY static. This is easily cured by using a cache, and Django does have a cache system, so I wouldn't worry that much about this point. Anyway, most CMS are just that - db storage for mostly static content !-) Also and FWIW, there's also and already a Django app for this - Flatpage. But anyway, even if you roll your own, I don't get why you should want to restrict to only one instance - what you want (IMVHO) as a model is not an "About", it's a general mechanism for storing text fragments. In this case, I'd go for something with a slug as primary key (or as unique field in addition to an auto primary key), and a convention that the 'about' page (or fragment of..) is slugged "about". My 2 cents... (snip) --~--~-~--~~~---~--~~ 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: Overwriting the delete() Method in a Model
AFAIK, related models are not deleted by invoking delete(). A better way to recognize deletion is the use of signals, i.e. pre_delete and post_delete http://code.djangoproject.com/wiki/Signals Hope that helps. Regards, Daniel Am Dienstag, den 17.06.2008, 02:54 -0700 schrieb Daniel Austria: > Hi there, > > got a Problem. Maybe someone knows a solution. > > I have a model Data which is linked via a foreignkey to the model > Participant. > I have overwritten the delete() Method in the model Data. > When i delete a instance of Data via the Admin-Interface, delete() is > called appropriately. > When i delete a instance of Participant, all related Data instances > are delete too (like it should) but delete() is not called > > Strange. What should i do to recognize, that a Data instance is > deleted? > > regards, > Dan > > --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
smart cache management
Is there anything built into the cache system to manage the deletion/ invalidating of cache? All the examples seem to be based on setting a time. --~--~-~--~~~---~--~~ 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: What am I doing that is sooo wrong with newforms??
Thanks - it was late and I got my objects messed up. I did try the commit=False save but then I wasn't saving the object returned, but assigning to the same object (i.e. form) and trying to RESAVE that.. Thanks again. Richard (another happy django convert). On Jun 17, 12:03 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > You can't assign to the form so your code should look like: > > if form.is_valid(): > c = form.save(commit=False) > c.user = request.user > c.save() > > calling save on the form with commit=False will create a model object, > but won't save it to the db. > > On Jun 16, 5:55 pm, "Karen Tracey" <[EMAIL PROTECTED]> wrote: > > > On Mon, Jun 16, 2008 at 6:49 PM, Richard Green <[EMAIL PROTECTED]> > > wrote: > > > > Hi there - has anybody got a simple example of a newform that has a > > > few fields that are not edited by the user - a simple example is a > > > "comment" field - > > > the table looks something like : > > > > class Comment(models.Model): > > >commentText = models.CharField(max_length=100) > > >commentUser = models.ForeignKey(User, editable=False) > > > > The form : > > > > class CommentForm(ModelForm): > > >class Meta: > > >model = Comment > > > > and in the view : > > > > @login_required > > > def add_comment(request): > > >if request.method == 'POST': > > >form = CommentForm(request.POST) > > >if form.is_valid(): > > >u = request.user > > >form.user = u > > >form.save() > > > > ( I won't bore you with the rest...) > > > > Pretty frickin simple right? For the life of me I can't get it to > > > work ! Please don't just point me towards the docs at > > >http://www.djangoproject.com/documentation/modelforms/asthey don't > > > have any real concrete working examples I can work from - and the > > > statement : "To avoid this failure, you must instantiate your model > > > with initial values for the missing, but required fields, or use > > > save(commit=False) and manually set any extra required fields:" just > > > does NOT work for me > > > > A working 20 line example would suit me grandly !! Thanks in advance, > > > Richard. > > > You seem to have gotten so frustrated that you neglected to mention what, > > exactly, isn't working? Is the form not showing what you want, are you > > getting an error, etc? More specifics on what is going wrong would probably > > help someone help you. > > > 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Overwriting the delete() Method in a Model
Hi there, got a Problem. Maybe someone knows a solution. I have a model Data which is linked via a foreignkey to the model Participant. I have overwritten the delete() Method in the model Data. When i delete a instance of Data via the Admin-Interface, delete() is called appropriately. When i delete a instance of Participant, all related Data instances are delete too (like it should) but delete() is not called Strange. What should i do to recognize, that a Data instance is deleted? regards, Dan --~--~-~--~~~---~--~~ 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: Model - Only allow One
If you just want an editable "about" page, the flatpages app might do what you want. http://www.djangoproject.com/documentation/flatpages/ Regards, Daniel Am Montag, den 16.06.2008, 13:23 -0700 schrieb ocgstyles: > The client wants certain parts of the site to be editable, I don't > particularly agree with the logic, simply because why take a DB hit > (although small) just to grab text from a database for an "About" page > when that text us USUALLY static. > > So thinking of this "About" page, maybe the client just tells a little > about the business etc, but maybe wants to update it occasionally. I > implemented it as a "About" class in a "Section" module. But with > that model, you can add multiple "About" texts. One way I thought of > doing it was to grab the latest edited object like this: > > class About(models.Model): >text = models.TextField() >pub_date = models.DateTimeField(auto_now=True) > > Then just use: > > About.objects.order_by('-pub_date') > > to retrieve the latest edited version. So having many versions isn't > a problem... > > Just wondered if there was a better way to handle this. > > > On Jun 14, 2:41 pm, bruno desthuilliers > <[EMAIL PROTECTED]> wrote: > > On 14 juin, 15:53, ocgstyles <[EMAIL PROTECTED]> wrote: > > > > > Is there a way create a restriction that will only allow one instance > > > of a model? > > > > The closest you could get would be to define a model with a unique not > > editable field and override the save method to make this field a > > constant value. But that wont work for direct database access. > > > > Anyway, why would you want such a thing ? > > --~--~-~--~~~---~--~~ 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: Changing admin index
I think there should be a better way to do this. I believe that there should be a way to override the admin index for each application separately. It would also have to be a way to specify the way these templates are displayed. I'm currently trying to override the admin index of one application, but I would still like the other applications to behave normally. Should this discussion be moved to the developers group? Tx Jurie-Jan --~--~-~--~~~---~--~~ 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: library import issue.
The server is running suExec therefore Apache executes as the user. So it should be able to read my library. James On Mon, Jun 16, 2008 at 5:08 PM, Karen Tracey <[EMAIL PROTECTED]> wrote: > On Mon, Jun 16, 2008 at 9:19 AM, James Matthews <[EMAIL PROTECTED]> > wrote: > >> Karen >> >> The library path is in both LD_LIBRARY_PATH and the PYTHONPATH > > > You mean you've specified it in the appropriate config file? Based on the > results, though, it doesn't seem to be working. What, exactly, did you > specify where? I'm assuming you are using a setup similar to what is > described here: > > > http://www.djangoproject.com/documentation/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache > > ? > > If so then a couple of things occur to me. It sounds like your code will > be running in the context of an Apache-spawned process, so a path like > "~/opt/lib" as you mention in your first mail won't, I don't think, resolve > to your home directory's opt/lib. Did you fully-specify the path wherever > you put it? The other possibility is that the Apache-spawned process does > not have permission to read this directory under your home directory. Have > you changed permissions so that the Apache process can read this directory? > > Karen > > > > > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: ModelForms
I've been looking through the ModelForms code and can't really find a way to fix this. I changed the view code to this: print form.category.queryset form.category.queryset = Category.objects.filter(blog__exact=request.user.author_set.all() [0].blog) print form.category.queryset And my console output is this: [, , ] [] So the first line is all of the categories and the second line is the filtered queryset. However, the html form still shows all of the categories... On Jun 17, 2:06 am, "Jonas Oberschweiber" <[EMAIL PROTECTED]> wrote: > Hmm, yeah, I guess it should... I don't really know much about the > inner workings of ModelForms, but you could try inserting print > statements or something the like directly in the django code for > testing purposes. Or just look at the django code. That almost always > solves the problems I have. > > On Tue, Jun 17, 2008 at 8:03 AM, emont88 <[EMAIL PROTECTED]> wrote: > > > Ok, that makes sense, but I'm still getting weird behavior. > > Right after I call limit_categories() in my view, I inserted the print > > statement: "print form.category.queryset" so that I can see the > > contents of the queryset printed to the console. The result is that > > the console shows the correct thing - only the categories that belong > > to the current blog. However, the form itself still somehow displays > > all of the categories, or the categories that belong to the previous > > user's blog if I just logged out and logged in. > > If form.category.queryset is showing the right thing when printed to > > the console, shouldn't that be exactly what ends up in the html form? > > > On Jun 17, 1:37 am, "Jonas Oberschweiber" <[EMAIL PROTECTED]> > > wrote: > >> AFAIK querysets are always cached. > > >> On Tue, Jun 17, 2008 at 7:06 AM, emont88 <[EMAIL PROTECTED]> wrote: > > >> > I'm running into an interesting problem with ModelForms. > >> > I have a blogging app that handles multiple blogs, which makes things > >> > tricky with categories, because each category needs to belong to a > >> > specific blog, so an author editing blog1 should not be allowed to > >> > post an Entry to a Category from blog2. I am using ModelForms to > >> > generate the forms for posting a new Entry, which makes things pretty > >> > straightforward except for the Category foreignkey. I wrote a method > >> > "limit_categories" in my EntryForm class, which I call from the view > >> > after creating the form. This method takes in a Blog object, and > >> > limits the queryset for the Category foreignkey to categories that > >> > belong to that Blog. All seems good at this point. > >> > When I actually access the form though, the behavior is pretty > >> > random. Sometimes, it will not filter the categories at all. Other > >> > times, if I logout and login as another user, it will retain the > >> > category choices from the previous user. After a couple of refreshes > >> > though, it eventually works. > >> > I don't think I have any type of caching enabled, so I'm not sure > >> > what's going on here. > > >> > Here is some of my code, hopefully enough to figure things out: > > >> > class EntryForm(forms.ModelForm): > >> > class Meta: > >> > model = Entry > >> > fields = ('title', 'slug', 'pub_date', 'category', 'body', > >> > 'excerpt') > >> > # Must define category explicitly so that limit_categories() can > >> > access it > >> > category = forms.ModelChoiceField(queryset=Category.objects.all()) > > >> > def limit_categories(self, blog): > >> > # Limits the category choices to those belonging to the > >> > current blog > >> > print "Limiting categories" > > >> > self.category._set_queryset(Category.objects.filter(blog__exact=blog)) > > >> > @login_required > >> > def admin_entry_edit(request, entry_id): > >> > entry = get_object_or_404(Entry, id__exact=entry_id) > >> > if request.method == 'POST': > >> > form = EntryForm(request.POST, instance=entry) > >> > if form.is_valid(): > >> > form.save() > >> > request.user.message_set.create(message="Entry saved > >> > successfully.") > >> > return HttpResponseRedirect('../') > >> > else: > >> > form = EntryForm(instance=entry) > >> > form.limit_categories(request.user.author_set.all()[0].blog) > >> > context = {'form': form} > >> > return render_to_response('blogs/admin/edit.html', context, > >> > context_instance=RequestContext(request)) --~--~-~--~~~---~--~~ 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: ModelForms
Hmm, yeah, I guess it should... I don't really know much about the inner workings of ModelForms, but you could try inserting print statements or something the like directly in the django code for testing purposes. Or just look at the django code. That almost always solves the problems I have. On Tue, Jun 17, 2008 at 8:03 AM, emont88 <[EMAIL PROTECTED]> wrote: > > Ok, that makes sense, but I'm still getting weird behavior. > Right after I call limit_categories() in my view, I inserted the print > statement: "print form.category.queryset" so that I can see the > contents of the queryset printed to the console. The result is that > the console shows the correct thing - only the categories that belong > to the current blog. However, the form itself still somehow displays > all of the categories, or the categories that belong to the previous > user's blog if I just logged out and logged in. > If form.category.queryset is showing the right thing when printed to > the console, shouldn't that be exactly what ends up in the html form? > > On Jun 17, 1:37 am, "Jonas Oberschweiber" <[EMAIL PROTECTED]> > wrote: >> AFAIK querysets are always cached. >> >> On Tue, Jun 17, 2008 at 7:06 AM, emont88 <[EMAIL PROTECTED]> wrote: >> >> > I'm running into an interesting problem with ModelForms. >> > I have a blogging app that handles multiple blogs, which makes things >> > tricky with categories, because each category needs to belong to a >> > specific blog, so an author editing blog1 should not be allowed to >> > post an Entry to a Category from blog2. I am using ModelForms to >> > generate the forms for posting a new Entry, which makes things pretty >> > straightforward except for the Category foreignkey. I wrote a method >> > "limit_categories" in my EntryForm class, which I call from the view >> > after creating the form. This method takes in a Blog object, and >> > limits the queryset for the Category foreignkey to categories that >> > belong to that Blog. All seems good at this point. >> > When I actually access the form though, the behavior is pretty >> > random. Sometimes, it will not filter the categories at all. Other >> > times, if I logout and login as another user, it will retain the >> > category choices from the previous user. After a couple of refreshes >> > though, it eventually works. >> > I don't think I have any type of caching enabled, so I'm not sure >> > what's going on here. >> >> > Here is some of my code, hopefully enough to figure things out: >> >> > class EntryForm(forms.ModelForm): >> >class Meta: >> >model = Entry >> >fields = ('title', 'slug', 'pub_date', 'category', 'body', >> > 'excerpt') >> ># Must define category explicitly so that limit_categories() can >> > access it >> >category = forms.ModelChoiceField(queryset=Category.objects.all()) >> >> >def limit_categories(self, blog): >> ># Limits the category choices to those belonging to the >> > current blog >> >print "Limiting categories" >> >> > self.category._set_queryset(Category.objects.filter(blog__exact=blog)) >> >> > @login_required >> > def admin_entry_edit(request, entry_id): >> >entry = get_object_or_404(Entry, id__exact=entry_id) >> >if request.method == 'POST': >> >form = EntryForm(request.POST, instance=entry) >> >if form.is_valid(): >> >form.save() >> >request.user.message_set.create(message="Entry saved >> > successfully.") >> >return HttpResponseRedirect('../') >> >else: >> >form = EntryForm(instance=entry) >> >form.limit_categories(request.user.author_set.all()[0].blog) >> >context = {'form': form} >> >return render_to_response('blogs/admin/edit.html', context, >> > context_instance=RequestContext(request)) > > > --~--~-~--~~~---~--~~ 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: ModelForms
Ok, that makes sense, but I'm still getting weird behavior. Right after I call limit_categories() in my view, I inserted the print statement: "print form.category.queryset" so that I can see the contents of the queryset printed to the console. The result is that the console shows the correct thing - only the categories that belong to the current blog. However, the form itself still somehow displays all of the categories, or the categories that belong to the previous user's blog if I just logged out and logged in. If form.category.queryset is showing the right thing when printed to the console, shouldn't that be exactly what ends up in the html form? On Jun 17, 1:37 am, "Jonas Oberschweiber" <[EMAIL PROTECTED]> wrote: > AFAIK querysets are always cached. > > On Tue, Jun 17, 2008 at 7:06 AM, emont88 <[EMAIL PROTECTED]> wrote: > > > I'm running into an interesting problem with ModelForms. > > I have a blogging app that handles multiple blogs, which makes things > > tricky with categories, because each category needs to belong to a > > specific blog, so an author editing blog1 should not be allowed to > > post an Entry to a Category from blog2. I am using ModelForms to > > generate the forms for posting a new Entry, which makes things pretty > > straightforward except for the Category foreignkey. I wrote a method > > "limit_categories" in my EntryForm class, which I call from the view > > after creating the form. This method takes in a Blog object, and > > limits the queryset for the Category foreignkey to categories that > > belong to that Blog. All seems good at this point. > > When I actually access the form though, the behavior is pretty > > random. Sometimes, it will not filter the categories at all. Other > > times, if I logout and login as another user, it will retain the > > category choices from the previous user. After a couple of refreshes > > though, it eventually works. > > I don't think I have any type of caching enabled, so I'm not sure > > what's going on here. > > > Here is some of my code, hopefully enough to figure things out: > > > class EntryForm(forms.ModelForm): > > class Meta: > > model = Entry > > fields = ('title', 'slug', 'pub_date', 'category', 'body', > > 'excerpt') > > # Must define category explicitly so that limit_categories() can > > access it > > category = forms.ModelChoiceField(queryset=Category.objects.all()) > > > def limit_categories(self, blog): > > # Limits the category choices to those belonging to the > > current blog > > print "Limiting categories" > > > self.category._set_queryset(Category.objects.filter(blog__exact=blog)) > > > @login_required > > def admin_entry_edit(request, entry_id): > > entry = get_object_or_404(Entry, id__exact=entry_id) > > if request.method == 'POST': > > form = EntryForm(request.POST, instance=entry) > > if form.is_valid(): > > form.save() > > request.user.message_set.create(message="Entry saved > > successfully.") > > return HttpResponseRedirect('../') > > else: > > form = EntryForm(instance=entry) > > form.limit_categories(request.user.author_set.all()[0].blog) > > context = {'form': form} > > return render_to_response('blogs/admin/edit.html', context, > > context_instance=RequestContext(request)) --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---