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
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
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
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
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
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
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
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
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
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
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 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
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()
> 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
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
> 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 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
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
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
> 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
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
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
> 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
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.
--~--~-~--~~~
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
> 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
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
> 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
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.
--~--~
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
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
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
> 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})
--~--~-~--~~~---~--
> When I tried to run the command (python manage.py syncdb), the table cannot
> be created. The SQL command are just
>
> Begin;
> Commit;
Your form definitions have nothing to do with the database. They are
completely separate things. There are a few helpers that combine the
two for convenience
What you have should work. Using your models (on .96):
In [1]: from sandbox import models as pm
In [2]: p=pm.Poll.objects.get(pk=1)
In [3]: p.choice_set.create(choice="too much tea",votes=0)
Out[3]:
In [4]: p.choice_set.all()
Out[4]: [, ]
Anytime things fail to work the way I expect th
http://www.djangosnippets.org/snippets/377/
I've been using a slightly modified version of this JSONField snippet
for a while now, and it's been really useful for storing info that
doesn't quite fit a field field. I had to make these changes to get
it to work in .96 and let the admin edit the mo
I think you want filter's evil twin exclude:
http://www.djangoproject.com/documentation/0.96/db-api/#exclude-kwargs
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send e
It might depend on your cache setting in setting.py, and the devserver
reloading on file change. I've had that happen and confuse things a
bit. Going straight to memcache or file based for low level caching
development was the only way to get consistent.
There are also some limitations on the s
Is there a way to make custom model field that works normally except
for database interaction where it is ignored. In looking at the
source it doesn't seem possible but I thought it couldn't hurt to ask.
I have a serialized model field, based on a text field. I usually use
it to store random bi
The save() method on a form doesn't actually exist in every case. If
you use the helper functions like form_for_model and
form_for_instance, they will magically create it for you. The form
builders make sure there is enough info in the form (hidden or
otherwise) to tie it to a model instance.
Django forms are just form elements, not the whole form. The easy
approach is to split your form into several django forms, and process
them separately in the view. If you have multiple instances of the
same form class you can keep them identified by using a prefix when
you instantiate each (you
For cookie/session setup:
http://www.djangoproject.com/documentation/sessions/
If you don't want to roll your own user framework:
http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/
You might also want to reconsider your model, unless you have other
reasons for needing the
It looks like you have a search view that uses form POST data, and you
want a shortcut to be able to show a predetermined search. So if you
were a clothing store, you might want to use a link click to show all
the Jackets, another all the Pants, etc. I think the best way to
handle that is to not
I'd love to know if there is a better method, but this is the best I
could come up with... pretty much the same thing you are doing, but
forcing the view functions to call 'import_feed' which can only load a
restricted set of modules.
AVAILABLE_FEEDS =
{'columbia':'columbia.search','glvar':'glvar
Could you do something like a wrapper object in your view before it
hits the context? The wrapper below relies on a field list, but you
could easily have it inspect the Meta class on the model and build the
list.
class RedWrap(object):
def __init__(self,restrict,obj,attrlist=[]):
1st: http://www.b-list.org/weblog/2006/jun/13/how-django-processes-request/
2nd: Tutorial
3rd: The docs, just sit down and read them. If you expect to use them
as a reference manual without reading them first it will probably
cause you trouble... they just aren't written that way.
After doing th
You might consider a single view and form class, and then doing your
split up in the template using form.field to print the fields you want
for that 'page' by passing the page in with the context. Leave the
form processing to a single form and view.
Rather than worry with pages I'd probably just
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
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
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
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
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
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 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
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
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
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
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
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 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.
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 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).
--~--~--
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,
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
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
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)
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
> 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
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
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
> 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
> 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
> [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
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
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
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.")
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
> ---
>
> 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
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
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
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()
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
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
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
> 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
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
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.
--~--~-~--~~~---~--~---
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
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
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
> 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
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
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
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
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
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
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
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
1 - 100 of 114 matches
Mail list logo