poplib is pretty easy to work with:
def check_pop3(server,user,password):
import email,poplib,string
messages=[]
s=poplib.POP3(server)
s.user(user)
s.pass_(password)
resp, items, octets = s.list()
todelete=[]
for item in items:
id,size=item.split()
I can't claim best way, but the way we do it is to have a few django
models for storing the messages, and some help from the email, and
smptlib libraries.
Models:
Mailserver: model for storing connection information for connecting to
a standard smtp server, with mixin class using smtplib to provi
One thing that has bitten me more times than I care to remember is
forgetting to disable DEBUG in settings.py before processing large
datasets. The SQL queries build up in connection.queries until the
process dies. I ended up patching my django install to store queries
in a wrapper around buffer
I went the hideous route, but tried to make it general enough I could
reuse. I'm still on .96, but it shouldn't be too much trouble to make
it work with 1.0.
In [2]: template.Template("{% load kwtag %}{% do_kwtagtest foo foo=bar
%}").render(template.Context())
Out[2]: "['foo']{'foo': 'bar'}"
In
It's not very efficient, but it's possible. I just finished up an app
where dynamic urls was an unfortunate requirement, but simple to
implement.
A view is just a function within which can call another view, so it's
easily possible to have a catchall view that captures the url (using
the normal
I don't know if it's the best approach or not, but what I've done in
the past is to have the first call to the tag do any expensive stuff
and store it in a dict under a special name in the context (I usually
use __tagname). Subsequent calls to the tag use the data from the
context variable rather
Django is pretty flexible, so it's impossible to say exactly how to
integrate with your existing design since the original developer could
have done the template layout in a number of different ways. Since
the development process is a bit different that php, you might want to
step through the tut
It might be better to use the rewrite/proxy capability of your
webserver rather than try to proxy using django. If you do end up
trying to do it in python, I found pycurl to be much easier to deal
with for any requests requiring cookies, authentication, or anything
besides a simple url get despit
Take a look at this part of the documentation:
http://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this
Might not be the easiest way, but you could use a custom filter:
def formsbyfield(forms,field):
""" Given a list of similar forms, and a field name,
return a list of formfields, one from each form.
"""
return [form.fields.get(field,'') for form in forms]
register.filter('forms
This has been on my todo list of a while now, so I thought I'd trying
to figure it out.
I -think- the proper way to go about this would be in a custom
middleware with a process_exception handler that checks to see if the
exception is an instanace of the database defined exceptions. Looking
in dj
Maybe the APPEND_SLASH setting is causing it (along with a missing
slash at the end of your url)?
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-user
There is no way you can give an answer based on an application that
doesn't exist, and a server that doesn't exist. What I would do is
give them real numbers based on an application you -can- test. Build
a tiny Django application that does something resonably representitive
of what the real appl
If you are using the helper functions like form_for_model, form.save()
should return the saved object. The helper functions build the save
method for you based on the model definition. If you are doing custom
forms, it's up to you to make the form.save() method to handle the
form->model mappings
Are you sure the request is actually being made, and not ignored by
the browser? If you do GETs to the same url with the same parameters
(your boolean I assume) the browser will simply ignore the request. I
ran into that trying to do some ajax stuff, and ended up appending a
timestamp number as
admin != user
Atleast that's my view. As tempting as the pretty admin interface
might be, I think you would be better off rolling your own form and
view for end users. Then you have complete control. Using the
form_for_* functions you could have the whole thing done in a few
minutes.
fetch us
Assuming you just want to debug and are using the dev server you can
just do "print request.POST" and it will show up on the dev server
console. The results aren't all that pretty, but usable.
--~--~-~--~~~---~--~~
You received this message because you are subscr
I don't know how others have approached it, but I have a 'settings'
file with defaults defined in one place and reference those values via
imports in the form file and model file. For values specific for the
app, I stick them in the models file.
models.py
-
POST_DEFAULTS = {'status':'pub
Don't use a ChoiceField, but do use the select widget.
class TF(forms.Form):
blah=forms.IntegerField(widget=forms.Select(choices=((1,'one'),
(2,'two'))), initial = 2)
post = {'blah': 42}
form = TF(post)
form should validate. It would be up to you to make sure that the
Integer value is in
Maybe you could do something like this?
filterargs = {}
filterargs[fieldname] = some value
# or for other types of filtering
filterargs["%s__istartswith" % fieldname] = somevalue
mdl.objects.filter(**filterargs)
You might also want to take a look at the function get_model()
from django.db.mode
Using threadlocals and a custom template loader would probably work,
just put your loader first in settings.py.
http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google
Just pass them in as context variables, either the whole thing or just
the parts you need. This is kind of a snippet from my current project
that might show what I mean. I say kind of because I use a handler
object that wraps request and a few other things instead of request
directly, but the pr
Garg, hit enter too fast.
Class MyForm(forms.Form):
username = forms.CharField(max_length=12)
def clean_username(self):
username = self.clean_data['username']
if username == 'bob':
raise ValidationError("Bob is not allowed here")
return username
If so
newforms does that, but it's up to you do take care of the details by
either subclassing one of the existing fields like this snippet shows:
http://www.djangosnippets.org/snippets/115/
Or by making a specially named method on the form definition like
this:
Class MyForm(forms.Form)
username
> So my question is am I missing something or I was just expecting too
> much from the newforms?
I had similar problems initially, and after hundreds of forms built I
still get annoyed every time I have to build a newforms form. On the
other hand, I can't really think of a better way to do it ei
To get a list out of post you need to do:
request.POST.getlist('fieldname') and not request.POST['fieldname']
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email
You could also make your own render_to_response() function that
renders and caches the generic part of the page, and then passes that
in as a context for your base layout with the non-cacheable stuff like
the username. Or make some of the generic stuff tags that cache
themselves using the lower l
Everything can be changed. Look under auto_id in the newforms docs on
djangoproject.com. The default does it exactly the way you seem to
be, prepending 'id_' to the field name. If you want to set a class,
you need to change the attrs dict on the field's widget.
All a newforms field really cons
I had a lot of trouble with Eclipse on ubuntu. The default JRE was
not Sun's, and Eclipse was not completely stable using it. I
completely removed the other JRE, installed the Sun JRE and the
lockups went away. It's been flawless ever since.
--~--~-~--~~~---~--~---
As far as I know a form submits to a single url via the action=?
specifier. That's just the way an html form works. Each submit
button that is part of the form is going to post to the action url in
the form. You can override with javascript, but that doesn't make
much sense unless you're doing
> thanks doug, this is what I did, but I am not comfortable with it.
> those two button do different things, and if they're under one method
> on the views it could be ugly, what if I have 4 or 5 submit buttons?
Keep in mind there is nothing keeping one view from calling another.
def button1view
context_dict.update(button1_helper())
Opps, forgot to actually call button1_helper. Sorry, need sleep :)
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to d
A queryset is kind of like a list, you can slice it, access by index,
or iterate through it. I'm not quite sure what you are trying to do,
but to access the individual user objects you have to fetch them from
the queryset somehow:
users = User.objects.all()
by index:
print users[0].user
print u
You can make a 'views' subfolder in your app folder, and make sure it
contains an __init__.py file (can be empty).
My personal opinion is that going overboard trying to make your python
file structure 'neater' will eventually bite you in the ass. It wasn't
too bad for views, but became import hel
form = NewsForm(request.POST, somegroup=somegroup)
given your form __init__ definition, you are passing POST into the
spot for somegroup.
What I did to get around this was something like this:
class NewsBaseForm(BaseForm):
def __init__(self, *args, **kwargs):
nkwargs = kwargs.copy()
See if this tag won't work for you:
class ObjectAttribNode(template.Node):
def __init__(self, obj, attr):
self.obj = obj
self.attr = attr
def render(self, context):
print self.attr
try:
obj = resolve_variable(self.obj, context)
attr
maybe something like this...
class Employee(models.Model):
# your employee model fields here, no FKs to Contact or
Assignment models
...
class EmployeeAssignment(models.Model):
active = models.BooleanField() # I added this
employee = models.ForeignKey(Employee)
...
class
> ---
>
> If I have 8 people, how should bind POST data to a form object in the
> view?
You can use the 'prefix' option when instantiating the forms. Prefix
the form with the corresponding form 'number' or other unique
identifie
Syncdb doesn't create the intermediary table* if the model the
manytomanyfield is on already exists. You'll have to create it
manually, or drop the entry table and then run syncdb to create it.
ManyToManyField keeps track of the relations in a 3 column third table
like: id | entry_id | tag_id
It's hackish, but couldn't you override model save and check for
existance of a primary key.
def save(self,*args,**kwargs):
if not self._get_pk_val():
return super(UserEmail,self).save(*args,**kwargs)
else:
warnings.warn("Attempt to modify registered email %s
rejected.")
The caching is intentional, and designed to save you expensive
database queries. You can reset the cache in the shell by doing
something like this:
qs=ModelName.objects.all()
# do stuff with your queryset
# do your external database manipulation
qs._result_cache=None # setting _result_cache non
As far as I know it's for the life the the queryset variable. So if
you create a queryset at module level, it lasts until the module is
reloaded. If you define a queryset in one of your views it will hit
the database everytime that view function is accessed.
QS1=Model.objects.all()
def view(re
> [PYTHON]
> class Order(models.Model):
> def count_items(self):
> items = 0
> for item in self.orderitem_set.filter(order=self):
> items += item.quantity
> return items
> count = property(count_items)
> [/PYTHON]
For the instance.othermodel_set object
> q="select SUM(quantity) as item_count from %s where order=%s" %
> (self.orderitem_set.model._meta.db_table,self._get_pk_val())
Sorry, that first one is wrong.
q="select SUM(quantity) as item_count from %s where order_id=%s" %
(self.orderitem_set.model._meta.db_table,self._get_pk_val())
I wish
> I tried that, but I get the same error, the traceback displays that
> line as the "buggy" one: for item in self.orderitem_set.all():
def count_items(self):
items = 0
for item in self.fielddef_set.all():
items += item.id
return items
I added that to one o
I think you've got some misconceptions about newforms.
http://www.djangoproject.com/documentation/newforms/ should give you
the info you need.
Something more like this:
def save(self):
#set up the objects we are going to populate
user = User() # you want a new -instance- not another referen
You could build a builder function that does what you want (totally
untested, rough example). The form_for_model functions are good
working examples if I screwed something up here.
def form_builder(question_instance):
base_fields={'text': forms.CharField(widget=forms.Textarea,
help_text=ques
> mediaform = CustomMediaForm
> # get the initial queryset fo a large table
> qs=mediaform.base_fields['somefield'].queryset
>
> forms = []
>
> for i in requested_forms:
> form=mediaform(data, auto_id="some_generated_id")
> # assign the queryset to the choices
> form.base_fields['some
q = list(a) + list(b) + list(c)
q.sort('-date')
The problem you have here is the q.sort() method doesn't understand
how to compare your objects. '-date' means nothing to it.I'm
pretty sure you need to write your own comparison function and pass
that to sort. If you've got models with the sam
What I gave you should work, I have no idea about the error your
getting. Here is a complete example, maybe that will help.
In [15]: ls1=cm.Listing.objects.all()[:2]
In [16]: ls2=cm.Listing.objects.all()[10:13]
In [17]: fs3=cm.Field.objects.all()[:2]
In [18]: q=list(ls1) + list(ls2) + list(fs3)
I'm trying to figure out how best to approach this. I've got a site
model, and a few related models that are loaded in middleware and
stuck on almost every request. I'd like to use select related for
this, but the site model also has foreignkey references from lots of
models I don't need. For ex
There isn't much difference. Once you ennumerate,slice, or iterate a
queryset that's when the actual database query occurs. It will pull
in all matching object in order to save you additional queries.
Why not iterate in batches, by slicing the query? That way if you set
you step to say 100, yo
You could probably use the post_init signal to make a copy of the
model values for comparison in your save method. I'm doing something
similar to create a special manager object each time a certain model
instance is created.
Something like this...
def backup_model_data(sender, instance, signal,
I think you should take a look at writing a custom inclusion tag, and
then using that tag in both views.
http://www.djangoproject.com/documentation/templates_python/#inclusion-tags
Unless I am misunderstanding, they would be perfect for what you want
to do (and are very easy to make).
--~--~--
Hmm. It works in shell for me, I'm not sure what the difference might
be. It only keeps _original_data for the life of the instance, so if
the view completes, the next view is a different instance. You could
make a pickle field to persist it, if you wanted to keep track of the
changed values.
I think what you want is the newforms 'prefix' option. I can't seem
to find it in the docs though, so here is an example. It seems a
little strange to be saving forms in the session, and I can't see how
your quantity updates can happen if you don't access POST in the
update_quantity view at all.
This is long, but my primary question is "How the heck do I save a
picklable copy of POST data, specifically to cache it for use in a
inclusion tag, without manually extracting the data into a normal
dict?"
My tag has a form that posts to a single view that may not be the
current one. I want the
I was curious, so I took a look at how django does the year/day/month
selects. They use a backend specific lookup. This is how you could
do it using postgres.
em.LoggedEvent.objects.filter().extra(where=['extract(MINUTE from
event_loggedevent.when) < 20'])
SQLite doesn't support extract, so dj
> But I need the initial data to be dynamic, so I can't just do
> text = forms.CharField(widget = forms.Textarea, initial = 'sometext')
A form also has an initial argument.
form=YourForm(initial={'formfield1':
formvalue1,'formfield2':formvalue2})
--~--~-~--~~~---~--
Couldn't you get what you are looking for by just returning the songs
function results? The view are just python functions, so you can
return a view from a view. If things get to0 confusing that way,
making one or more helper functions shared between different views is
another option.
def add(r
On Jan 7, 3:05 pm, Darthmahon <[EMAIL PROTECTED]> wrote:
> Hi Doug,
>
> Returning the songs function results worked a treat. I'm looking into
> the generic views part of Django at the moment as it seems to be what
> I want or is it ok for me to do as you suggested above?
I haven't used generic vi
Another alternative is a virtual server via vmware running a small
barebones/server install of your favorite distro. There are a number
of pre-built vmware images online, and vmware player is free now. It
worked out really well for me.
--~--~-~--~~~---~--~~
You re
Assuming you'll have task->subtask1->...subtaskN it seems to be that
a post save signal might be useful since it can recurse easily. You
might have to copy the initial value for is_complete during __init__
and then compare in post save to make sure to act only when the value
has changed.
--~--~
> Basically I'm looking for some users to placate my fear that I'll run
> into insurmountable problems down the road and I'll end up kicking
> myself for not going with a CMS or blog system because the problems
> could have been trivially addressed with those systems.
It all depends on your needs
I'd suggest doing a repr on request.POST and seeing exactly what is
being posted. Your use of getlist usage looks ok, so I'd guess
something is happening on the javascript side.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Goog
> Oh man, that's what I'm afraid of. I know even less about
> javascript. :)
Javascript is something new for me too. It looks like things are
getting encoded twice. From a minute in google it looks like you are
using prototype?
Try:
postBody:Sortable.serialize('sortedriders')
instead of:
para
It doesn't sound like Django is what you want. Django a code
framework that supplies some of the nuts and bolts to make web
development in python easy, but definately not an app. It may look a
bit like an app at first glance due to the much referenced admin
interface, but that's because the admi
I think we'd need to see your Event model class too. It really would
be a good idea to take advantage of the validation from doing this as
a django form, just passing in POST is dangerous. It would also
abstract the whole datetime handling issue for you.
--~--~-~--~~~
> Which - as expected - creates a multi-select box with the appropriate
> cars. Problem is, when the user selects one the form validation kicks
> it out, saying it is not a valid choice. If I don't use the custom
> widget everything is fine, other than it showing cars it shouldn't.
>
> What am I
On Apr 4, 9:32 am, Matias Surdi <[EMAIL PROTECTED]> wrote:
> Hi,
> Is it possible to pass keyword arguments to a custom inclusion tag?
I'm still back on .96, but as far as I know tags only support
positional arguments. I made some helpers that kind of allow a
combination of keyword and positional
I have need of a WYSIWYG editor that won't screw up django templates.
I've been trying to make Innovaeditor work, but it has a bad habit of
breaking the template code by adding entities or throwing it out
altogether. Does anyone have a suggestion for a similar textarea
replacement that might be
> What is the best practice for making it so when I toggle is_featured
> to on for Balboa Park the admin enforces a rule that only one place
> can be featured for a city. Hope that makes sense, thank you.
You could override save on Place and unset the other places. Although
I think it might be b
Its been a while, but I had problems getting this to work at first
too. It turned out to be how I was importing the module that
contained thread locals. I needed to specify the project as well as
the app when doing the import.
I couldn't just do from myapp import mymiddleware, I had to do from
Unless something has changed since.96 you should be able to access
initial and bound data directly. They are stored in dicts on the form
object called 'initial' and 'data'
form.data.fieldname (this is pre-cleaned bound data)
form.cleaned_data.fieldname (post clean if valid)
form.initial.fieldname
I haven't send near 8000 messages yet, but what I did was a
combination of what Malcom suggested. I setup a model to queue the
messages (pickled email.MIMEMultipart) with a priority, and a cron
that runs occasionally to dump N messages per mx domain over time so
the mailing trickles out. to the l
> I'd like to use something like the Django sessions middleware,
> but I don't want to involve cookies or HTTP request headers
> at all. Does anyone have a good way to do this?
Why not? You've got to use some kind of transport to get the XML
there anyway, and django is built with HTTP in mind.
I think you may need to consider looking outside the ORM for imports
of that size. I was having trouble with only about 5 million rows,
and got a reasonable speed up doing executemany. It was still slow
though. I ended up redesigning to eliminate that table, but from what
I read in trying to ma
> Why is that a bad idea?
> If I mainly need CRUD operations it is natural to solve it with admin
> interface.
> Cannot these "security issues" if any eliminated, and use the admin
> interface for a whole site? (if it needs just CRUD).
->ADMIN<- Interface. It wasn't designed to be an entire sit
You can't limit choice like that. The choices specified there are
evaluated only when the model is first evaluated (module load time).
What you need to do is limit the options displayed to the user via
form choices assigned in your view.
So you might do something like this (I'm half asleep, but
My suggestion would be to NOT implement it! I took a similar approach
when I was trying to learn python/django, wasted a bit of time, and
almost never use the monstrosity I created. I'd have been better off
just doing it the django way and/or waiting for newforms to be
completed (which may break
The dev server operates much differently than an actual production
server. The production server will only evaluate module code once
when the module is initially loaded. It doesn't automatically scan
for file changes and load files as necessary like the dev server
does. If you want file changes
If you put the call to your _users() function in the form __init__() I
think it will be what you are looking for. initi s called
automatically whenever an instance is created.
class MemoForm(forms.Form):
-snip-
def __init__(self,*args,**kwarg)
super(MemoForm,self).__init__(*args,**kw
If you put the call to your _users() function in the form __init__() I
think it will be what you are looking for. initi s called
automatically whenever an instance is created.
class MemoForm(forms.Form):
-snip-
def __init__(self,*args,**kwarg)
super(MemoForm,self).__init__(*args,**kw
If you put the call to your _users() function in the form __init__() I
think it will be what you are looking for. initi s called
automatically whenever an instance is created.
class MemoForm(forms.Form):
-snip-
def __init__(self,*args,**kwarg)
super(MemoForm,self).__init__(*args,**kw
Your proposed solution is exactly what I did. I think the official
term is a 'mixin class'. It's worked out really well so far.In my
case the mixin class looks for the Event class defined in the model
for various settings. In your case they might contain a mapping
between your mixin model d
I'd love to know this too. I've had nothing but pain trying to
separate models, and dealing with circular import issues. I spent a
week trying to make mine work well (any model or import changes felt a
lot like playing a round of jinga), and finally gave up and went back
to an absurdly large sin
I've got a problem I can't figure out, and from the silence in IRC I'm
either doing something really stupid or it's as strange as I think it
is. I'd appreciate any assistance.
For a nice highlighted version try: http://dpaste.com/11163/
"""
I'm sorry this is so long. The nutshell version
is tha
Thanks to Malcolm, this was resolved. The problem was because I was
trying to use a model before all models had fully been loaded.
Unfortunately it was due to my own mistake rather than anything that
would help with ticket 1796, but I'm grateful he stuck around to help
figure it out anyway. Hope
I've been looking around the limited signals documentation and the
code hoping to find a signal that basically says 'django is done
importing models ready to receive requests', but haven't found it
yet. The closest I've found is connecting a receiver to
request_started, and then removing that rec
I have an event manager that is a bit like a database driven
pydispatch combined with a general logging/monitoring app.
Embarassingly enough I wrote it before learning about pydispatch and
signals. So much for not reinventing the wheel. It keeps track of
various events, calls registered callback
I think you can make a custom form field to do your validation check
for you.
def StrippedField(forms.CharField):
def clean(self,value):
#do your validation here
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google
Could you just use a collection of forms with different prefixes
(which posted back via a hidden field generated by your script)?
add to each of your
element sets.
class RoomShared(Form):
room_type = IntegerField(widget=Select(choices=BEDROOM_TYPES))
room_price = IntegerField()
is_sh
Not without a little work, atleast as far as I know. A custom manger
is what you want. Then you could do something like
model.current.filter(otherstuff) or make an extra method on the
manager and chain
model.objects.is_current().filter(otherstuff)
class CustManager(models.Manager):
def is_c
I agree with Nicolas. Some fights aren't worth the effort or risk.
Even if it works flawlessly from a technical aspect, it may not go
well for you. Here in the sue happy states it would probably open you
up to quite a bit of legal liability, they least of which would result
in you not getting pa
Search for 'prefix' in the regression tests, that does what you want.
Doesn't seem to be in the docs.
http://code.djangoproject.com/browser/django/trunk/tests/regressiontests/forms/forms.py
--~--~-~--~~~---~--~~
You received this message because you are subscrib
I have a page that needs to display basic user information plus the
last logged activity date for the user, and I need to be able to sort
by that value. (there are two of these relations,I'm just mentioning
one here) My SQL-fu is very, very weak and I just can't seem to get
it.
There is a table
Anwering my own question... it helps to specify an actual join
condition.
This worked:
extra['last_event_when'] = "SELECT event_loggedevent.when FROM
event_loggedevent,event_eventrelation WHERE
(event_eventrelation.event_id = event_loggedevent.id) AND
(event_eventrelation.content_type_id = %s) AN
The bound data and initial data dicts are just set on the form
instance as form.data, and form.initial. This isn't 'clean' data
though, so you are bypassing any newforms validation.
a = AForm( initial = {'x': 1} )
a.initial['x']
--~--~-~--~~~---~--~~
You receive
You might be able to do something like:
qs_big.exclude(pk__in=[o.id for o in qs_small])
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@google
Try just using the year attribute on the datetime instance.
{% ifequal training.start_date.year training.end_date.year %}
...
On Oct 30, 12:28 pm, Nicolas Steinmetz <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Issue : I would like to compare date at year level only. Idea is to
> display the year o
1 - 100 of 114 matches
Mail list logo