Re: Multi-db: is database routing per request possible?
Russ, Your gut feeling confirms my suspicion. Changing the lines to the following fixes my problem: db = model_instance._state.db if db is None: db = router.db_for_write(model_instance.__class__, instance=model_instance) qs = self.rel.to._default_manager.using(db).filter(**{self.rel.field_name:value}) The validation of many2many fields (further down in the same file) has a similar issue and would need fixing too. I'll file a bug on the topic. I somehow feel a bit uncomfortable with this approach: the formfield constructor accepts the "using" argument to direct the queries to a database, but since the validation is model-based (not form-based) that info is not used in validation. You rely on guess-work like the above or on the fact that the routing logic is in sync with the "using" argument you provided. This can't be DRY... Regards, Johan On Jun 16, 2:25 am, Russell Keith-Magee wrote: > On Tue, Jun 15, 2010 at 9:11 PM, johan de taeye > > > > wrote: > > >> You can't do this with a router; as you've noted, the router doesn't > >> have any information about the request in which it is being used. > > >> However, you could do it by manually requesting your database > >> connection whenever you use the database. For example: > > >> Author.objects.using('otherdb').filter(...) > > >> will perform a query that is guaranteed to operate on the 'otherdb', > >> regardless of what the router says. > > > I was able to get this part working fine. Since most views are based > > on a reuable generic one this was pretty easy to do anyway. > > > Getting ModelForms (or ModelAdmin) to work with foreign keys is a > > different story: When the form/model is validated, the field value is > > searched in the source table to verify the key exists. This lookup > > uses the _default_manager (see code below), which isn't aware of the > > request any more and always checks on the default database (unless I > > can route it). As a result I always get a validation error on the > > form. > > > Looks like I need a patched/smarter RelatedField that is aware of the > > database to look in? > > You're in somewhat uncharted territory here, so I can't give you a > simple prepared answer. However, you certainly appear to be on the > right track. > > It's also possible that you've discovered an edge case bug -- looking > at the code, my gut tells me that the _default_manager call should be > forced onto the same database as model_instance - i.e., the query > should be: > > db = router.db_for_read(self.rel.to, instance=model_instance) > qs = > self.re.to._default_manager.using(db).filter(**self.rel.field_name:value}) > > or similar. I'd need to do more tests to confirm this, though. Feel > free to log a bug if you can reduce this to a test case that > demonstrates that this is indeed a bug. > > Yours, > Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Model validation (not form validation)
Hi, I'm making a model, that has a bit complex dependencies between the fields, such as date progression (start_date must not be later than finish_date). I'm looking for a way to validate these dependencies while creating (or saving) the model, but I am not sure which approach should I use. The best solution would be overriding Model's method *clean*, but this seems to work only when working with forms. Another solution utilizes pre_save() or save() methods. Which one is the "proper" one? Regards, Mateusz Haligowski -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: commit=False in Model save?
Today I'm a bit more awake than when I replied yesterday and I realized that you're talking about views here. What I mean however is that I would like to do validation in the model class' save function in models.py. I have tried to use this method on my save function though, but it just gives me the following error: Transaction managed block ended with pending COMMIT/ROLLBACK I don't think it should be pending. My save function will eventually commit or rollback and the error occurs in both cases. So either this method doesn't work when used on a model class' save function, or because it's not a view function, something else needs to happen as well that I don't know of (in case of a rollback the function might for example need to return an error of some kind). I've also come across the problem that the 'through' table of my ManyToManyField is not updated before commit. I call super(Model, self).save(*args, **kwargs) at the start of def save(*args, **kwargs):, but I get an empty list when after super-save I try to retrieve the linked through instances, because they simply do not exist yet. Could anyone tell me if what I'm doing is the right way of approaching it and how it should be done? Thanks! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Overriding fForm class __init__ method
Hi, I have created a form class like this: class VoteRadioForm(forms.Form): choices = forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= True, poll__id = 2), empty_label= None, widget= forms.RadioSelect, ) This class gives me dynamic number of entries for my form, based on the poll_id. But as you may have already seen it, the poll__id is hardcoded in this example. In order to pass different values to poll__id, I tried to generated my choices element inside the __init__ method like this: #choices = forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= True, poll__id = 2), def __init__(self, pid = None, *args, **kwargs): super(VoteRadioForm, self).__init__() self.fields['ch'] = forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= True, poll__id = pid), empty_label= None, widget= forms.RadioSelect, ) The first example(Hardcoded version) works perfectly fine. The second example generates the form correctly, when I use: form = VoteRadioForm(i) However, when I try to validate the data and pass the request object to it, it gives me the following error: int() argument must be a string or a number, not 'QueryDict' I even tried to add *args and **kwargs arguments when initializing my class, just like this example: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ But, it doesn't make any difference. I'm having Pythong 2.6.5 on my Arch Linux machine. I was wondering if anyone has ever had such problem? Thanks in advance -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Overriding fForm class __init__ method
On Jun 16, 10:30 am, DevelopsDjangoApps wrote: > Hi, > > I have created a form class like this: > > class VoteRadioForm(forms.Form): > > choices = > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > True, poll__id = 2), > empty_label= None, > widget= forms.RadioSelect, > ) > > This class gives me dynamic number of entries for my form, based on > the poll_id. But as you may have already seen it, the poll__id is > hardcoded in this example. In order to pass different values to > poll__id, I tried to generated my choices element inside the __init__ > method like this: > > #choices = > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > True, poll__id = 2), > def __init__(self, pid = None, *args, **kwargs): > super(VoteRadioForm, self).__init__() > self.fields['ch'] = > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > True, poll__id = pid), > empty_label= None, > widget= forms.RadioSelect, > ) > > The first example(Hardcoded version) works perfectly fine. The second > example generates the form correctly, when I use: > > form = VoteRadioForm(i) > > However, when I try to validate the data and pass the request object > to it, it gives me the following error: > > int() argument must be a string or a number, not 'QueryDict' > > I even tried to add *args and **kwargs arguments when initializing my > class, just like this example: > > http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ > > But, it doesn't make any difference. > > I'm having Pythong 2.6.5 on my Arch Linux machine. > > I was wondering if anyone has ever had such problem? > > Thanks in advance It's because your 'pid' parameter is grabbing the first argument to the function, which is usually the posted data. Instead, do this: def __init__(self, *args, **kwargs): pid = kwargs.pop('pid', None) super(VoteRadioForm, self).__init__(*args, **kwargs) ...etc... -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Emailing users with invalid local part email addresses
On di, 2010-06-15 at 17:44 +0100, Tom Evans wrote: > I have a bunch of users from one of our subscribers who all have > invalid local parts to their email addresses. > > Eg: > > åsak.østerga...@example.com > jan-åke.hammarstr...@example.com > > Django assumes that all the addresses are valid, and so coerces them > to strings, which of course then blows up when self.to is a list of > non-ascii unicode addresses (and it is entirely reasonable for it to > complain, those email addresses are complete nonsense). > > Is anyone aware of any sort of workaround for this sort of situation? Tell your subscriber to send valid addresses? -- Dennis K. They've gone to plaid! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Overriding fForm class __init__ method
Thanks a lot. Your solution was the right one. However, I just needed to provide 'pid' as the only argument for the pop method. Now when I use the following command in my view it doesn't give me any error: form = VoteRadioForm(request.POST, pid = 2 ) However, I'm having a problem with form validation since is_valid returns false. I think my form is not created correctly. Because when I issue cleaned_data method, I get the following error: 'VoteRadioForm' object has no attribute 'cleaned_data' I need to sleep now. Hopefully, tomorrow I am able to figure out this problem. Thanks On Jun 16, 3:51 am, Daniel Roseman wrote: > On Jun 16, 10:30 am, DevelopsDjangoApps wrote: > > > > > > > Hi, > > > I have created a form class like this: > > > class VoteRadioForm(forms.Form): > > > choices = > > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > > True, poll__id = 2), > > empty_label= None, > > widget= forms.RadioSelect, > > ) > > > This class gives me dynamic number of entries for my form, based on > > the poll_id. But as you may have already seen it, the poll__id is > > hardcoded in this example. In order to pass different values to > > poll__id, I tried to generated my choices element inside the __init__ > > method like this: > > > #choices = > > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > > True, poll__id = 2), > > def __init__(self, pid = None, *args, **kwargs): > > super(VoteRadioForm, self).__init__() > > self.fields['ch'] = > > forms.ModelChoiceField(queryset=Choice.objects.filter(poll__active= > > True, poll__id = pid), > > empty_label= None, > > widget= forms.RadioSelect, > > ) > > > The first example(Hardcoded version) works perfectly fine. The second > > example generates the form correctly, when I use: > > > form = VoteRadioForm(i) > > > However, when I try to validate the data and pass the request object > > to it, it gives me the following error: > > > int() argument must be a string or a number, not 'QueryDict' > > > I even tried to add *args and **kwargs arguments when initializing my > > class, just like this example: > > >http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ > > > But, it doesn't make any difference. > > > I'm having Pythong 2.6.5 on my Arch Linux machine. > > > I was wondering if anyone has ever had such problem? > > > Thanks in advance > > It's because your 'pid' parameter is grabbing the first argument to > the function, which is usually the posted data. > > Instead, do this: > > def __init__(self, *args, **kwargs): > pid = kwargs.pop('pid', None) > super(VoteRadioForm, self).__init__(*args, **kwargs) > ...etc... > > -- > DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Problem in Django App Part 1 Tutorial
Hello, I am a Python newbie and this is my first time I use Django and Python. I was reading the Django App tutorial Part 1 and got stuck in a place. I execute these statements in the Python Shell: >>> from mysite.polls.models import Poll, Choice >>> import datetime >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now()) >>> p.save() >>> p = Poll.objects.get(pk=1) >>> p.was_published_today() For the last statement I get an error: Traceback (most recent call last): File "", line 1, in AttributeError: 'Poll' object has no attribute 'was_published_today' This is my "models.py" file: from django.db import models import datetime class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_today(self): return self.pub_date.date() == datetime.date.today() class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() def __unicode__(self): return self.question I wrote it with IDLE. I thought it was an indentation and whitespace problem, but I followed strictly the identation rules and used only tabs. Also I tried other editors and nothing changed. the error message still shows up. Please help me, what am I doing wrong? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
how to use render_to_response, ajax and javascript variables
Hi, Please can anyone help with an app architecture problem I am having? (I am quite new to Django) I have an app which which serves up XHR requests (via YUI3 io uitility) to urlpatterns. The views make HttpResponses using render_to_response like so: return render_to_response("registration/register.html", { 'form': form, }, context_instance=RequestContext(request)) That is all fine: The html content is rendered in the relevant div (using a YUI3 io's success callback) . But the problem I have - and I may be thinking about this in the wrong way - is that I also want to pick out some variables from the response to use in my js success callback. If I wasn't using django templating this could be straightforwardly achieved with a JSON response parsed client side. So my difficulty is that I want both a rendered template response and some JSON response in the same callback... I have thought about 'enriching' the render_to_response context with these additional variables, inserting them in hidden html fields and then querying the dom for their values - but that feels awkward and also means the response has to be added to the dom before the js can act on their values. This seems like a familiar nut that must be well documented somewhere... :) any help, pointers very appreciated. Thanks Alex -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use render_to_response, ajax and javascript variables
On Wed, Jun 16, 2010 at 1:17 PM, Alex wrote: > Hi, > > Please can anyone help with an app architecture problem I am having? > (I am quite new to Django) > > I have an app which which serves up XHR requests (via YUI3 io > uitility) to urlpatterns. The views make HttpResponses using > render_to_response like so: > > return render_to_response("registration/register.html", { > 'form': form, > }, context_instance=RequestContext(request)) > > That is all fine: The html content is rendered in the relevant div > (using a YUI3 io's success callback) . > > But the problem I have - and I may be thinking about this in the wrong > way - is that I also want to pick out some variables from the response > to use in my js success callback. If I wasn't using django templating > this could be straightforwardly achieved with a JSON response parsed > client side. So my difficulty is that I want both a rendered template > response and some JSON response in the same callback... I have thought > about 'enriching' the render_to_response context with these additional > variables, inserting them in hidden html fields and then querying the > dom for their values - but that feels awkward and also means the > response has to be added to the dom before the js can act on their > values. > > This seems like a familiar nut that must be well documented > somewhere... :) any help, pointers very appreciated. > > Thanks > Alex > The prototype framework allows you to place (small amounts) of JSON into the response header 'X-JSON', which it then evaluates, and stores in transport.headerJSON. If you are using prototype, that could be a solution, or implement your own version of that. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use render_to_response, ajax and javascript variables
Perhaps instead of using render_to_response to generate the response, render the template output to a string and then stuff that in the data structure that you serialise to json along with the other data? Regards, Matt On Jun 16, 1:17 pm, Alex wrote: > > But the problem I have - and I may be thinking about this in the wrong > way - is that I also want to pick out some variables from the response > to use in my js success callback. If I wasn't using django templating > this could be straightforwardly achieved with a JSON response parsed > client side. So my difficulty is that I want both a rendered template > response and some JSON response in the same callback... I have thought > about 'enriching' the render_to_response context with these additional > variables, inserting them in hidden html fields and then querying the > dom for their values - but that feels awkward and also means the > response has to be added to the dom before the js can act on their > values. > > This seems like a familiar nut that must be well documented > somewhere... :) any help, pointers very appreciated. > > Thanks > Alex -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: determining changes in file
El 16/06/10 03:56, tazimk escribió: > I have a text file being written by another process on a server which > I want to watch for changes. Each time a change occurs I'd like to > read the new data and send it to client . Any suggestions will be > valuable . Using Django,Python > If using Linux, Pyinotify may be what you're looking for: http://trac.dbzteam.org/pyinotify -- Gonzalo Delgado -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: mod_wsgi sometimes gives error on first reload but not thereafter
On Jun 15, 6:42 pm, Graham Dumpleton wrote: > This occurs when Apache is first reading HTTP headers for request and > long before it hands it off to any Django application or even > mod_wsgi. Is there anything I can do about this? I assume this means we should pronounce the mod_wsgi setup I have good and not bother trying to use your sample script after all like you discussed in previous email? cs -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
Never mind I solved the problem! For all of you with the same problem: it appears that the first time that you use or import (i'm not really sure) a class in the python shell, it's source-code file is compiled automatically in a ".pyc" file, in the same directory where the source-code file is located and with the same name. After that everytime you import that class, the python interpreter gets it from the ".pyc" file. You added the "was_published_today()" method to the Poll class in the "models.py" file, but the "models.pyc" file still contains the old version even after an re-import or reuse of the Poll class. It seems that Python compiles the module only the first time it is imported, and after that even if the source-code in "models.py" changes, the python interpreter doesn't automatically recompile the new version of the code. That's why the ".pyc" file still has the old version of the Poll class and that's where the Python interpreter imports the class from so you get the Traceback (most recent call last): File "", line 1, in AttributeError: 'Poll' object has no attribute 'was_published_today' error in the interpreter. I think that it has nothing to do with indentation or whitespaces. If you delete the ".pyc" files for every file you change, then there should be no more problems. Just go to polls/ directory and delete "models.pyc" (or any other ".pyc" file if you had made changes to "settings.py" or "urls.py"). Everything should work fine now. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
Never mind I solved the problem! For all of you with the same problem: it appears that the first time that you use or import (i'm not really sure) a class in the python shell, it's source-code file is compiled automatically in a ".pyc" file, in the same directory where the source-code file is located and with the same name. After that everytime you import that class, the python interpreter gets it from the ".pyc" file. You added the "was_published_today()" method to the Poll class in the "models.py" file, but the "models.pyc" file still contains the old version even after an re-import or reuse of the Poll class. It seems that Python compiles the module only the first time it is imported, and after that even if the source-code in "models.py" changes, the python interpreter doesn't automatically recompile the new version of the code. That's why the ".pyc" file still has the old version of the Poll class and that's where the Python interpreter imports the class from so you get the Traceback (most recent call last): File "", line 1, in AttributeError: 'Poll' object has no attribute 'was_published_today' error in the interpreter. I think that it has nothing to do with indentation or whitespaces. If you delete the ".pyc" files for every file you change, then there should be no more problems. Just go to polls/ directory and delete "models.pyc" (or any other ".pyc" file if you had made changes to "settings.py" or "urls.py"). Everything should work fine now. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
I noticed you are importing your project name, are you invoking your "python manage.py shell" from within your project folder? If you are, try the following: project_folder/python manage.py shell >>> from polls.models import Poll >>> dir(Poll) The above should show you that "was_published_today" method in a list. Try to call the method again: >>> Poll.objects.get(pk=1).was_published_today() On Jun 16, 8:08 am, "!...@!!!" wrote: > Hello, > I am a Python newbie and this is my first time I use Django and > Python. > I was reading the Django App tutorial Part 1 and got stuck in a place. > > I execute these statements in the Python Shell: > > >>> from mysite.polls.models import Poll, Choice > >>> import datetime > >>> p = Poll(question="What's up?", pub_date=datetime.datetime.now()) > >>> p.save() > >>> p = Poll.objects.get(pk=1) > >>> p.was_published_today() > > For the last statement I get an error: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'Poll' object has no attribute 'was_published_today' > > This is my "models.py" file: > > from django.db import models > import datetime > > class Poll(models.Model): > question = models.CharField(max_length=200) > pub_date = models.DateTimeField('date published') > def __unicode__(self): > return self.question > def was_published_today(self): > return self.pub_date.date() == datetime.date.today() > > class Choice(models.Model): > poll = models.ForeignKey(Poll) > choice = models.CharField(max_length=200) > votes = models.IntegerField() > def __unicode__(self): > return self.question > > I wrote it with IDLE. > I thought it was an indentation and whitespace problem, but I followed > strictly the identation rules and used only tabs. > Also I tried other editors and nothing changed. the error message > still shows up. > Please help me, what am I doing wrong? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Is there any kind of verbose_name for apps?
And if not how can I emulate that? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: modeling a book repository
One more reply after doing some more research. Apparently this has been discussed quite a bit and a solution may appear in the 1.3 release: http://code.djangoproject.com/ticket/7539 But, to handle the situation where you want to avoid a cascade delete (which was my problem with my previous/next linked list of chapters), override the delete method on the class: def delete(self): self.previous_set.clear() self.next_set.clear() super(Chapter,self).delete() This works only if the ForeignKey can be null, so for example, the fields look like this: previous = models.ForeignKey('self', blank=True,null=True,related_name='a') next = models.ForeignKey('self', blank=True,null=True,related_name='b') Note however, I haven't tested this code yet, caveat emptor. From what I can glean from the docs and the forums though, it's close to correct. thanks, --Tim On Jun 15, 1:41 pm, Tim Arnold wrote: > Thanks for both these great answers. After thinking about it, I think > either way I go I'll need to modify both the add and delete methods. > The linked list seems more natural to me, but since my writers will be > using the interface, the sequence number may be a better choice for > them. More to think about... > > thanks again! > --Tim > > On Jun 15, 12:48 pm, Dan Harris wrote: > > > > > Hi Tim, > > > You can probably override the Chapter model's delete method. Inside > > this overridden delete method you can swap around your FK's of > > previous and next chapters before calling the super classes delete. > > Basically do your linked list management inside the delete method > > before the calling the super class delete. This way when the cascades > > go through it doesn't have links to next or previous chapters and not > > everything is deleted. > > > Hope this helps, > > > Dan Harris > > dih0...@gmail.com > > > On Jun 15, 12:11 pm, Tim Arnold wrote: > > > > Hi, > > > I have a model for a Book that contains Chapters. My problem is > > > figuring out the ordered sequence of Chapters in a Book. I first tried > > > setting Chapter up as a linked list with pointers to the previous > > > Chapter and next Chapter. That worked okay, but when I need to delete > > > a Chapter, the prev/next links cascade through and it wants to delete > > > all the chapters. > > > > I'm now thinking of adding a 'sequence number' to the chapter model > > > which I suppose will work okay, but if want to add or delete a chapter > > > later on, I'll have to renumber all the later chapters in the > > > database. > > > > This is a little tricky--does anyone have a better solution? > > > thanks, > > > --Tim Arnold -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response ?
In case of views that contain login or logout, this sessionid is different from the one submitted in request's Coockie header. I need to retrieve it before returning response for some purpose. I need to retrieve it between 'login(...)' and 'return HttpResponse(...)' How can I do this ? Django adds the new session entry to the table 'django_session' during django.contrib.auth.login(). Django has to attach sessionid with Set-Cookie during returning response. How does django identifies which sessionid to attach ? And that is what exactly I want to fetch before returning from view. Is there a way I can fetch this sessionid ? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: mod_wsgi sometimes gives error on first reload but not thereafter
On Jun 16, 3:07 pm, Chris Seberino wrote: > On Jun 15, 6:42 pm, Graham Dumpleton > wrote: > > > This occurs when Apache is first reading HTTP headers for request and > > long before it hands it off to any Django application or even > > mod_wsgi. > > Is there anything I can do about this? I assume this means we should > pronounce the mod_wsgi setup I have good and not bother trying to use > your sample script after all like you discussed in previous email? > Since it looks like a problem with the http communication between the browser and the server you might find it worth hooking something like TCPWatch (http://hathawaymix.org/Software/TCPWatch) in between the two and look at what's going back and forth to try spot where the problem is being introduced. On the face of it, it seems most likely it's your copy of firefox misbehaving for some reason! Matt -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use render_to_response, ajax and javascript variables
Just one comment - Django lets you render to JSON just as easily as rendering to HTML (or XML). You just write your template as JSON and set the MIME type for the response accordingly. Because I control my JSON parsing on the client side, I set the MIME type to text/plain but you could set to another if you wanted. I realise that this doesn't actually solve your problem of combining HTML and JSON in a response and I think one of the other comments addresses this but I wanted to make the point that JSON by itself is easy. Cheers Ian On Jun 16, 1:17 pm, Alex wrote: > Hi, > > Please can anyone help with an app architecture problem I am having? > (I am quite new to Django) > > I have an app which which serves up XHR requests (via YUI3 io > uitility) to urlpatterns. The views make HttpResponses using > render_to_response like so: > > return render_to_response("registration/register.html", { > 'form': form, > }, context_instance=RequestContext(request)) > > That is all fine: The html content is rendered in the relevant div > (using a YUI3 io's success callback) . > > But the problem I have - and I may be thinking about this in the wrong > way - is that I also want to pick out some variables from the response > to use in my js success callback. If I wasn't using django templating > this could be straightforwardly achieved with a JSON response parsed > client side. So my difficulty is that I want both a rendered template > response and some JSON response in the same callback... I have thought > about 'enriching' the render_to_response context with these additional > variables, inserting them in hidden html fields and then querying the > dom for their values - but that feels awkward and also means the > response has to be added to the dom before the js can act on their > values. > > This seems like a familiar nut that must be well documented > somewhere... :) any help, pointers very appreciated. > > Thanks > Alex -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Multiple AJAX sends within a views.py-function
Cool. That is a clever way to subvert (I don't mean this negatively) the response generation. I do have a couple of comments: 1) It relies on the response being sent to the client as it is generated and not buffered by the server. That is clearly working for you and I don't know the internals of the different web servers to know if any would break this. I suspect this will work with all servers so nice trick. 2) I would be worried by resources on the web server if you expect many connections of this type. In most servers that I have seen, each request is assigned to a thread from a pool and the thread is not freed up until the request is completed. Each of these requests will tie up a thread until it is completed (I think). This is likely to work well for a small number of simultaneous connections but if you had more simultaneous clients than threads in your pool, I would expect new requests to be blocked / delayed. If you only expect one or a small number of clients to use this request at one time then you are fine. If you want to scale this then I think that you may have a problem. I suggest testing this by setting up more simultaneous clients than your server has threads set in the pool. The test might be fiddly to set up and you could reconfigure the server to have fewer threads and add delays into the calculations to make it easier to test. This is the reason why I chose to build my own custom server for long- running requests but that causes a lot of extra work and possible bugs so I don't recommend it if there is any alternative. Cheers Ian On Jun 15, 8:45 pm, Christoph Siedentop wrote: > Hi Dmitry, hi Ian, > > thanks for the help. > > I got it to work. Here is what I am doing. > > Django gets a request for "/data.json". A view function is called. > This is my function: > > def data(request): > return HttpResponse(subsampling(), mimetype='application/javascript') > > subsampling() is an iterator, i.e. it yields data every once in while. > Look > at:http://docs.djangoproject.com/en/dev/ref/request-response/#passing-it... > > I am yielding simplejson.dumps(my_dict) + '\n' which is then received > by the client. The original request for data.json came from an ajax > function (using jQuery). At the beginning using 'beforeSend' I start a > function that takes the XmlHttpRequest.responseText and sees how much > data has arrived and appends that data to the already existing data. I > do this every 10ms and stop once the xmr.readyState indicates that the > connection was closed. > > I am quite satisfied with this result. It does not use much memory and > is much faster (and feels much faster) than before. > > I tested it under Chromium, Firefox and Konqueror. I will add some > additional functionality and make it a nice graphics module in the > late summer. Probably GPL'ed. It would be for people like me, who have > lots of data and want to make them available interactively. > > Regards, > Christoph > <> -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Cannot import a module when deployed in Apache WSGI
This may be very silly, but I cant figure out the problem. Everything seems to be in place. I have deployed my django project to Apache using mod_wsgi. In urls.py I am mapping "gateway/" to gateway.py which imports 'pyamf' module. The problem is, even though pyamf module is in python path, its not able to find it. I can import it from command line and when in django development server. ViewDoesNotExist at /gateway/ Could not import TestProject.gateway. Error was: No module named pyamf Request Method: GET Request URL:http://localhost/dj/gateway/ Django Version: 1.2.1 Exception Type: ViewDoesNotExist Exception Value: Could not import TestProject.gateway. Error was: No module named pyamf Exception Location: D:\Python2.6\lib\site-packages\django\core \urlresolvers.py in _get_callback, line 134 Python Executable: C:\Program Files\Apache Software Foundation \Apache2.2\bin\httpd.exe Python Version: 2.6.0 Python Path:['D:\\Python2.6\\python26.zip', 'D:\\Python2.6\\Lib', 'D:\ \Python2.6\\DLLs', 'D:\\Python2.6\\Lib\\lib-tk', 'C:\\Program Files\ \Apache Software Foundation\\Apache2.2', 'C:\\Program Files\\Apache Software Foundation\\Apache2.2\\bin', 'D:\\Python2.6', 'D:\\Python2.6\ \lib\\site-packages', 'D:/DjangoProjects', 'D:\\Python2.6\\Lib\\site- packages\\pyamf'] Server time:Wed, 16 Jun 2010 20:37:57 +0530 Any idea whats going on? As you can see, pyamf is in python path. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Seeking Django vs. Joomla comparison
Thank you all for your thoughts. I liked the link to article that compares Drupal with Django. I wish there was a Joomla vs. Drupal compariosn too. A little background. I am a Django developer for almost 4 years. Recently I submitted a proposal to undertake the web operation of a community run orgnization. One vendor proposed Joomla and I have proposed Django. Never mind, he says Joomla is a framework. That is OK. What primarily differentiates the two proposals is that mine wants to develop all modules in Django (and use available Django-based softwate). While the other one wants to use Joomla as the base and and claims it will write code to modify Joomla or develop new modules from scratch. My proposal saves more money. I personally think developers are used to a modern programming language. It is about preference. Hoosh -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
admin actions
Hi, I would like to display javascript alert boxes when something goes wrong during admin actions. Is it possible ? --RJ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
select_related removes broken Foreign Keys, but How?
I noticed this first in the Django Admin. If you have 100 rows in Table A, and 5 of those have a foreign key entry pointing to a nonexistent item in Table B, rather than throwing an error, the admin displays 95. This happens if you set list_select_related = True, or if one of the list_display fields is a ForeignKey. (http://docs.djangoproject.com/en/dev/ref/contrib/admin/ #django.contrib.admin.ModelAdmin.list_select_related) So you can reproduce this by calling select_related. But my question is "How does this happen?". What are the lines of code that remove the 5 rows with broken foreign keys from the queryset? I've been digging through the Django codebase and can't find it. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Django access data passed to form
Hey, I have got a choiceField in my form, where I display filtered data. To filter the data I need two arguments. The first one is not a problem, because I can take it directly from an object, but the second one is dynamically generated. Here is some code: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **kwargs) parent_id = forms.IntegerField(widget=forms.HiddenInput) choices = forms.ChoiceField( choices = [ [group.node_id, group.name] for group in Objtree.objects.filter( type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), parent_id = 50 ).distinct()] + [[0, 'Add a new one'] ], widget = forms.Select( attrs = { 'id': 'group_select' } ) ) I would like to change the parent_id that is passed into the Objtree.objects.filter. As you can see I tried in the init function, as well with kwargs['initial']['parent_id'] and then calling it with self, but that doesnt work, since its out of scope... it was pretty much my last effort. I need to acccess it either trough the initial parameter or directly trough parent_id field, since it already holds its value (passed trough initial). Any help is appreciated, as I am running out of ideas. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Selling Django
Hi, I have with interest followed the thread "Seeking Django vs. Joomla comparison", and it has inspired me to start this new thread. I consider myself a Python/Django programmer, and I do so because my experiences with a number of programming languages, CMS'es and web frameworks has lead me to believe that Python and Django is simply the better choice from a technical perspective. I am not a fanatic and I won't say that everything else sucks, but honestly - if you have the choice between a better and a no-quite-so-good technology, you will of course want to use the better one, despite that the other would work, too. Now to the problem: a lot of people who needs websites have heard of Drupal or Joomla! or WordPress or PHP. But NOBODY has EVER heard about Django. If somebody suggests that they make their website with something called "Django" then this "Django-thing" must at least have some reasons to why it exists and why one should prefer it over well- known solutions. Consequently, people come the this discussion group and ask: "What are the reasons that you think your product is better?", and the answer they get is: "our product cannot be compared with the others because you cannot compare apples with oranges." This means that people who where willing to listen to a good sales talk leaves the shop in a hurry because the salesman obviously didn't want to sell anything at all. Which leaves me and a lot of other Django entusiasts with not so much work as we would as we would like to have. I think that we - the Django community - could do a better job selling our product, and I'd like to volunteer in this work. I just don't know how to do it. Let me end this post with a comment to the "compare-apples-with- oranges"-thing that I hear so often: every programmer knows that "apples" can be compared with "oranges". Since "o" has a higher value then "a" in most encoding systems, "oranges" > "apples". What we need to do is simply to convince people that the flexibility and code cleanness they get with Django gives them much more value than all of the 1000+ Drupal modules together. I think that was all... Finn Gruwier Larsen -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
File - .dat
Hello, I need to leave a file tabbed, like this: http://www.srl.caltech.edu/~shane/sensitivity/asteroids/scg_8564.dat Following piece of my code that does this: - with Django # - # Import # - from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect from django.http import HttpResponse from django.template import RequestContext from django.core.urlresolvers import reverse from simuladores.detector.forms import Fase from django.template import loader, Context from django.views.generic.simple import direct_to_template from django.forms import forms, fields from matplotlib import use use('Agg') from matplotlib.pyplot import plot, savefig, setp, figure, subplot import csv #from struct import pack from pylab import * import pylab from decimal import Decimal import math import matplotlib.pyplot as plt # # A view that to show the form # def desenha_grafico(request): if request.method == 'POST': form = Fase(request.POST) if form.is_valid(): f = xrange(3000,3400) # # S, Sfase # Sfase=[] for v in f: # --- # Sfase # --- Sfase.append(form.cleaned_data['Sph']*(pow(v,2)/ pow(form.cleaned_data['df'],2))) # --- # Plot Graph # --- fig = plt.figure() plt.subplots_adjust(hspace=0.4) plt.subplots_adjust(wspace=0.4) ax = plt.subplot(2,2,1) ax.plot(f,Sfase) leg = ax.legend(loc="left") setp(ax.get_xticklabels(), fontsize=8.5) setp(ax.get_yticklabels(), fontsize=8.5) frame = leg.get_frame() frame.set_facecolor('white') # set the frame face color to white # matplotlib.text.Text instances for t in leg.get_texts(): t.set_fontsize('9') grid('TRUE') savefig('C:\simuladores\detector\media\imagem.png') writer = csv.writer(open('C:\simuladores\detector\media \dados.dat','wb')) writer.writerow(f) writer.writerow(Sfase) resultado = Fase() # --- # return to template # --- return render_to_response('gera_grafico.html', {'resultado': resultado}, context_instance = RequestContext(request)) #return render_to_response('soma.html', {'resultado': resultado}) else: form = Fase(request.POST) return render_to_response('soma.html', {'form': form}) form=Fase() return render_to_response('soma.html', {'form': form}) Following my code in the IDLE of Python import numpy import pylab from pylab import * x = arange(3000,3400) y = -108*((x**2)/(3e14**2)) numpy.savetxt('C:\Documents and Settings\Web\dados.dat', (x,y)) However, my file dados.dat out as follows in this link, yhis out in a single line http://paste.pocoo.org/show/226192/ As I viewthis as link: http://www.srl.caltech.edu/~shane/sensitivity/asteroids/scg_8564.dat -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
Thanks Thierry, but problem solved!...:) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
P On Jun 16, 6:49 pm, "!...@!!!" wrote: > Thanks Thierry, but problem solved!...:) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Selling Django
On Wed, Jun 16, 2010 at 5:26 PM, finn wrote: > Hi, > > I have with interest followed the thread "Seeking Django vs. Joomla > comparison", and it has inspired me to start this new thread. > > > > Let me end this post with a comment to the "compare-apples-with- > oranges"-thing that I hear so often: every programmer knows that > "apples" can be compared with "oranges". Since "o" has a higher value > then "a" in most encoding systems, "oranges" > "apples". What we need > to do is simply to convince people that the flexibility and code > cleanness they get with Django gives them much more value than all of > the 1000+ Drupal modules together. > > I think that was all... > > Finn Gruwier Larsen > This kind of discussion comes up frequently whenever there are people who like a bit of software, they get used to using one particular bit of software, and start to think that that bit of software is so clearly the best that choosing another bit of software is "wrong" and their way is "better". Different tasks may require different tools, and just because one knows a particular tool extremely well, they think it should be used for all of them, where as it is usually more accurate that many different tools can produce an effective solution. The most important thing for any project manager is that they know precisely why they are using a particular tool. You should be able to justify to yourself why to use a particular tool, and the answer is never "it's better". For instance, on one of my projects we are using django. Why are we using django? 1) Django is written in python, python is quick and easy for programmers to learn, lots of job applicants (profess to) have python skills. 2) Django has an elegant structure of middleware and context processors that allow us to modify/update important parts of the web stack. 3) Django has a sane template system, not based on XML (use ZPT/XSLT for a while, see what I mean :) 4) Django has useful 3rd party apps we can use to shorten development time, eg django-rosetta for our translators to update translations, django-south for managing database structure, contrib.auth and contrib.admin. 5) We have resource to maintain development on this project For other projects, eg our wiki, blogs, bug tracking and vcs we use COTS software (well, Open Source Off The Shelf perhaps may be more accurate), because we don't want to spend the time maintaining/updating/improving these applications, we just want them to work (hacking them until they work). This is a long way of saying "Just because you can write a CMS in django, you probably shouldn't". Unless your goal is developing a CMS in django, you will waste time you could be doing useful things in! Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Problem in Django App Part 1 Tutorial
PO On Jun 16, 6:55 pm, "!...@!!!" wrote: > P > > On Jun 16, 6:49 pm, "!...@!!!" wrote: > > > > > Thanks Thierry, but problem solved!...:) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
models.URLField with verify_exists=True pass non existent Urls to DB
Hi, I have a model with URLField. Parmether verify_exists is set to True, but when I enter url that does not exists (e.g. http://foobarbarfoo.com, or http://www.google.com/foobar) they somehow manage to get to the DB. Should model report error? Or I do not understand docs: "If True (the default), the URL given will be checked for existence (i.e., the URL actually loads and doesn't give a 404 response)." on http://docs.djangoproject.com/en/dev/ref/models/fields/#urlfield My model is: class Link(models.Model): url = models.URLField(verify_exists=True, unique=True) class Bookmark(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User) link = models.ForeignKey(Link) class Tag(models.Model): name = models.CharField(max_length=64, unique=True) bookmarks = models.ManyToManyField(Bookmark) Form class is: class BookmarkSaveForm(forms.Form): url = forms.URLField( label=u'URL', widget=forms.TextInput(attrs={'size' : 64}) ) title = forms.CharField( label=u'Title', widget=forms.TextInput(attrs={'size' : 64}) ) tags = forms.CharField( label=u'Tags', required=False, widget=forms.TextInput(attrs={'size' : 64}) ) View function that handle form is: def bookmark_save_page(request): if request.method == 'POST': form = BookmarkSaveForm(request.POST) if form.is_valid(): link, dummy = Link.objects.get_or_create( url=form.cleaned_data['url'] ) bookmark, created = Bookmark.objects.get_or_create( user=request.user, link=link ) # Update bookmark title. bookmark.title = form.cleaned_data['title'] # If the bookmark is being updated, clear old tag list. if not created: bookmark.tag_set.clear() # Create new tag list. tag_names = form.cleaned_data['tags'].split() for tag_name in tag_names: tag, dummy = Tag.objects.get_or_create(name=tag_name) bookmark.tag_set.add(tag) # Save bookmark to database. bookmark.save() return HttpResponseRedirect( '/user/%s/' % request.user.username ) else: form = BookmarkSaveForm() variables = RequestContext(request, { 'form' : form }) return render_to_response('bookmark_save.html', variables) I am using Django 1.2.1, Python 2.6.5 on Kubuntu 10.04 (64b) Thanks, Zlatan -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: models.URLField with verify_exists=True pass non existent Urls to DB
On Wed, Jun 16, 2010 at 1:29 PM, aurel...@gmail.com wrote: > Hi, > > I have a model with URLField. Parmether verify_exists is set to True, > but when I enter url that does not exists (e.g. http://foobarbarfoo.com, > or http://www.google.com/foobar) they somehow manage to get to the > DB. > > Should model report error? Or I do not understand docs: "If True (the > default), the URL given will be checked for existence (i.e., the URL > actually loads and doesn't give a 404 response)." on > http://docs.djangoproject.com/en/dev/ref/models/fields/#urlfield > > This checking is done either when a ModelForm based on the model is used, or when full_clean() on a model instance is called. In the code you show you do neither of these things. You have created a regular Form with URLField, but when you create this form field you do not specify verify_exists=True. So when is_valid() is called on that form, it returns True even when the specified URL does not exist, because cleaning the form URL field does not check for the existence of the URL, since the form does not ask for that. Then the data from the cleaned form is used to create a model instance, but full_clean() is not called before saving that instance, so again the validation is bypassed. Easiest fix is to specify verify_exists on your form's URLField. Karen -- http://tracey.org/kmt/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
enumerating view functions
Hi, Is there a way to enumerate view functions that are currently associated with a url patern? In the end, I'd like to get a list of triples: pattern name, pattern, callback function. Thanks Dmitry -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Is there any kind of verbose_name for apps?
I don´t think there is (although this issue has already been discussed years ago) - no ability to change apps-name and/or app-translations. you could use a 3rd-party-app like admin-tools to customize your index- page and change appnames (see http://bitbucket.org/izi/django-admin-tools/overview/). regards, patrick On 16 Jun., 16:31, Massimiliano della Rovere wrote: > And if not how can I emulate that? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Seeking Django vs. Joomla comparison
> A little background. I am a Django developer for almost 4 years. > Recently I submitted a proposal to undertake the web operation of a > community run orgnization. One vendor proposed Joomla and I have > proposed Django. Never mind, he says Joomla is a framework. That is > OK. What primarily differentiates the two proposals is that mine wants > to develop all modules in Django (and use available Django-based > softwate). While the other one wants to use Joomla as the base and and > claims it will write code to modify Joomla or develop new modules from > scratch. My proposal saves more money. Thanks for this additional background. There's a difference between a team evaluating where to invest their time when deciding new technologies to support as part of their service and a client making a choice between vendors that are using different technologies to produce a project. You are essentially looking for a way to favorably compare your proposal to the proposal of the other vendor, correct? In that case, I think the Django/Drupal article would be sufficient because it tackles the core "platform" vs "cms" issue. > I personally think developers are used to a modern programming language. > It is about preference. This is meaningless to most clients, because that speaks to your business not theirs. You need to answer questions like: - Will your platform be flexible enough to support changing requirements? - Will the client be able to find maintainers if you get hit by a bus or are too busy to work on the site? - If the site is redesigned in 2-3 years, how difficult will it be to migrate the current content? - How easy will the site be to use for the content editors? - If 3rd party functionality is buggy or ceases to be maintained, how difficult will it be to fix/maintain internally? - Will the site be as easy to maintain, improve 2 years from now as it is now? - When a new version of your platform is released, how easy will the upgrade process be? These questions directly effect the viability of your proposal to your client in the long run. I think platforms in general come out better than CMSs in these areas (and Django in particular). Here is a general critique of CMS systems in general compared to frameworks: http://sunlightlabs.com/blog/2009/content-management-systems-just-dont-work/ V -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: enumerating view functions
En/na Dmitry Beransky ha escrit: Hi, Is there a way to enumerate view functions that are currently associated with a url patern? In the end, I'd like to get a list of triples: pattern name, pattern, callback function. If you want to get a dump of the (regex, view, name) triples on the screen take a look at django-command-extensions[1], command 'show_urls'. If you want to get the list from your app in order to do some processing on it [2] provides a simple example on how to "introspect" the URLs. [1] http://code.google.com/p/django-command-extensions/ [2] http://djangosnippets.org/snippets/2059/ HTH -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Q objects for subqueries with cross-references
Hi, I am having a hard time with Q objects based on subqueries. It's a part of a linguistic corpus analysis query builder (hence Q objects as this is how I parse and translate arbitrary queries into Django) -- the user can search 'posts' that meet complex criteria. Anyway, it's all working fine and dandy with the exception of querying post tags (there is a many-to-many relationship between posts and tags). A simplified version of my models.py: --- BEGIN --- class Tag(models.Model): label = models.CharField(max_length=255) class Post(models.Model): tags = models.ManyToManyField(Tag, through='TagsForPost') class TagsForPost(models.Model): tag = models.ForeignKey(Tag) post = models.ForeignKey(Post) --- END --- The query parser iterates over the query expression and for every criterion (=smallest subexpression) it adds a Q object. Let's say I have this query: 'Tag' 'is' "tagA" AND 'Tag' 'is' "tagB" which should yield all posts that are tagged with both tagA and tagB. So I feel I need something that will generate IN operator in SQL, with the condition set being the result of a subquery fetching all tags for a post. This seems to be handled nicely by Django: http://docs.djangoproject.com/en/dev/ref/models/querysets/#in However, since I am looking for posts, I need to cross-reference the post in the inner query with the post in the outer query (on the SQL level at least). I guess matching posts by primary key is the way to go here. However, I can't quite wrap my mind around the Django syntax here. Can anyone help me with getting the proper Q object that will do the trick? Let's assume that for every iteration the tag name (string) is held in a variable called 'value'. As an example, for conditions for searching for posts starting with a given text I do: result = Q(body_anonymized__istartswith=value) ('body' was originally a part of Post above in models.py) Thanks in advance! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: custom template tags with a raw query
The first link I had seen and used. My custom query works, I had just been having issues with the tags. I had been through the docs and seen a different one on tags, but apparently passed over the one you posted in the link. It filled in some of the gaps I was missing, thanks. Very helpful. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Seeking Django vs. Joomla comparison
Many thanks to V and others who have contributed to this topic. More info. I guess I am coming up to speed now. The decision makers are not managers, but a private organization who members will read both proposals and ask questions from both vendors. At then end they vote democratically. One member, one vote. For the most part the members are not computer experts. They care about ease of use as they would be operating the final programs/modules -- be it updating the content of the public side of the web site or in the back-office applications. For this reason I have suspected that a simple user interface will do the job, and therefore, I am better off just develop the programs as opposed to adopting one CMS and be restricted to that interface. I have a team of Django developers. I cannot say we are the best, but we are very comfortable and rapid developers in the Django environment. Good questions, V. Thanks . > You need to answer questions like: > - Will your platform be flexible enough to support changing > requirements? > - Will the client be able to find maintainers if you get hit by a bus > or are too busy to work on the site? > - If the site is redesigned in 2-3 years, how difficult will it be to > migrate the current content? > - How easy will the site be to use for the content editors? > - If 3rd party functionality is buggy or ceases to be maintained, how > difficult will it be to fix/maintain internally? > - Will the site be as easy to maintain, improve 2 years from now as it > is now? > - When a new version of your platform is released, how easy will the > upgrade process be? > > These questions directly effect the viability of your proposal to your > client in the long run. I think platforms in general come out better > than CMSs in these areas (and Django in particular). > > Here is a general critique of CMS systems in general compared to > frameworks:http://sunlightlabs.com/blog/2009/content-management-systems-just-don... Great article. I learned few things. Specially this one: "... but the software crosses the line into content management systems when it starts providing default user-experiences out of the box. This means you have to un-do the way default behavior works and apply what you want as desired behavior rather than writing behavior from scratch." Very interesting. He explained this one in such a way even a 4-year- old could understand. Regards, Hooshyar -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
How to create the model in a different database from within the same database server.
Hi, when I mean database I mean the separate databases from within one mysql database server. So ex: DB server: server.example.com Databases that are contained in the one instance of mysql: People Books I have made the connection in the settings.py at the project level but in the individual applications suppose People I would like to create the models that write the tables in that database space and the application Books to write its models in the Books database. This should be possible to do but not sure why its not working. Any thoughts? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
How to implement this model
OK, here's the deal. I'm working up an obituary site. There are 3 models/tables and at one point I need to connect two in a way that is different than I have done up to this point. Here is the situation, any recommendations on how to accomplish this would be great: I have an obituary table. In that table there is a field that checks if a funeral service is on the premises (column name "on_premises" of the Funeral Home that is entering the information. If this BooleanField is checked then it returns the location information of the funeral home which is stored in a business_profile table. Not difficult, just check if the boolean returns a value and then populate the template That works out nicely except I have been given an extra criteria for this project. Some business have both a funeral home and a crematorium. Many of these situations require that we list the address of one or the other. Since the "on premises" is a BooleanField there is no way for someone to state what part of their business is responsible for the service. What I would like to do is make this option a drop down in the obituary form that basically gives the business the option of choosing which one of their locations is the one we want attached to this obit. Once this is chosen then I will pull the value into the templates. How do I relate these models? My first thought is to create two "business type" columns in the business profile table and then relate the "service_location" column to these columns in a drop down? Is that even possible? How do I retrieve the values from two different fields and then select from them in another model? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: How to create the model in a different database from within the same database server.
Which version of django are you working with? On Jun 16, 2:28 pm, thusjanthan wrote: > Hi, > > when I mean database I mean the separate databases from within one > mysql database server. So ex: > > DB server: server.example.com > Databases that are contained in the one instance of mysql: > People > Books > > I have made the connection in the settings.py at the project level but > in the individual applications suppose People I would like to create > the models that write the tables in that database space and the > application Books to write its models in the Books database. This > should be possible to do but not sure why its not working. > > Any thoughts? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: how to use render_to_response, ajax and javascript variables
Thanks all. I may go with Matt's idea of serialising html + other data to json and decoding client side. I'm not totally keen though because this abandons a very nice rollup of functionality in django's render_to_response (I am not familiar with how to write the template as JSON and rendering to that. Keeping the template as html seems like the right thing to do). I was hoping you'd scream 'don't be daft - everyone does this...' :) Alex -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
i18n variable string translation
Hi guys, In http://www.djangobook.com/en/2.0/chapter19, there is a paragraph Translation works on variables. Again, here’s an identical example: def my_view(request): sentence = 'Welcome to my site.' output = _(sentence) return HttpResponse(output) (The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin.py makemessages, won’t be able to find these strings. More on makemessages later.) It's a bit confusing, one one hand it says Translation works on variables, on the other hand, it says makemessages won't be able to find these strings. Which one is right? The makemessages section didn't mention how to "fix" this problem neither. Any ideas? -Aaron -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: i18n variable string translation
On Wed, Jun 16, 2010 at 01:00:36PM -0700, Aaron Lee wrote: > def my_view(request): > sentence = 'Welcome to my site.' > output = _(sentence) > return HttpResponse(output) > > (The caveat with using variables or computed values, as in the previous two > examples, is that Django’s translation-string-detecting utility, > django-admin.py makemessages, won’t be able to find these strings. More on > makemessages later.) > It's a bit confusing, one one hand it says Translation works on variables, > on the other hand, it says makemessages won't be able to find these strings. Yes, it will work if you happen to have a translation, and yes, it doesn't say how to identify such strings for translation, because the value of the variable may not be known at the time makemessages is run (neither is it straightforward in cases where it could in theory be calculated). What kind of problem are you trying to solve? With kind regards, -- Baurzhan Ismagulov http://www.kz-easy.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-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: How to create the model in a different database from within the same database server.
Django 1.2 I have the following setup: ProjectA settings.py: ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test_database', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } ... now in the mysql database server the following databases exist: test_database Books People Under ProjectA director the following applications exist: Books People What I would like to do is create the models within those applications (Books/People) to write their sql tables to the appropriate database within my one mysql database server. eg: I want the create table on Books to be: create table Books.author ... Any thoughts? On Jun 16, 12:40 pm, Nick wrote: > Which version of django are you working with? > > On Jun 16, 2:28 pm, thusjanthan wrote: > > > > > Hi, > > > when I mean database I mean the separate databases from within one > > mysql database server. So ex: > > > DB server: server.example.com > > Databases that are contained in the one instance of mysql: > > People > > Books > > > I have made the connection in the settings.py at the project level but > > in the individual applications suppose People I would like to create > > the models that write the tables in that database space and the > > application Books to write its models in the Books database. This > > should be possible to do but not sure why its not working. > > > Any thoughts? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Is it possible to use Django with an API as its back-end?
Erik, thanks so much for pointing me to django-roa. It looks really cool, particularly because of its ability to handle so many different types of data storage solutions (eg - nosql, multiple dbs, etc). I also randomly stumbled across django-pipes, which seems to work really well for running Django's models off of an api. As for #2, can anyone point me toward a benchmark comparison of Django 1.2 and other similar Python, PHP, Java, etc frameworks? Most of the benchmark comparisons that I've found are from a few years ago, and use older versions of Django. Honestly, even if it was just a benchmark for Django 1.2, it would be really helpful. Thanks everyone, I love how friendly the Django community has been thus far! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: i18n variable string translation
Well what happened was I have a forms.py which has CONSTANT = _("Hello World") x = {'var': CONSTANT } and in the django.po, I do have a translation msgid "Hello World" msgstr "xxx" But it doesn't show up on the website, all the other translations work, so I am wondering what am I missing -Aaron On Jun 16, 1:35 pm, Baurzhan Ismagulov wrote: > On Wed, Jun 16, 2010 at 01:00:36PM -0700, Aaron Lee wrote: > > def my_view(request): > > sentence = 'Welcome to my site.' > > output = _(sentence) > > return HttpResponse(output) > > > (The caveat with using variables or computed values, as in the previous two > > examples, is that Django’s translation-string-detecting utility, > > django-admin.py makemessages, won’t be able to find these strings. More on > > makemessages later.) > > It's a bit confusing, one one hand it says Translation works on variables, > > on the other hand, it says makemessages won't be able to find these strings. > > Yes, it will work if you happen to have a translation, and yes, it > doesn't say how to identify such strings for translation, because the > value of the variable may not be known at the time makemessages is run > (neither is it straightforward in cases where it could in theory be > calculated). > > What kind of problem are you trying to solve? > > With kind regards, > -- > Baurzhan Ismagulovhttp://www.kz-easy.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-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: models.URLField with verify_exists=True pass non existent Urls to DB
Thanks Karen! Django 1.0 Web Site Development book (code example is from that book) has following paragraph: "By specifying correct field types in our form, we don't have to implement any additional input validation. For example, Django will automatically make sure that the user enters a valid URL because the corresponding field is defined as models.URLField." So book has error, at least for Django 1.2 On Jun 16, 7:53 pm, Karen Tracey wrote: > On Wed, Jun 16, 2010 at 1:29 PM, aurel...@gmail.com wrote: > > > Hi, > > > I have a model with URLField. Parmether verify_exists is set to True, > > but when I enter url that does not exists (e.g.http://foobarbarfoo.com, > > orhttp://www.google.com/foobar) they somehow manage to get to the > > DB. > > > Should model report error? Or I do not understand docs: "If True (the > > default), the URL given will be checked for existence (i.e., the URL > > actually loads and doesn't give a 404 response)." on > >http://docs.djangoproject.com/en/dev/ref/models/fields/#urlfield > > This checking is done either when a ModelForm based on the model is used, or > when full_clean() on a model instance is called. In the code you show you do > neither of these things. You have created a regular Form with URLField, but > when you create this form field you do not specify verify_exists=True. So > when is_valid() is called on that form, it returns True even when the > specified URL does not exist, because cleaning the form URL field does not > check for the existence of the URL, since the form does not ask for that. > Then the data from the cleaned form is used to create a model instance, but > full_clean() is not called before saving that instance, so again the > validation is bypassed. Easiest fix is to specify verify_exists on your > form's URLField. > > Karen > --http://tracey.org/kmt/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Q objects for subqueries with cross-references
On 16 kesä, 21:41, rt wrote: > Hi, > > I am having a hard time with Q objects based on subqueries. It's a > part of a linguistic corpus analysis query builder (hence Q objects as > this is how I parse and translate arbitrary queries into Django) -- > the user can search 'posts' that meet complex criteria. Anyway, it's > all working fine and dandy with the exception of querying post tags > (there is a many-to-many relationship between posts and tags). > > A simplified version of my models.py: > --- BEGIN --- > class Tag(models.Model): > label = models.CharField(max_length=255) > > class Post(models.Model): > tags = models.ManyToManyField(Tag, through='TagsForPost') > > class TagsForPost(models.Model): > tag = models.ForeignKey(Tag) > post = models.ForeignKey(Post) > --- END --- > > The query parser iterates over the query expression and for every > criterion (=smallest subexpression) it adds a Q object. Let's say I > have this query: > 'Tag' 'is' "tagA" > AND > 'Tag' 'is' "tagB" > which should yield all posts that are tagged with both tagA and tagB. > Haven't tested this but this particular query should be doable with: Post.objects.filter(tags__label__in=['tagA', 'tagB']) The thing inside parentheses could of course be represented with a Q object. For example I have a test db with bit different models: class Person(models.Model): name = models.CharField(max_length=200) class Group(models.Model): name = models.CharField(max_length=200) persons = models.ManyToManyField(Person, through='Through') class Through(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) The query Groups.objects.filter(persons__name__in=['anssi']) gives this SQL: 'SELECT "autocomplete_group"."id", "autocomplete_group"."name" FROM "autocomplete_group" INNER JOIN "autocomplete_through" ON ("autocomplete_group"."id" = "autocomplete_through"."group_id") INNER JOIN "autocomplete_person" ON ("autocomplete_through"."person_id" = "autocomplete_person"."id") WHERE "autocomplete_person"."name" IN (anssi)' -- Anssi > So I feel I need something that will generate IN operator in SQL, with > the condition set being the result of a subquery fetching all tags for > a post. This seems to be handled nicely by > Django:http://docs.djangoproject.com/en/dev/ref/models/querysets/#in > However, since I am looking for posts, I need to cross-reference the > post in the inner query with the post in the outer query (on the SQL > level at least). I guess matching posts by primary key is the way to > go here. However, > I can't quite wrap my mind around the Django syntax here. Can anyone > help me with getting the proper Q object that will do the trick? > > Let's assume that for every iteration the tag name (string) is held in > a variable called 'value'. As an example, for conditions for searching > for posts starting with a given text I do: > result = Q(body_anonymized__istartswith=value) > ('body' was originally a part of Post above in models.py) > > Thanks in advance! -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: How to implement this model
I am going to try to add better information for this issue, here we go: The model for the obituary looks like this: class obit_entry(models.Model): first_name = models.CharField('First Name', max_length=100, blank=False) middle_name = models.CharField('Middle Name', max_length=100, blank=False) last_name = models.CharField('Last Name', max_length=100, blank=False) nick_name = models.CharField('Nickname', max_length=100, blank=True) city = models.CharField('City', max_length=100, blank=False) state = USStateField(blank=False) occupation = models.CharField('Occupation', blank=True, max_length=100) date_of_birth = models.DateField(blank=False) date_of_death = models.DateField(blank=False) date_of_service = models.DateTimeField(blank=False) type_of_service = models.CharField('Type of service', max_length=100, choices=Service_Type, blank=False) on_premises = models.BooleanField(blank=True) service_location = models.CharField('Location of service', max_length=100, blank=True) service_address = models.CharField('Service Address', max_length=100, blank=True) service_city = models.CharField('City of service', max_length=100, blank=True) service_state = USStateField('State of service', blank=True) additional_info = models.TextField('Additional Information', blank=True) organ_donor = models.BooleanField(blank=True) natural_causes = models.CharField('Died of Natural causes', max_length=100, choices=Causes_Choices, blank=False) date_to_run = models.DateField('Date obit should run', blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(FullProfile, related_name="createdBY", null=True, blank=True) the model for the business profile (FullProfile) looks like this: class FullProfile(User): bus_name = models.CharField('Full Business Name', help_text='excluding type (e.g. Funeral Home, Crematorium)', max_length=200, blank=True) bus_type = models.CharField('Business Type', help_text='(e.g. Funeral Home, Crematorium, etc.)', max_length=200, blank=True) address_street = models.CharField('Street Number', max_length=200, blank=True) address_city = models.CharField('City', max_length=200, blank=True) address_zip = models.CharField('Zip Code', max_length=10, blank=True) phone = PhoneNumberField('Phone Number', blank=True) contact = models.CharField('Contact Name', max_length=100, blank=True) bus_type_2 = models.CharField('Business Type 2', help_text='(e.g. Funeral Home, Crematorium, etc.)', max_length=200, blank=True) address_street_2 = models.CharField('Street Number', max_length=200, blank=True) address_city_2 = models.CharField('City', max_length=200, blank=True) address_zip_2 = models.CharField('Zip Code', max_length=10, blank=True) completed = models.BooleanField() objects = UserManager() There is an obituary form that is a model form of the obit model: I would like to change the on_premises field to lookup of the two business type fields in the FullProfile model so that the user can select which business type they want to attach to the individual obituary. So if a business has bus_type = Funeral Home and bus_type_2 = Crematorium, in the obituary form the user will have a drop down of either "Funeral Home" or "Crematorium" to choose from. On Jun 16, 2:39 pm, Nick wrote: > OK, here's the deal. I'm working up an obituary site. There are 3 > models/tables and at one point I need to connect two in a way that is > different than I have done up to this point. Here is the situation, > any recommendations on how to accomplish this would be great: > > I have an obituary table. In that table there is a field that checks > if a funeral service is on the premises (column name "on_premises" of > the Funeral Home that is entering the information. > > If this BooleanField is checked then it returns the location > information of the funeral home which is stored in a business_profile > table. Not difficult, just check if the boolean returns a value and > then populate the template > > That works out nicely except I have been given an extra criteria for > this project. Some business have both a funeral home and a > crematorium. Many of these situations require that we list the address > of one or the other. Since the "on premises" is a BooleanField there > is no way for someone to state what part of their business is > responsible for the service. > > What I would like to do is make this option a drop down in the > obituary form that basically gives the business the option of choosing > which one of their locations is the one we want attached to this obit. > Once this is chosen then I will pull the value into the templates. > > How do I relate these models? My first thought is to create two > "business type" columns in the business profile table and then relate > the "service_location" col
Why does django's default test suite runner set settings.DEBUG = False?
This is a new feature of Django 1.2. I'm curious, why does it want to do this? I want to control this for my settings so that I can things like disabled verify_exists on my URLFields when I run tests. # django/test/simple.py class DjangoTestSuiteRunner(object): def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs): self.verbosity = verbosity self.interactive = interactive self.failfast = failfast def setup_test_environment(self, **kwargs): setup_test_environment() settings.DEBUG = False ... What's the benefit? Is it important? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: How to implement this model
Without caring or even attempting to understand your business I sounds like you just need to stop using a BooleanField() and instead use a ForeignKey(null=True) and then judge if it's "on_premise" by a method rather than a field something like this: class MyModel(Model): related_premise = ForeignKey(Premise, null=True) def on_premise(self): return self.related_premise is not None def get_related_premise(self): assert self.on_premise() return self.related_premise On Jun 16, 3:39 pm, Nick wrote: > OK, here's the deal. I'm working up an obituary site. There are 3 > models/tables and at one point I need to connect two in a way that is > different than I have done up to this point. Here is the situation, > any recommendations on how to accomplish this would be great: > > I have an obituary table. In that table there is a field that checks > if a funeral service is on the premises (column name "on_premises" of > the Funeral Home that is entering the information. > > If this BooleanField is checked then it returns the location > information of the funeral home which is stored in a business_profile > table. Not difficult, just check if the boolean returns a value and > then populate the template > > That works out nicely except I have been given an extra criteria for > this project. Some business have both a funeral home and a > crematorium. Many of these situations require that we list the address > of one or the other. Since the "on premises" is a BooleanField there > is no way for someone to state what part of their business is > responsible for the service. > > What I would like to do is make this option a drop down in the > obituary form that basically gives the business the option of choosing > which one of their locations is the one we want attached to this obit. > Once this is chosen then I will pull the value into the templates. > > How do I relate these models? My first thought is to create two > "business type" columns in the business profile table and then relate > the "service_location" column to these columns in a drop down? Is that > even possible? > > How do I retrieve the values from two different fields and then select > from them in another model? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: i18n variable string translation
Try to use lazy translation. El 16/06/2010 23:09, "Aaron" escribió: Well what happened was I have a forms.py which has CONSTANT = _("Hello World") x = {'var': CONSTANT } and in the django.po, I do have a translation msgid "Hello World" msgstr "xxx" But it doesn't show up on the website, all the other translations work, so I am wondering what am I missing -Aaron On Jun 16, 1:35 pm, Baurzhan Ismagulov wrote: > On Wed, Jun 16, 2010 at 01:00:3... > Baurzhan Ismagulovhttp://www.kz-easy.com/ -- You received this message because you are subscribed to the Google Groups "Django users" group -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: How to implement this model
The question is how do I relate this to the business_types in the FulLProfile model? Since a business can have multiple "Premises" On Jun 16, 4:44 pm, Peter Bengtsson wrote: > Without caring or even attempting to understand your business I sounds > like you just need to stop using a BooleanField() and instead use a > ForeignKey(null=True) and then judge if it's "on_premise" by a method > rather than a field something like this: > > class MyModel(Model): > related_premise = ForeignKey(Premise, null=True) > def on_premise(self): > return self.related_premise is not None > def get_related_premise(self): > assert self.on_premise() > return self.related_premise > > On Jun 16, 3:39 pm, Nick wrote: > > > OK, here's the deal. I'm working up an obituary site. There are 3 > > models/tables and at one point I need to connect two in a way that is > > different than I have done up to this point. Here is the situation, > > any recommendations on how to accomplish this would be great: > > > I have an obituary table. In that table there is a field that checks > > if a funeral service is on the premises (column name "on_premises" of > > the Funeral Home that is entering the information. > > > If this BooleanField is checked then it returns the location > > information of the funeral home which is stored in a business_profile > > table. Not difficult, just check if the boolean returns a value and > > then populate the template > > > That works out nicely except I have been given an extra criteria for > > this project. Some business have both a funeral home and a > > crematorium. Many of these situations require that we list the address > > of one or the other. Since the "on premises" is a BooleanField there > > is no way for someone to state what part of their business is > > responsible for the service. > > > What I would like to do is make this option a drop down in the > > obituary form that basically gives the business the option of choosing > > which one of their locations is the one we want attached to this obit. > > Once this is chosen then I will pull the value into the templates. > > > How do I relate these models? My first thought is to create two > > "business type" columns in the business profile table and then relate > > the "service_location" column to these columns in a drop down? Is that > > even possible? > > > How do I retrieve the values from two different fields and then select > > from them in another model? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Multiple AJAX sends within a views.py-function
Hi Ian, On Wed, Jun 16, 2010 at 4:11 PM, Ian McDowall wrote: > Cool. That is a clever way to subvert (I don't mean this negatively) > the response generation. I do have a couple of comments: :-) Thanks > 1) It relies on the response being sent to the client as it is > generated and not buffered by the server. True, although that would only affect the server, and if a server wants to be slow, who am I to tell it to be quicker.^^ The amount of data has to be sent some way or another. The client does not care, whether all the data arrives at once or slowly drips in. This is nicely seen if I reload the page, where the data comes in much more quickly. (That is also nice, one sees that data is arriving, making the wait not as bad. ) The request generates a "data.json"-response which can just be cached and subsequently sent to the client in one go. > That is clearly working for > you and I don't know the internals of the different web servers to > know if any would break this. I suspect this will work with all > servers so nice trick. I have run it under the Django internal server and apache2. It works for both. > > 2) I would be worried by resources on the web server if you expect > many connections of this type. In most servers that I have seen, each > request is assigned to a thread from a pool and the thread is not > freed up until the request is completed. Each of these requests will > tie up a thread until it is completed (I think). This is likely to > work well for a small number of simultaneous connections but if you > had more simultaneous clients than threads in your pool, I would > expect new requests to be blocked / delayed. > > If you only expect one or a small number of clients to use this > request at one time then you are fine. If you want to scale this then > I think that you may have a problem. I suggest testing this by > setting up more simultaneous clients than your server has threads set > in the pool. The test might be fiddly to set up and you could > reconfigure the server to have fewer threads and add delays into the > calculations to make it easier to test. > I am writing exams right now but I should test this sometime. Thanks for pointing it out. Cheers, Christoph -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: i18n variable string translation
Thanks, the lazy translation solves the problem. -Aaron On Wed, Jun 16, 2010 at 2:59 PM, Antoni Aloy wrote: > Try to use lazy translation. > > El 16/06/2010 23:09, "Aaron" escribió: > > > Well what happened was I have a forms.py > > which has > > CONSTANT = _("Hello World") > x = {'var': CONSTANT } > > and in the django.po, I do have a translation > > msgid "Hello World" > msgstr "xxx" > > But it doesn't show up on the website, all the other translations > work, so I am wondering what am I missing > > -Aaron > > > > On Jun 16, 1:35 pm, Baurzhan Ismagulov wrote: > > On Wed, Jun 16, 2010 at 01:00:3... > > Baurzhan Ismagulovhttp://www.kz-easy.com/ > > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To post to this group, send email to django-us...@googlegroups.com. > To unsubscribe from this group, send email to > django-users+unsubscr...@googlegroups.com > . > For more options, visit this group at > http://groups.google.com/group/django-users?hl=en. > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: i18n variable string translation
Another problem I am facing is it seems some pages are not being translated until I hit certain page, after that everything is fine. I am not exactly sure what the problem is but if you guys experience this problem, would appreciate some insights. -Aaron On Wed, Jun 16, 2010 at 4:47 PM, Aaron Lee wrote: > Thanks, the lazy translation solves the problem. > > -Aaron > > > On Wed, Jun 16, 2010 at 2:59 PM, Antoni Aloy wrote: > >> Try to use lazy translation. >> >> El 16/06/2010 23:09, "Aaron" escribió: >> >> >> Well what happened was I have a forms.py >> >> which has >> >> CONSTANT = _("Hello World") >> x = {'var': CONSTANT } >> >> and in the django.po, I do have a translation >> >> msgid "Hello World" >> msgstr "xxx" >> >> But it doesn't show up on the website, all the other translations >> work, so I am wondering what am I missing >> >> -Aaron >> >> >> >> On Jun 16, 1:35 pm, Baurzhan Ismagulov wrote: >> > On Wed, Jun 16, 2010 at 01:00:3... >> > Baurzhan Ismagulovhttp://www.kz-easy.com/ >> >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group >> >> -- >> You received this message because you are subscribed to the Google Groups >> "Django users" group. >> To post to this group, send email to django-us...@googlegroups.com. >> To unsubscribe from this group, send email to >> django-users+unsubscr...@googlegroups.com >> . >> For more options, visit this group at >> http://groups.google.com/group/django-users?hl=en. >> > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: select_related removes broken Foreign Keys, but How?
On Wed, Jun 16, 2010 at 11:55 PM, ryan wrote: > I noticed this first in the Django Admin. If you have 100 rows in > Table A, and 5 of those have a foreign key entry pointing to a > nonexistent item in Table B, rather than throwing an error, the admin > displays 95. This happens if you set > list_select_related = True, or if one of the list_display fields is a > ForeignKey. (http://docs.djangoproject.com/en/dev/ref/contrib/admin/ > #django.contrib.admin.ModelAdmin.list_select_related) > > So you can reproduce this by calling select_related. But my question > is "How does this happen?". What are the lines of code that remove > the 5 rows with broken foreign keys from the queryset? I've been > digging through the Django codebase and can't find it. A select_related() is a query that returns all the rows from table A that have corresponding rows in table B. If a row in A doesn't have a corresponding row in B (which includes the case where A points to a non-existent row in B), then the row from A isn't included, either. This isn't thing that Django implements - it's a function of the way the underlying relational database works. Yours, Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Why does django's default test suite runner set settings.DEBUG = False?
On Thu, Jun 17, 2010 at 5:40 AM, Peter Bengtsson wrote: > This is a new feature of Django 1.2. I'm curious, why does it want to > do this? I want to control this for my settings so that I can things > like disabled verify_exists on my URLFields when I run tests. No, it isn't a new feature at all. It's been there since the test system was introduced almost 4 years ago. http://code.djangoproject.com/browser/django/trunk/django/test/simple.py?rev=3658#L55 Here's the reasoning: * Production code should always be running in DEBUG=False, and you should be testing how your code will operate in production. It would be a pain to have to manually set (and, more importantly, to remember to set) DEBUG=True every time you run your test suite, so we do it for you. * DEBUG=True will be marginally faster, because it doesn't collect various debug/traceback information during execution. In a big test suite, every little bit matters. Yours, Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: I experience problem with special chars like æ øå in filename when using models.ImageField. and models.Fi leField
You are totally right Karen This solved the problem, just as you said it would: export LANG='en_US.UTF-8' export LC_ALL='en_US.UTF-8' Thanks alot Karen :o) So now I only need to: Fix the security issue to make sure that people dont upload php files etc. (I just read a warning about that) And if its possible, create some kind of resize function that can resize huge picture files before they get saved. And maybe create the rename function i menchined earlier in here, that removes special chars. On 15 Jun., 14:22, Karen Tracey wrote: > On Tue, Jun 15, 2010 at 8:18 AM, MichaelHjulskov wrote: > > > My good friend just told me to take a look here and define a function > > on upload_to that filters special chars from filenames. > > >http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.mod... > > > Do you aggree? Would that be the an appropriate solution to solve this > > problem? > > You could use that as a workaround, but I would not call that the right > answer. The right answer is for the environment of the web server to be set > up so that unicode strings containing non-ASCII data can be successfully > passed to Python file system functions. > > Karen > --http://tracey.org/kmt/ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Selling Django
On Wednesday 16 June 2010 21:56:12 finn wrote: > I think that we - the Django community - could do a better job selling > our product, and I'd like to volunteer in this work. I just don't know > how to do it. > which is your market? The CMS market is aimed at the end user - the django market is among developers. -- Regards Kenneth Gonsalves Senior Associate NRC-FOSS at AU-KBC -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Clean method across multiple models?
Hello all, Is there a sane way to make a clean [1] method that depends on fields from across multiple models? I've got a view that uses two form classes and want to write custom validation that checks clean_data fields in both models and I'm looking for an example of such. TIA, John [1] http://docs.djangoproject.com/en/1.1/ref/forms/validation/#s-cleaning-and-validating-fields-that-depend-on-each-other -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
key error in templates
hi, in many models with an imagefield called photo, I have this code in the template: {% if p.photo %} {% endif %} this has been working across many sites for years - and is working on a particular site running Revision: 12453. In my current project I am getting keyerror: photo where the photo does not exist. This is running on latest trunk. The only difference between the two sites is that in site where it is working, 'p' is a query set passed from the view, whereas in the site where it is not working, the values are got from a pickled file, so the code is like this: {% if hand.0.player.photo %}hi{% endif %} here hand.0.player is a Player model which has a field called photo. If the photo does not exist I get a KeyError. The full error traceback is given below: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/displayhandicap/ Django Version: 1.2.1 SVN-13354 Python Version: 2.6.2 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'djangogolf.web', 'sorl.thumbnail'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Template error: In template /home/lawgon/djangogolf/templates/web/handicaplist.html, error at line 20 Caught KeyError while rendering: photo 10 : 11 : 12 : Member 13 : Photo 14 : Club 15 : Handicap index 16 : Handicap for Ooty 17 : Handicap for Coimbatore 18 : Cut? 19 : 20 : {% for hand in handlist.hlist %} 21 : 22 : {{hand.0}} 23 : 24 : {% if hand.0.player.photo %}hi{% endif %} 25 : {{hand.0.player.homeclub.shortname}} 26 : {{hand.1}} 27 : {{hand.2}} 28 : {{hand.3}} 29 : {{hand.4}} 30 : Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/djangogolf/web/views.py" in displayhandicap 1911. {'handlist':handlist,})) File "/usr/lib/python2.6/site-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/python2.6/site-packages/django/template/loader.py" in render_to_string 186. return t.render(context_instance) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in render 173. return self._render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/lib/python2.6/site-packages/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/lib/python2.6/site-packages/django/template/defaulttags.py" in render 251. return self.nodelist_true.render(context) File "/usr/lib/python2.6/site-packages/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/usr/lib/python2.6/site-packages/django/template/debug.py" in render_node 72. result = node.render(context) File "/usr/lib/python2.6/site-packages/django/template/defaulttags.py" in render 167.
Re: key error in templates
On Thursday 17 June 2010 06:46:21 Kenneth Gonsalves wrote: > in many models with an imagefield called photo, I have this code in the > template: > > {% if p.photo %} > > > {% endif %} > > this has been working across many sites for years - and is working on a > particular site running Revision: 12453. > > In my current project I am getting keyerror: photo where the photo does > not exist. This is running on latest trunk. The only difference between > the two sites is that in site where it is working, 'p' is a query set > passed from the view, whereas in the site where it is not working, the > values are got from a pickled file, so the code is like this: > > {% if hand.0.player.photo %}hi{% endif %} > I have now confirmed that this KeyError also comes in revision 12453 - so it is a problem with my code -- Regards Kenneth Gonsalves Senior Associate NRC-FOSS at AU-KBC -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Form Relationships, Multiple Models Using a loop?
First time poster, so go easy on me... I need to create a form that will display a heading / description that comes from one model (DReq) which I can get to display in a for loop. Each dreq.desc is dependent on the results of a var that gets set and read in from the user's session. Then I need to add a couple form fields (from Saq) to each one that will relate to dreq.req_number (also displayed alongside the desc) so that I can save the user's input to the db (the DReq and MSaq are related as a MTM through another model Saq). The best way I can figure out how to do this is to use some sort of for loop that will display each item and the respective form fields. I have gotten that far by going the template route (see below). My problem is that I do not know how to relate them to each other. Below is some of what I have come up with. If all else fails I will just create four (there are only four possible configurations for the form, but it seems like this would be more elegant in a loop, somehow relating them) individual forms to handle the task. Here is what I have come up with so far (I know this together doesn't work, it is just what I have tried in the various MTV places): forms.py: class MSForm(forms.Form): answer = forms.Charfield(widget=forms.NullBooleanSelect) note = forms.Charfield(widget=forms.TextArea) # Perhaps use a ModelForm? #class Meta: #model = DReq #fields = [ #'answer', #'note', #] views.py @login_required def saq(request): current_saq = request.session.get('current_saq') question = DReq.objects.filter(s_types=current_saq) # Probably not the right place for the loop, but i was trying something different for dreq in question: if question.headline: req_headline = question.headline req_number = dreq.req_num if dreq.needs_answer: saq_form = MSForm() if request.method == 'POST': saq_form = MSForm(request.POST) if saq_form.is_valid(): # Query that pulls the requirement and assigns the correct answer to it. ... template.html -- This will display the form with the proper information (from a different views.py version), but the form inputs and the desc/reqs are not related in any way. Closest I've come except it obviously doesn't work. ... {% csrf_token %} {% for dreq in question %} {% if dreq.headline %} {{ dreq.headline }} {% endif %} {{ dreq.req_num }}: {{ dreq.desc}} {% if dreq.needs_answer %} {{ saq_form.answer }} {{ saq_form.note }} {% endif %} {% endfor %} ... models.py ... # This is where the desc text comes from class DReq(models.Model): req_num = models.CharField(max_length=5, blank=False) headline = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=False) needs_answer = models.BooleanField(blank=False) s_types = models.ManyToManyField(SType) class MSaq(models.Model): complete = models.BooleanField(blank=True) d_req = models.ManyToManyField(DReq, through='Saq') # This is where the data needs to be stored and related to class Saq(models.Model): d_req = models.ForeignKey(DReq) m_saq = models.ForeignKey(MSaq) answer = models.NullBooleanField(blank=False) note = models.CharField(max_length=200, blank=True) ... I have redacted some of the names to protect the innocent, I hope it is still easy to follow. I feel like I am missing something very basic, but I just can't wrap my head around what. So, I just need to link the descriptions (which get iterated and displayed just fine) to the form fields that get displayed with them, so I can write the responses to the db. I hope this isn't info overkill. Thanks in advance. Erich -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
admin filters getting reset after admin action
Hi there, I have some filters set-up on admin page. As soon as I perform admin action. All filters are getting reset. Is this is a bug from framework ? --RJ -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
URLConf
Hi, I did the following to allow the page to be loaded with or without the '/' at the end: (r'^mysite(/*)$', redirect_to, {'url':'/mysite/home/'}), in URL patterns. I got an error page, and the following error: Exception Type: TypeError at /mysite/ Exception Value: redirect_to() got multiple values for keyword argument 'url' Can you tell me what the problem is? Is there sufficient information? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: OneToOneField usage
> Is there a particular reason why using a related OneToOneField raises > DoesNotExist instead of returning None? > > | class Person( Model ): > | pass > | > | class Pet( Model ): > | owner = OneToOneField( Person ) > | > | # Assuming "joe" exists as a Person > | >>> kitty = joe.pet > | DoesNotExist: Pet matching query does not exist. I have the same problem as TallFurryMan. In this situation, kitty should be None, rather than an exception being thrown, since the related object not existing is a valid, non-exceptional condition, and this would bring symmetry between OneToOneField and ForeignKey. It also would enable more conveniently checking if such an object does or doesn't exist, ie: if joe.pet == None and some_other_condition(): do_stuff() Rather than having to code such an expression using a try/rescue. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: key error in templates - solved
On Thursday 17 June 2010 06:46:21 Kenneth Gonsalves wrote: > In my current project I am getting keyerror: photo where the photo does > not exist. This is running on latest trunk. The only difference between > the two sites is that in site where it is working, 'p' is a query set > passed from the view, whereas in the site where it is not working, the > values are got from a pickled file, so the code is like this: > > {% if hand.0.player.photo %}hi{% endif %} > solved - what had happened was that when I pickled the results, the model in question did not have a 'photo' field which I added subsequently to pickling. Once I repickled, the problem was solved -- Regards Kenneth Gonsalves Senior Associate NRC-FOSS at AU-KBC -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: key error in templates - solved
On Thu, Jun 17, 2010 at 9:58 AM, Kenneth Gonsalves wrote: > solved - what had happened was that when I pickled the results, the model > in > question did not have a 'photo' field which I added subsequently to > pickling. > Once I repickled, the problem was solved > Totally not related to your Q, but if you are using photos - try using django-photologue. Its awsum! -V- http://twitter.com/venkasub -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: key error in templates - solved
On Thursday 17 June 2010 10:02:20 Venkatraman S wrote: > > Once I repickled, the problem was solved > > Totally not related to your Q, but if you are using photos - try using > django-photologue. Its awsum! > was awesome - I do not think it is maintained now, I tried it with trunk and gave up after 5 minutes - I have my own gallery app which is enough for my purposes -- Regards Kenneth Gonsalves Senior Associate NRC-FOSS at AU-KBC -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Selling Django
On Wed, Jun 16, 2010 at 9:56 PM, finn wrote: > I think that we - the Django community - could do a better job selling > our product, and I'd like to volunteer in this work. I just don't know > how to do it. > Very well structured email - and i concur to the views expressed and i myself am sometimes at loss of words when i have to sell Django. I mean, i can talk technically, but django needs more sales-tone to it now - which basically means more user acceptance. Consider RoR - this is a framework which i think is more 'marketed' than Django. Recently I heard one of my pals who was new to web pragramming, who wants to build the site in RoR just because it has a ORM and a templating engine. I was like @#$%^&* -- i told him that in Django its much easier and it *also* has the same things and ended up explaining it to him that most of web-languages/frameworks do support all these, but the question is not that of supporting , but the ease of development and maintaining the code --- in which Python scores a big 10/10. Things like 'South' simply amaze me - data migrations on the go have never been more easier. There are many more amazing components which are simple but at the same time solve many of the complex routines - and all this happens in the Django world which needs to be showcased. At the same time, look at Pinax - its almost dead since 0.7 and #pinax is mostly silent; whereas this is a kickass mashup which needs more innovation. Django needs to be evangelized more. Now, what can i do in this effort? I intend to start a django blog and go through some of the nuances of the framework and start writing more and showcase how certain things can be done more easily than other frameworks. There are lots of django blogs around, and mine would probably be one more in the list. But again, I am just trying :) -V- http://twitter.com/venkasub -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: URLConf
On Wed, Jun 16, 2010 at 11:48 PM, Siddharth. S wrote: > Hi, > > I did the following to allow the page to be loaded with or without the > '/' at the end: > > (r'^mysite(/*)$', redirect_to, {'url':'/mysite/home/'}), > > in URL patterns. I got an error page, and the following error: > > Exception Type: TypeError at /mysite/ > Exception Value: redirect_to() got multiple values for keyword > argument 'url' > > Can you tell me what the problem is? Is there sufficient information? Everything grouped with ( ) in the regular expressions gets passed to the view as arguments. Try with: r"^mysite/?$" Regards, ~Rolando -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
DateField issues
I've defined a number of models, one of which I've called MemberProfile that looks like this class MemberProfile(models.Model): postal_addr1=models.CharField(max_length=50, verbose_name="postal address line 1") postal_addr2=models.CharField(max_length=50, verbose_name="postal address line 2") postal_addr3=models.CharField(max_length=50, verbose_name="postal address line 3") postalcode=models.CharField(max_length=4, verbose_name="postal code") res_addr1=models.CharField(max_length=50, verbose_name="residential address line 1") res_addr2=models.CharField(max_length=50, verbose_name="residential address line 2") res_addr3=models.CharField(max_length=50, verbose_name="residential address line 3") rescode=models.CharField(max_length=4, verbose_name="residential postal code") homeno=models.CharField(max_length=12, verbose_name="home number") workno=models.CharField(max_length=12, verbose_name="work number") cellno=models.CharField(max_length=12, unique=True, verbose_name="cellphone number") idno=models.CharField(max_length=13, unique=True, verbose_name="id or passport number") occu=models.CharField(max_length=15, verbose_name="occupation") employer=models.CharField(max_length=30) amount_paid=models.IntegerField(blank=True, null=True, help_text="total fees paid to date", verbose_name="total reciepts") reciept_no=models.IntegerField(blank=True, null=True, help_text="latest reciept number", verbose_name="reciept number") dob=models.DateField(verbose_name="date of birth") start_date=models.DateField() expire_date=models.DateField() captured_by=models.CharField(max_length=50, help_text="name of data capturer") photo=models.ImageField(upload_to="memberphotos", null=True, blank=True) permission=models.CharField(max_length=1, choices=PERMISSION_CHOICES, help_text="Administration level, if the user is a superuser this field has no effect") user=models.ForeignKey(User,unique=True,related_name="member", editable=False) branch=models.ForeignKey(Branch,related_name="member", null=True) def create_member(self,username,email,password): m=MemberProfile() m.user=User.objects.create_user(username=username,email=email,password=password) return m def __unicode__(self): return self.user.username def save(self,*args,**kwargs): if not self.start_date: self.start_date=models.DateField(datetime.date.today()) year=timedelta(days=365) self.expire_date=models.DateField(datetime.date.today() +year) super(MemberProfile, self).save(self,*args,**kwargs) I then wrote a method called populate just to test the database out and it is pretty friendly until I get this: Traceback (most recent call last): File "", line 1, in File "/host/Shared info/MyDBA/MyMembers/populate.py", line 114, in populate m1.save() File "/host/Shared info/MyDBA/MyMembers/../MyMembers/chiefs/ models.py", line 115, in save super(MemberProfile, self).save(self,*args,**kwargs) File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line 410, in save self.save_base(force_insert=force_insert, force_update=force_update) File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line 483, in save_base values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields if not isinstance(f, AutoField)] File "/usr/lib/pymodules/python2.6/django/db/models/fields/ __init__.py", line 192, in get_db_prep_save return self.get_db_prep_value(value) File "/usr/lib/pymodules/python2.6/django/db/models/fields/ __init__.py", line 511, in get_db_prep_value return connection.ops.value_to_db_date(self.to_python(value)) File "/usr/lib/pymodules/python2.6/django/db/models/fields/ __init__.py", line 472, in to_python if not ansi_date_re.search(value): TypeError: expected string or buffer m1 is an instance of MemberProfile... The error goes away if I comment out everything to do with DateField... Am I doing something retarded? As far as I can see I'm populating the fields the right way... Any help would be greatly 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-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: DateField issues
read about autofill_now=True and autofill=True On Thu, Jun 17, 2010 at 8:14 AM, Sheena wrote: > I've defined a number of models, one of which I've called > MemberProfile that looks like this > > class MemberProfile(models.Model): >postal_addr1=models.CharField(max_length=50, verbose_name="postal > address line 1") >postal_addr2=models.CharField(max_length=50, verbose_name="postal > address line 2") >postal_addr3=models.CharField(max_length=50, verbose_name="postal > address line 3") >postalcode=models.CharField(max_length=4, verbose_name="postal > code") >res_addr1=models.CharField(max_length=50, > verbose_name="residential address line 1") >res_addr2=models.CharField(max_length=50, > verbose_name="residential address line 2") >res_addr3=models.CharField(max_length=50, > verbose_name="residential address line 3") >rescode=models.CharField(max_length=4, verbose_name="residential > postal code") >homeno=models.CharField(max_length=12, verbose_name="home number") >workno=models.CharField(max_length=12, verbose_name="work number") >cellno=models.CharField(max_length=12, unique=True, > verbose_name="cellphone number") >idno=models.CharField(max_length=13, unique=True, verbose_name="id > or passport number") >occu=models.CharField(max_length=15, verbose_name="occupation") >employer=models.CharField(max_length=30) >amount_paid=models.IntegerField(blank=True, null=True, > help_text="total fees paid to date", verbose_name="total reciepts") >reciept_no=models.IntegerField(blank=True, null=True, > help_text="latest reciept number", verbose_name="reciept number") >dob=models.DateField(verbose_name="date of birth") >start_date=models.DateField() >expire_date=models.DateField() >captured_by=models.CharField(max_length=50, help_text="name of > data capturer") >photo=models.ImageField(upload_to="memberphotos", null=True, > blank=True) >permission=models.CharField(max_length=1, > choices=PERMISSION_CHOICES, help_text="Administration level, if the > user is a superuser this field has no effect") >user=models.ForeignKey(User,unique=True,related_name="member", > editable=False) >branch=models.ForeignKey(Branch,related_name="member", null=True) > >def create_member(self,username,email,password): >m=MemberProfile() > > > m.user=User.objects.create_user(username=username,email=email,password=password) >return m > >def __unicode__(self): >return self.user.username > >def save(self,*args,**kwargs): >if not self.start_date: >self.start_date=models.DateField(datetime.date.today()) >year=timedelta(days=365) >self.expire_date=models.DateField(datetime.date.today() > +year) >super(MemberProfile, self).save(self,*args,**kwargs) > > > I then wrote a method called populate just to test the database out > and it is pretty friendly until I get this: > > Traceback (most recent call last): > File "", line 1, in > File "/host/Shared info/MyDBA/MyMembers/populate.py", line 114, in > populate >m1.save() > File "/host/Shared info/MyDBA/MyMembers/../MyMembers/chiefs/ > models.py", line 115, in save >super(MemberProfile, self).save(self,*args,**kwargs) > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > 410, in save >self.save_base(force_insert=force_insert, > force_update=force_update) > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > 483, in save_base >values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) > or f.pre_save(self, True))) for f in meta.local_fields if not > isinstance(f, AutoField)] > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > __init__.py", line 192, in get_db_prep_save >return self.get_db_prep_value(value) > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > __init__.py", line 511, in get_db_prep_value >return connection.ops.value_to_db_date(self.to_python(value)) > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > __init__.py", line 472, in to_python >if not ansi_date_re.search(value): > TypeError: expected string or buffer > > m1 is an instance of MemberProfile... > > The error goes away if I comment out everything to do with > DateField... > Am I doing something retarded? As far as I can see I'm populating the > fields the right way... > > Any help would be greatly 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-us...@googlegroups.com. > To unsubscribe from this group, send email to > django-users+unsubscr...@googlegroups.com > . > For more options, visit this group at > http://groups.google.com/group/django-users?hl=en. > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscr
Re: DateField issues
Thanks The question is how do I populate a field with some other date, for example, there's a date of birth field that the auto stuff wont be ideal for... In the populate method i mentioned before, i passed the dob(date of birth) field a Date object initialized to something arbitrary. Does the DateField not get along with standard date objects? What format should stuff be in for populating DateFields? On Jun 17, 7:24 am, Alexander Jeliuc wrote: > read about autofill_now=True and autofill=True > > On Thu, Jun 17, 2010 at 8:14 AM, Sheena wrote: > > I've defined a number of models, one of which I've called > > MemberProfile that looks like this > > > class MemberProfile(models.Model): > > postal_addr1=models.CharField(max_length=50, verbose_name="postal > > address line 1") > > postal_addr2=models.CharField(max_length=50, verbose_name="postal > > address line 2") > > postal_addr3=models.CharField(max_length=50, verbose_name="postal > > address line 3") > > postalcode=models.CharField(max_length=4, verbose_name="postal > > code") > > res_addr1=models.CharField(max_length=50, > > verbose_name="residential address line 1") > > res_addr2=models.CharField(max_length=50, > > verbose_name="residential address line 2") > > res_addr3=models.CharField(max_length=50, > > verbose_name="residential address line 3") > > rescode=models.CharField(max_length=4, verbose_name="residential > > postal code") > > homeno=models.CharField(max_length=12, verbose_name="home number") > > workno=models.CharField(max_length=12, verbose_name="work number") > > cellno=models.CharField(max_length=12, unique=True, > > verbose_name="cellphone number") > > idno=models.CharField(max_length=13, unique=True, verbose_name="id > > or passport number") > > occu=models.CharField(max_length=15, verbose_name="occupation") > > employer=models.CharField(max_length=30) > > amount_paid=models.IntegerField(blank=True, null=True, > > help_text="total fees paid to date", verbose_name="total reciepts") > > reciept_no=models.IntegerField(blank=True, null=True, > > help_text="latest reciept number", verbose_name="reciept number") > > dob=models.DateField(verbose_name="date of birth") > > start_date=models.DateField() > > expire_date=models.DateField() > > captured_by=models.CharField(max_length=50, help_text="name of > > data capturer") > > photo=models.ImageField(upload_to="memberphotos", null=True, > > blank=True) > > permission=models.CharField(max_length=1, > > choices=PERMISSION_CHOICES, help_text="Administration level, if the > > user is a superuser this field has no effect") > > user=models.ForeignKey(User,unique=True,related_name="member", > > editable=False) > > branch=models.ForeignKey(Branch,related_name="member", null=True) > > > def create_member(self,username,email,password): > > m=MemberProfile() > > > m.user=User.objects.create_user(username=username,email=email,password=password) > > return m > > > def __unicode__(self): > > return self.user.username > > > def save(self,*args,**kwargs): > > if not self.start_date: > > self.start_date=models.DateField(datetime.date.today()) > > year=timedelta(days=365) > > self.expire_date=models.DateField(datetime.date.today() > > +year) > > super(MemberProfile, self).save(self,*args,**kwargs) > > > I then wrote a method called populate just to test the database out > > and it is pretty friendly until I get this: > > > Traceback (most recent call last): > > File "", line 1, in > > File "/host/Shared info/MyDBA/MyMembers/populate.py", line 114, in > > populate > > m1.save() > > File "/host/Shared info/MyDBA/MyMembers/../MyMembers/chiefs/ > > models.py", line 115, in save > > super(MemberProfile, self).save(self,*args,**kwargs) > > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > > 410, in save > > self.save_base(force_insert=force_insert, > > force_update=force_update) > > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > > 483, in save_base > > values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) > > or f.pre_save(self, True))) for f in meta.local_fields if not > > isinstance(f, AutoField)] > > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > > __init__.py", line 192, in get_db_prep_save > > return self.get_db_prep_value(value) > > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > > __init__.py", line 511, in get_db_prep_value > > return connection.ops.value_to_db_date(self.to_python(value)) > > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > > __init__.py", line 472, in to_python > > if not ansi_date_re.search(value): > > TypeError: expected string or buffer > > > m1 is an instance of MemberProfile... > > > The error goes away if I comment out everything to do with > > DateField... > > Am I doing something retarded? As far as I can see I'm po
Re: DateField issues
Your error is this... def save(self,*args,**kwargs): if not self.start_date: self.start_date=models.DateField(datetime.date.today()) year=timedelta(days=365) self.expire_date=models.DateField(datetime.date.today() +year) On Thu, Jun 17, 2010 at 8:40 AM, Sheena wrote: > Thanks > > The question is how do I populate a field with some other date, for > example, there's a date of birth field that the auto stuff wont be > ideal for... > In the populate method i mentioned before, i passed the dob(date of > birth) field a Date object initialized to something arbitrary. Does > the DateField not get along with standard date objects? What format > should stuff be in for populating DateFields? > > On Jun 17, 7:24 am, Alexander Jeliuc wrote: > > read about autofill_now=True and autofill=True > > > > On Thu, Jun 17, 2010 at 8:14 AM, Sheena > wrote: > > > I've defined a number of models, one of which I've called > > > MemberProfile that looks like this > > > > > class MemberProfile(models.Model): > > >postal_addr1=models.CharField(max_length=50, verbose_name="postal > > > address line 1") > > >postal_addr2=models.CharField(max_length=50, verbose_name="postal > > > address line 2") > > >postal_addr3=models.CharField(max_length=50, verbose_name="postal > > > address line 3") > > >postalcode=models.CharField(max_length=4, verbose_name="postal > > > code") > > >res_addr1=models.CharField(max_length=50, > > > verbose_name="residential address line 1") > > >res_addr2=models.CharField(max_length=50, > > > verbose_name="residential address line 2") > > >res_addr3=models.CharField(max_length=50, > > > verbose_name="residential address line 3") > > >rescode=models.CharField(max_length=4, verbose_name="residential > > > postal code") > > >homeno=models.CharField(max_length=12, verbose_name="home number") > > >workno=models.CharField(max_length=12, verbose_name="work number") > > >cellno=models.CharField(max_length=12, unique=True, > > > verbose_name="cellphone number") > > >idno=models.CharField(max_length=13, unique=True, verbose_name="id > > > or passport number") > > >occu=models.CharField(max_length=15, verbose_name="occupation") > > >employer=models.CharField(max_length=30) > > >amount_paid=models.IntegerField(blank=True, null=True, > > > help_text="total fees paid to date", verbose_name="total reciepts") > > >reciept_no=models.IntegerField(blank=True, null=True, > > > help_text="latest reciept number", verbose_name="reciept number") > > >dob=models.DateField(verbose_name="date of birth") > > >start_date=models.DateField() > > >expire_date=models.DateField() > > >captured_by=models.CharField(max_length=50, help_text="name of > > > data capturer") > > >photo=models.ImageField(upload_to="memberphotos", null=True, > > > blank=True) > > >permission=models.CharField(max_length=1, > > > choices=PERMISSION_CHOICES, help_text="Administration level, if the > > > user is a superuser this field has no effect") > > >user=models.ForeignKey(User,unique=True,related_name="member", > > > editable=False) > > >branch=models.ForeignKey(Branch,related_name="member", null=True) > > > > >def create_member(self,username,email,password): > > >m=MemberProfile() > > > > > > m.user=User.objects.create_user(username=username,email=email,password=password) > > >return m > > > > >def __unicode__(self): > > >return self.user.username > > > > >def save(self,*args,**kwargs): > > >if not self.start_date: > > >self.start_date=models.DateField(datetime.date.today()) > > >year=timedelta(days=365) > > >self.expire_date=models.DateField(datetime.date.today() > > > +year) > > >super(MemberProfile, self).save(self,*args,**kwargs) > > > > > I then wrote a method called populate just to test the database out > > > and it is pretty friendly until I get this: > > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "/host/Shared info/MyDBA/MyMembers/populate.py", line 114, in > > > populate > > >m1.save() > > > File "/host/Shared info/MyDBA/MyMembers/../MyMembers/chiefs/ > > > models.py", line 115, in save > > >super(MemberProfile, self).save(self,*args,**kwargs) > > > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > > > 410, in save > > >self.save_base(force_insert=force_insert, > > > force_update=force_update) > > > File "/usr/lib/pymodules/python2.6/django/db/models/base.py", line > > > 483, in save_base > > >values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) > > > or f.pre_save(self, True))) for f in meta.local_fields if not > > > isinstance(f, AutoField)] > > > File "/usr/lib/pymodules/python2.6/django/db/models/fields/ > > > __init__.py", line 192, in get_db_prep_save > > >return self.get_db_prep_value(value) > > > File "/usr/lib/pymodules/python2.6/dj
Re: DateField issues
Here is DateField class I think You will find all You need here class DateField(Field): description = _("Date (without time)") empty_strings_allowed = False default_error_messages = { 'invalid': _('Enter a valid date in -MM-DD format.'), 'invalid_date': _('Invalid date: %s'), } def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True Field.__init__(self, verbose_name, name, **kwargs) def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value if not ansi_date_re.search(value): raise exceptions.ValidationError(self.error_messages['invalid']) # Now that we have the date string in -MM-DD format, check to make # sure it's a valid date. # We could use time.strptime here and catch errors, but datetime.date # produces much friendlier error messages. year, month, day = map(int, value.split('-')) try: return datetime.date(year, month, day) except ValueError, e: msg = self.error_messages['invalid_date'] % _(str(e)) raise exceptions.ValidationError(msg) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now() setattr(model_instance, self.attname, value) return value else: return super(DateField, self).pre_save(model_instance, add) def contribute_to_class(self, cls, name): super(DateField,self).contribute_to_class(cls, name) if not self.null: setattr(cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) setattr(cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) def get_prep_lookup(self, lookup_type, value): # For "__month", "__day", and "__week_day" lookups, convert the value # to an int so the database backend always sees a consistent type. if lookup_type in ('month', 'day', 'week_day'): return int(value) return super(DateField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_date(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) if val is None: data = '' else: data = datetime_safe.new_date(val).strftime("%Y-%m-%d") return data def formfield(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateField, self).formfield(**defaults) On Thu, Jun 17, 2010 at 8:47 AM, Alexander Jeliuc wrote: > Your error is this... > def save(self,*args,**kwargs): >if not self.start_date: >self.start_date=models.DateField(datetime.date.today()) >year=timedelta(days=365) >self.expire_date=models.DateField(datetime.date.today() > +year) > > > > On Thu, Jun 17, 2010 at 8:40 AM, Sheena wrote: > >> Thanks >> >> The question is how do I populate a field with some other date, for >> example, there's a date of birth field that the auto stuff wont be >> ideal for... >> In the populate method i mentioned before, i passed the dob(date of >> birth) field a Date object initialized to something arbitrary. Does >> the DateField not get along with standard date objects? What format >> should stuff be in for populating DateFields? >> >> On Jun 17, 7:24 am, Alexander Jeliuc wrote: >> > read about autofill_now=True and autofill=True >> > >> > On Thu, Jun 17, 2010 at 8:14 AM, Sheena >> wrote: >> > > I've defined a number of models, one of which I've called >> > > MemberProfile that looks like this >> > >> > > class MemberProfile(models.Model): >> > >postal_addr1=models.CharField(max_length=50, verbose_name="postal >> > > address line 1") >> > >postal_addr2=models.CharField(max_length=50, verbose_name="postal >> > > address line 2") >> > >postal_addr3=models.CharField(max_length=50, verbose_name="postal >> > > address line 3") >> > >postalcode=models.CharField(max_length=4, verbose_n