Re: Why INSERT instead of UPDATE?

2010-11-08 Thread Torbjörn Lundquist
SOLVED!

It was a typo, the action attribute was pointing to the wrong view. Thanks a
lot for the help!

/Torbjörn


2010/11/8 Knut Ivar Nesheim 

> Look at the HTML for the form. The 'action' attribute tells the
> browser where to submit the post. The view responsible for that URL is
> the one you should be looking at.
>
> If you have a ModelForm with no instance, Django will insert a new
> row. If there is an instance and you call form.save(), it will be
> updated (unless you have mucked about with model.pk or are forcing an
> insert)
>
> And to answer the "return to" question. Whenever you do:
>
>return HttpResponseRedirect('/url/')
>
> it will appear as a completely new request to '/url/'. No magic going on
> here.
>
> Where it can get confusing is if you are using the 'reverse' or
> 'redirect' functions, which will do a reverse lookup of urls or views
> based on url name or method name. If you have multiple urls with the
> same name and arguments, for instance, you can run into problems.
>
>
> On Mon, Nov 8, 2010 at 9:48 PM, Torbjörn Lundquist
>  wrote:
> > That did not help.
> > I think I know what the problem is but I don't know how to solve it:
> > It seems that when I press the Submit button I jump to another
> view-function
> > (that inserts a new course). So, I use the same form i two different
> places,
> > both for insert and update. How does django know which view-function it
> > should "return" to?
> > /Torbjörn
> > 2010/11/7 cootetom 
> >>
> >> This is a tough one, everything looks okay. I would try removing the
> >> categories variable from your model class just to see if that is
> >> causing problems. By the way, you can get that categories list from an
> >> instance of the Course class in the following way
> >> c.coursecategories_set.all() presuming CourseCategory has a foreign
> >> key back to Course and c = a Course instance.
> >>
> >> The other thing to check is the POST. Perhaps if it contains a key
> >> named "id" it would cause an insert, just a guess though.
> >>
> >>
> >>
> >> On Nov 7, 7:09 pm, Torbjorn  wrote:
> >> > Here is the model:
> >> >
> >> > class Course(models.Model):
> >> > title = models.CharField(max_length=255)
> >> > owner = models.ForeignKey(User)
> >> >
> >> > def __unicode__(self):
> >> > return self.title
> >> >
> >> > def _getCategories(self):
> >> > cc = CourseCategories.objects.filter(course=self)
> >> > return cc
> >> >
> >> > categories = property(_getCategories)
> >> >
> >> > and the form:
> >> >
> >> > class PartialCourseForm(ModelForm):
> >> > class Meta:
> >> > model = Course
> >> > exclude = ('owner')
> >> >
> >> > Thanks
> >> > /Torbjörn
> >> >
> >> > On 7 Nov, 16:34, Marc Aymerich  wrote:
> >> >
> >> >
> >> >
> >> >
> >> >
> >> >
> >> >
> >> > > On Sun, Nov 7, 2010 at 4:21 PM, Torbjorn
> >> >
> >> > >  wrote:
> >> > > > Hi, I want to update a record but somehow it becomes an INSERT
> >> > > > instead. This is my code:
> >> >
> >> > > > def editcourse(request, course_id):
> >> > > >course= Course.objects.get(id=course_id)
> >> > > >if request.method == 'POST':
> >> > > >form = PartialCourseForm(request.POST, instance=course)
> >> > > >if form.is_valid():
> >> > > >form.save()
> >> > > >return HttpResponseRedirect("/courses/")
> >> > > >else:
> >> > > >form = PartialCourseForm(instance=course)
> >> >
> >> > > >return render_to_response("editcourse.html", {'form':form})
> >> >
> >> > > > What do I wrong?
> >> >
> >> > > Can you paste your course model?
> >> >
> >> > > --
> >> > > Marc
> >>
> >> --
> >> 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.
> >
>
> --
> 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
> .
> 

django-registration 0.7 or 0.8

2010-11-08 Thread Oivvio Polite
What version of django-registration do you folks recommend?
A  plain "pip install" gave me 0.7, but some discussions on the
intarwebs seem to indicate that people are using the yet unreleased 0.8.

oivvio

-- 
http://pipedreams.polite.se/about/


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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.



Using Django's auth for Trac too

2010-11-08 Thread Torsten Bronger
Hallöchen!

I know that my question has a strong Apache component, but can
anybody here give me hints for how to use Django's auth system for a
Trac installation running on the same Apache?  I.e., iff someone is
logged in in Django, it is also authenticated in Trac.  I already
have my own Django auth module that just needed to be fleshed out.
Maybe Django keeps a file up-to-date with all logged-in users, which
Apache uses for Trac authentication?

Thank you!

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: torsten.bron...@jabber.rwth-aachen.de
  or http://bronger-jmp.appspot.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.



hello xD

2010-11-08 Thread Daniel Lathrop
hello:
I have good news for you. Last week
I have Order china 25 Products Apple Macbook Pro 2.8 GHz 15 MB986LL/A 4GB
I  completed  bank transfer payments,I have received the product!
w e b: tooaomo.com
It's amazing! The item is original, brand new and has high quality,
but it's muc cheaper. I'm pleased to share this good news with you!
I believe you will find what you want there and have an good experience
on shopping from them
Regards!









nbmnbm 123   哉

-- 
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: Total in a django template

2010-11-08 Thread Gath
Try using custom tags

Create a folder called "templatetags" in your application folder, in
there create two files
 __init__.py
 customtags.py# this will have your custom tags/filters, please
note it can be any name.

Open your customtags.py file and drop the following lines and save.

from django.template import Library

register = Library()

@register.filter
def running_total(fine_list):
return sum(d.get('fine_sum') for d in fine_list

In your template call the customtags file like this

{% load customtags %}

i guess by this time you have a list of dict that you passed from your
view lets say its called "fines"

{% for fine in fines %}
  Display your fine items inside this loop
{% endfor %}

outside the loop call the customtag like this

 {{ fines.list|running_total }} 

It works for me.

Paul.



On Nov 9, 12:09 am, Knut Ivar Nesheim  wrote:
> You need to sum the fines before you enter the templates.
>
> This can be done either in your view like this:
>     total_fines = sum([item.fine for item in items])
>
> Or you can do it in the db using the 'Sum' aggregate, 
> seehttp://docs.djangoproject.com/en/dev/ref/models/querysets/#sum
>
> Regards
> Knut
>
> On Sun, Nov 7, 2010 at 12:32 AM, Michael Sprayberry
>
>
>
>
>
>
>
>  wrote:
>
> > Hello,
> >     I am not sure if this is what you are looking for but you can use a 
> > forloop.counter (index to 1) or a forloop.counter0 (index at 0) from within 
> > the template {% for loop %}
>
> > Michael
>
> > Hi,
> > In a django template I have a for loop that display (item, fine). I
> > would like to compute the total fine value at the end of the for loop.
> > Is it possible to compute the total in the template? How can I do 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 
> > athttp://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 
> > athttp://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: Adding in more sort mechanisms

2010-11-08 Thread David Cramer
Google seems to have deemed it a good idea to rename this thread
title. This is regarding Sentry (aka django-sentry), a 3rd party
Django app.

On Nov 8, 8:12 pm, David Cramer  wrote:
> I'm looking for feedback regarding something I want to implement in
> Sentry [1].
>
> Currently we allow sorting by a few things, but its mostly based
> around the "times_seen" value. Times seen is useful, and always
> available, but there are many use cases where log messages would be
> better to group by some other value.
>
> Cases are:
>
> - Grouping slow queries.
> - Performance logging.
>
> Various sort methods would be:
>
> - Times seen
> - Priority (this is now arbitrary, since if its a value sort its not
> using the times_seen / last_seen algorithm)
> - Total Time Spent (Should this be abstracted as Value?)
> - Average Time Spent (Again, Average Value?)
>
> We need to determine the best way to sort this data. Some ideas:
>
> - Specify certain loggers have a default sort
> - Specify global default sort
> - Specify "type" of message when logging. This would be multiple
> values. Some would be tally, some would be duration (value).
>
> I've opened an issue on GitHub regarding this, so feel free to leave
> feedback there as well.
>
> [1]https://github.com/dcramer/django-sentry
> [2]https://github.com/dcramer/django-sentry/issues/issue/39

-- 
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.



[Sentry] Adding in more sort mechanisms

2010-11-08 Thread David Cramer
I'm looking for feedback regarding something I want to implement in
Sentry [1].

Currently we allow sorting by a few things, but its mostly based
around the "times_seen" value. Times seen is useful, and always
available, but there are many use cases where log messages would be
better to group by some other value.

Cases are:

- Grouping slow queries.
- Performance logging.

Various sort methods would be:

- Times seen
- Priority (this is now arbitrary, since if its a value sort its not
using the times_seen / last_seen algorithm)
- Total Time Spent (Should this be abstracted as Value?)
- Average Time Spent (Again, Average Value?)

We need to determine the best way to sort this data. Some ideas:

- Specify certain loggers have a default sort
- Specify global default sort
- Specify "type" of message when logging. This would be multiple
values. Some would be tally, some would be duration (value).

I've opened an issue on GitHub regarding this, so feel free to leave
feedback there as well.

[1] https://github.com/dcramer/django-sentry
[2] https://github.com/dcramer/django-sentry/issues/issue/39

-- 
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: Exclude form field when calling form from view

2010-11-08 Thread Ed
I can fall back on the subclassing suggestion.  But I'd like to give
this one more shot for a fix.  I think it has something to do with the
request.FILES that I need.  Here is my complete form:

class UploadFileForm(forms.Form):
def __init__(self, show_title=True, *args, **kwargs):
super(UploadFileForm, self).__init__(*args, **kwargs)
if not show_title:
del self.fields['title']

def clean_file(self):
content = self.cleaned_data['file']
content_type = content.content_type.split('/')[0]
if content_type in settings.CONTENT_TYPES:
if content._size > settings.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_('Please keep 
filesize under %s.
Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE),
filesizeformat(content._size)))
else:
raise forms.ValidationError(_('File type is not 
supported'))
return content

title = forms.CharField(max_length=50)
file = forms.ImageField(label='Select photo to upload')


And here is my complete view:

def upload_file(request, modelname, id):
if modelname == 'film':
form = UploadFileForm()
else:
form = UploadFileForm(show_title=False)

object = get_object_or_404(modelname, id__iexact=id)
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES["file"]
filename = file.name
content = file.read()

# Assign unique name to file
new_image_name, extension = unique_name(filename, 
object,
modelname)

#FUTURE: Resize middle and resize remaining in 
background
#SMALL
#img_resizer(content)
u_small = new_image_name + '_small.jpg'
store_in_s3(u_small, img_resizer(content,250,250,90))

# Save thumbnail url to object
object.url_small = u_small
object.save()

# Grab Next param to determine where to redirect back to
redirect_to = request.GET.get('next', 
reverse('index_view'))
return HttpResponseRedirect(redirect_to)
else:
# If form validation fails, use original reverse url
redirect_to = request.GET.get('next', 
reverse('index_view'))

else:
# If first loading form, grab referer and pass to form
referer = request.META.get('HTTP_REFERER', None)

# Pass original location in next url param
if referer is None:
redirect_to = reverse('index_view')
else:
try:
redirect_to = urlsplit(referer, 'http', 
False)[2]
except IndexError:
redirect_to = reverse('index_view')


return render_to_response('upload.html', {'form': form,'obj':
object,'redirect_to':redirect_to}, context_instance =
RequestContext(request))

If I remove the def __init__ from the form class, it works perfectly,
but always shows the title.  But with that in the form class, it
always says "This field is required."  For just the imagefield if the
title is suppressed or for both the title and the imagefield if the
title is not suppressed.

Suggestions?

On Nov 8, 3:47 pm, Knut Ivar Nesheim  wrote:
> Maybe you could just use subclassing instead of doing stuff at run-time:
>
> class UploadForm(forms.Form):
>     file = ...
>     # custom upload and validation code here
>
> class ThumbnailUploadForm(UploadForm):
>     pass
>
> class UploadFileForm(UploadForm):
>     title = ...
>
> As for your current approach, it looks correct. I've done the same
> several times and it works as expected. Make sure you are really
> really passing show_title correctly in your thumbnail case.
>
> Regards
> Knut
>
> On Mon, Nov 8, 2010 at 9:29 PM, Ed  wrote:
> > I have an image upload form that takes a title and a file for its
> > field. I have two uses for it. Most of the time I call it, I need both
> > a title and the image itself. But when I call it simply to grab a
> > thumbnail, I don't need the title. In fact, the form data is saved to
> > a different model that doesn't even have title as a field.
>
> > I wanted to suppress the "title" field when I call the form. I could
> > have created two form classes in my forms.py, but this seemed
> > unnecessarily repetitious.
>
> > I included the following in my image form class:
>
> > def __init__ 

Create a ContentType object on model save

2010-11-08 Thread Kenny Meyer
Hello,

I have two models, 1) FlashCard and 2) Practice, and I have a generic relation
in the FlashCard model pointing to the Practice model using the contenttypes
framework.
The Practice model tracks information like how many times something was
practiced, and calculates an `easy factor'.
Each time I save a FlashCard I want at the same time to create Practice
object for the flashcard, automatically.


class Practice(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
item = generic.GenericForeignKey('content_type', 'object_id')

user = models.ForeignKey(User)


class FlashCard(models.Model):
"""
A basic Flashcard.

Has a front and a back view.
"""
front = models.TextField(
max_length = 255,
verbose_name = "Front")
back = models.TextField(
max_length = 255,
verbose_name = "Back")
user = models.ForeignKey(User)
practice = generic.GenericRelation(Practice)


I read the contenttypes documentation, and as far as I understand to create a
related Practice object for a flashcard instance I should do the following:

>>> user = User.objects.get(username="kenny")
# Create a sample flashcard
>>> flashcard = ("bla", "bla", user)
# ...and create a Practice object for it
>>> new_practice = Practice(item=flashcard)
# then I try to save it, but that fails with a large backtrace
>>> new_practice.save()
[snip]

Here the actual backtrace: http://dpaste.com/hold/272617/


Well, but this is not the reason I opened this thread. Still I want to create
Practice object for my FlashCard object.

I started a research on Google, but I really haven't found anything really
helping me to do that.

Can you guys give me a helping hand on this with your expertise, please?

Additional information about my environment:
  - Django 1.2.3
  - PostgreSQL 8.4.5

Cheers,
Kenny

-- 
- Kenny Meyer 
To understand recursion, we must first understand recursion.
--


pgp3RUd4A9RGp.pgp
Description: PGP signature


non-ASCII characters in {{}}

2010-11-08 Thread Sébastien RAGONS
Hello,

I try to display an article but there is char like 'é'.
The template is correctly displayed but there is no trace 
of the article (and no error are logged).

the line 'print html' show th article correctky:
Table des matières
Erreur
404
Erreur 404

La page demandée n'existe pas !


If i remove all the 'é', the page is correct and full

def displayArticle(request, nomArticle):
article = Article()
html = article.lecture(nomArticle)
print html 
return render_to_response('article.html',
{'article': html})


It's not a probleme with the template because if i send 'é'
throw it, it's ok.

could you help me

sebastien

-- 
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: Call a function after a model with inlines is created [solved]

2010-11-08 Thread Martin Tiršel
On Sun, 31 Oct 2010 20:15:19 +0100, Daniel Roseman   
wrote:



On Oct 31, 4:46 pm, Martin Tiršel  wrote:

If this is only needed for the admin, you probably want to override
the ModelAdmin's response_add method. This is called after the add
form has been processed and all the resulting objects saved. Be sure
to call (and return) the super method after you've done your
processing.
--
DR.



Yes, this seems to be the right place, thank you.

Martin

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-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.



Generic Views - do you use them?

2010-11-08 Thread Ted
What are their pros and cons?  How often do you use them when you're
coding?

The more I code in django the less I find generic views to be useful
shortcuts (direct to template being the exception).

My biggest complaints are:
* You don't end up saving many keystrokes unless you have 3 or more
views that are going to use the same info_dict.
* They can't be tweaked or changed much before you have to move the
code to the views file, destroying the keystroke savings.
* Second syntax for doing the same thing makes Django harder to
learn.

Am I alone on this?

I've thought about it and i think there is a better way.  I want to
see if there are others in the community who aren't in love with
generic views before I develop the alternate approach.

I'm not trying to start a flame war.

-- 
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.



Structured search pages?

2010-11-08 Thread James Smagala
Hey All,

I'm looking to improve the search functionality for my site.  It is
currently based on a highly customized django-seeker, but I'm hitting
a wall trying to move forward with that package.  (Not maintained, and
doesn't work at all out of the box on my site).

Can anyone offer suggestions?  The full-text solutions currently
available are tailored for text content with a little structure (tags,
categories).  My data is exactly the opposite - highly structured,
with a handful of comment fields that can easily be handled with ilike
queries without a big performance hit.

The goal is to provide non-programmer scientists with a visual 'query
builder' - a large number of filters to drill down to a dataset of
interest, then download it.  The concept is well described, but not
well implemented, by the django-seeker package.

Suggestions?

Thanks in advance,

James

-- 
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: clean method in a model

2010-11-08 Thread cootetom
If you want to associate an error to a specific field in a model form
then you need to populate self._errors with the error you find. Have a
read about this on the Django docs to see how it is done.

http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-validation

The last example shows how to associate a error with a specific field
in a form class.




On Nov 8, 8:40 pm, refreegrata  wrote:
> Hello list. I want to use the clean method in a model.
> --
> class myModel(models.Model):
>     fields 
>
>     def clean(self):
>             raise ValidationError('The Error.')
> ---
>
> Thats works fine. My question  is, how can I associate this error to
> the field in the modelform?. With this method the form validation can
> be controlled, but I can't pick the error dynamically to show at the
> user.
>
> Thanks for read.

-- 
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: creating a combined form linked via foreign key??

2010-11-08 Thread sosurim kim
Oops, I meant to say addressbook, not phonebook... sorry.

# models.py
class Myuser(User):
  bio = models.TextField()

class AddressBook(models.Model):
  userid = models.ForeignKey(CustomUser, blank=True, null=True)
  address = models.CharField(max_length=50)
  city = models.CharField(max_length=50)
  zip = models.CharField(max_length=20)
  state = models.CharField(max_length=50)

# admin.py
from django.contrib import admin
from models import *

class AddressBookInline(admin.TabularInline):
  model = AddressBook
  can_delete = True

class CustomUserAdmin(admin.ModelAdmin):
  inlines = ( AddressBookInline )
  fk_name = 'userid'

admin.site.register(Myuser, CustomUserAdmin)

>
>
> So when I go into django admin, I see all the fields for Myuser, but
> AddressBook fields appear three times. It doesn't matter whether I subclass
> StackedInline or TabularInline, I get the AddressBook three times.
>
> Is there a better way to create a combo form that contains two (or more)
> models linked with a foreign key (or manytomany, onetomany, etc.)??
>
> Thanks,
>
> S
>

-- 
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.



Threaded script

2010-11-08 Thread Big Gosh
Hello everybody.

I wrote a web application using Django. On server side I wrote also a
python script that runs as a deamon. The script is threaded and uses
the model I wrote for Django to access the postgres DB. Now i found a
thing I'm not able to solve: each thread waiting on a TCP socket opens
also a connection to postgresql.

Is there a way to have a multi-threaded deamon that opens only one
connection? I'm quite sure I'm going on with a stupid error but during
this last months I was not able to solve it.

Thanks in advance
christian f.

-- 
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.



creating a combined form linked via foreign key??

2010-11-08 Thread sosurim kim
Sorry if this has been asked before, but how can I create a form that is a
combination of two models linked through a foreign key? For example, let's
say I have two models:

# models.py
class Myuser(User):
  bio = models.TextField()

class AddressBook(models.Model):
  userid = models.ForeignKey(CustomUser, blank=True, null=True)
  address = models.CharField(max_length=50)
  city = models.CharField(max_length=50)
  zip = models.CharField(max_length=20)
  state = models.CharField(max_length=50)

# admin.py
from django.contrib import admin
from models import *

class PhoneBookInline(admin.TabularInline):
  model = PhoneBook
  can_delete = True

class CustomUserAdmin(admin.ModelAdmin):
  inlines = ( PhoneBookInline )
  fk_name = 'userid'

admin.site.register(Myuser, CustomUserAdmin)

So when I go into django admin, I see all the fields for Myuser, but
PhoneBook fields appear three times. It doesn't matter whether I subclass
StackedInline or TabularInline, I get the PhoneBook three times.

Is there a better way to create a combo form that contains two (or more)
models linked with a foreign key (or manytomany, onetomany, etc.)??

Thanks,

S

-- 
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: Total in a django template

2010-11-08 Thread Knut Ivar Nesheim
You need to sum the fines before you enter the templates.

This can be done either in your view like this:
total_fines = sum([item.fine for item in items])

Or you can do it in the db using the 'Sum' aggregate, see
http://docs.djangoproject.com/en/dev/ref/models/querysets/#sum

Regards
Knut

On Sun, Nov 7, 2010 at 12:32 AM, Michael Sprayberry
 wrote:
>
> Hello,
>     I am not sure if this is what you are looking for but you can use a 
> forloop.counter (index to 1) or a forloop.counter0 (index at 0) from within 
> the template {% for loop %}
>
>
> Michael
>
> Hi,
> In a django template I have a for loop that display (item, fine). I
> would like to compute the total fine value at the end of the for loop.
> Is it possible to compute the total in the template? How can I do 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.
>
>
> --
> 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: Enclosing intervals with dates on django

2010-11-08 Thread Knut Ivar Nesheim
Your query can be translated into the ORM by simply using '__gt' and
'__lt' on your start_date and ends_date.

Regards
Knut

2010/11/8 Rogério Carrasqueira :
> Hello Everybody!
>
> I'm developing a routine that will control the information about scheduled
> events and it will avoid that some events override others and prevent that
> it cannot happen. I made a query on mysql where that works fine and gives
> the results that I need. For example I have an event that begins at 05
> november and ends at 22 november, it must lock the agenda to prevent another
> event in this date range, so if I try to insert a new event that will hapens
> on 09 november and ends at 14 november, the system will return a message
> reporting that this operation cannot be done due the collision with another
> event previously scheduled.
>
> My goal is translate this query to ORM Django: select * from my_table  where
> ('2010-11-09' between start_date AND ends_date) or ('2010-11-14' between
> start_date AND ends_date )
>
> I've tried with range atribute but I was'n happy on this way
>
> Someone can help?
>
> Thanks so much!
>
> Rogério Carrasqueira
>
> ---
> e-mail: rogerio.carrasque...@gmail.com
> skype: rgcarrasqueira
> MSN: rcarrasque...@hotmail.com
> ICQ: 50525616
> Tel.: (11) 7805-0074
>
> --
> 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: Why INSERT instead of UPDATE?

2010-11-08 Thread Knut Ivar Nesheim
Look at the HTML for the form. The 'action' attribute tells the
browser where to submit the post. The view responsible for that URL is
the one you should be looking at.

If you have a ModelForm with no instance, Django will insert a new
row. If there is an instance and you call form.save(), it will be
updated (unless you have mucked about with model.pk or are forcing an
insert)

And to answer the "return to" question. Whenever you do:

return HttpResponseRedirect('/url/')

it will appear as a completely new request to '/url/'. No magic going on here.

Where it can get confusing is if you are using the 'reverse' or
'redirect' functions, which will do a reverse lookup of urls or views
based on url name or method name. If you have multiple urls with the
same name and arguments, for instance, you can run into problems.


On Mon, Nov 8, 2010 at 9:48 PM, Torbjörn Lundquist
 wrote:
> That did not help.
> I think I know what the problem is but I don't know how to solve it:
> It seems that when I press the Submit button I jump to another view-function
> (that inserts a new course). So, I use the same form i two different places,
> both for insert and update. How does django know which view-function it
> should "return" to?
> /Torbjörn
> 2010/11/7 cootetom 
>>
>> This is a tough one, everything looks okay. I would try removing the
>> categories variable from your model class just to see if that is
>> causing problems. By the way, you can get that categories list from an
>> instance of the Course class in the following way
>> c.coursecategories_set.all() presuming CourseCategory has a foreign
>> key back to Course and c = a Course instance.
>>
>> The other thing to check is the POST. Perhaps if it contains a key
>> named "id" it would cause an insert, just a guess though.
>>
>>
>>
>> On Nov 7, 7:09 pm, Torbjorn  wrote:
>> > Here is the model:
>> >
>> > class Course(models.Model):
>> >     title = models.CharField(max_length=255)
>> >     owner = models.ForeignKey(User)
>> >
>> >     def __unicode__(self):
>> >         return self.title
>> >
>> >     def _getCategories(self):
>> >         cc = CourseCategories.objects.filter(course=self)
>> >         return cc
>> >
>> >     categories = property(_getCategories)
>> >
>> > and the form:
>> >
>> > class PartialCourseForm(ModelForm):
>> >     class Meta:
>> >         model = Course
>> >         exclude = ('owner')
>> >
>> > Thanks
>> > /Torbjörn
>> >
>> > On 7 Nov, 16:34, Marc Aymerich  wrote:
>> >
>> >
>> >
>> >
>> >
>> >
>> >
>> > > On Sun, Nov 7, 2010 at 4:21 PM, Torbjorn
>> >
>> > >  wrote:
>> > > > Hi, I want to update a record but somehow it becomes an INSERT
>> > > > instead. This is my code:
>> >
>> > > > def editcourse(request, course_id):
>> > > >    course= Course.objects.get(id=course_id)
>> > > >    if request.method == 'POST':
>> > > >        form = PartialCourseForm(request.POST, instance=course)
>> > > >        if form.is_valid():
>> > > >            form.save()
>> > > >            return HttpResponseRedirect("/courses/")
>> > > >    else:
>> > > >        form = PartialCourseForm(instance=course)
>> >
>> > > >    return render_to_response("editcourse.html", {'form':form})
>> >
>> > > > What do I wrong?
>> >
>> > > Can you paste your course model?
>> >
>> > > --
>> > > Marc
>>
>> --
>> 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.
>

-- 
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: Validator for \t

2010-11-08 Thread J. Cliff Dyer
On Mon, 2010-11-08 at 12:21 -0800, Ralf wrote:
> Hi,
> 
> my users put values like 'Paul\t\t' per copy and paste into html-
> formfields and suceeded, the values ended up in the database.
> I wonder whether there is no build-in-validator to prevent these kind
> of invalid input.
> 
> Is there a cheap way to validate or strip these kind of input?
> 

Yep.  A string in python has a strip() method that will take any
whitespace off the beginning and end of the string.

>>> username = username.strip()

You can also specify characters to strip off.

>>> username = ' abcd .,.'
>>> username = username.strip('.,')
>>> username
' abcd '

You should really check out the python tutorial at
http://docs.python.org/tutorial/

Cheers,
Cliff


-- 
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 INSERT instead of UPDATE?

2010-11-08 Thread Torbjörn Lundquist
That did not help.

I think I know what the problem is but I don't know how to solve it:

It seems that when I press the Submit button I jump to another view-function
(that inserts a new course). So, I use the same form i two different places,
both for insert and update. How does django know which view-function it
should "return" to?

/Torbjörn

2010/11/7 cootetom 

> This is a tough one, everything looks okay. I would try removing the
> categories variable from your model class just to see if that is
> causing problems. By the way, you can get that categories list from an
> instance of the Course class in the following way
> c.coursecategories_set.all() presuming CourseCategory has a foreign
> key back to Course and c = a Course instance.
>
> The other thing to check is the POST. Perhaps if it contains a key
> named "id" it would cause an insert, just a guess though.
>
>
>
> On Nov 7, 7:09 pm, Torbjorn  wrote:
> > Here is the model:
> >
> > class Course(models.Model):
> > title = models.CharField(max_length=255)
> > owner = models.ForeignKey(User)
> >
> > def __unicode__(self):
> > return self.title
> >
> > def _getCategories(self):
> > cc = CourseCategories.objects.filter(course=self)
> > return cc
> >
> > categories = property(_getCategories)
> >
> > and the form:
> >
> > class PartialCourseForm(ModelForm):
> > class Meta:
> > model = Course
> > exclude = ('owner')
> >
> > Thanks
> > /Torbjörn
> >
> > On 7 Nov, 16:34, Marc Aymerich  wrote:
> >
> >
> >
> >
> >
> >
> >
> > > On Sun, Nov 7, 2010 at 4:21 PM, Torbjorn
> >
> > >  wrote:
> > > > Hi, I want to update a record but somehow it becomes an INSERT
> > > > instead. This is my code:
> >
> > > > def editcourse(request, course_id):
> > > >course= Course.objects.get(id=course_id)
> > > >if request.method == 'POST':
> > > >form = PartialCourseForm(request.POST, instance=course)
> > > >if form.is_valid():
> > > >form.save()
> > > >return HttpResponseRedirect("/courses/")
> > > >else:
> > > >form = PartialCourseForm(instance=course)
> >
> > > >return render_to_response("editcourse.html", {'form':form})
> >
> > > > What do I wrong?
> >
> > > Can you paste your course model?
> >
> > > --
> > > Marc
>
> --
> 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: Exclude form field when calling form from view

2010-11-08 Thread Knut Ivar Nesheim
Maybe you could just use subclassing instead of doing stuff at run-time:

class UploadForm(forms.Form):
file = ...
# custom upload and validation code here

class ThumbnailUploadForm(UploadForm):
pass

class UploadFileForm(UploadForm):
title = ...

As for your current approach, it looks correct. I've done the same
several times and it works as expected. Make sure you are really
really passing show_title correctly in your thumbnail case.

Regards
Knut

On Mon, Nov 8, 2010 at 9:29 PM, Ed  wrote:
> I have an image upload form that takes a title and a file for its
> field. I have two uses for it. Most of the time I call it, I need both
> a title and the image itself. But when I call it simply to grab a
> thumbnail, I don't need the title. In fact, the form data is saved to
> a different model that doesn't even have title as a field.
>
> I wanted to suppress the "title" field when I call the form. I could
> have created two form classes in my forms.py, but this seemed
> unnecessarily repetitious.
>
> I included the following in my image form class:
>
> def __init__ (self, show_title=True):
>    super (BaseClass, self).__init__()
>    if not show_title:
>        del self.fields['title']
>
> This works great except for one thing. Now I'm getting validation
> errors: "This field is required" whether I suppress the title field or
> not. Any time I try to submit the form, it tells me I need to enter
> data.  Any advice on how to do this correctly?
>
> class UploadFileForm(forms.Form):
>    def __init__ (self, show_title=True):
>        super (BaseClass, self).__init__()
>        if not show_title:
>            del self.fields['title']
>
>    title = forms.CharField(max_length=50)
>    file = forms.ImageField(label='Select photo to upload')
>
> --
> 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: Obtaining And Caching User Context

2010-11-08 Thread Daniel Roseman
On Nov 8, 5:54 pm, octopusgrabbus  wrote:
> I am able to log into my form page, which is a simple form asking the
> user for one value. If that value is entered successfully, I am able
> to redirect to another "you were successful" page. However, my
> template logic that checks to see if the user is authenticated -- as
> far as I can tell the user is logged using Django's admin resources --
> says the user is not authenticated.
>
> How is a user's being authenticated cached, so another html template
> knows that fact?

It's not 'cached'. A user's logged-in status is identified via their
session cookie, which is sent to the server on every request and
processed via the authentication middleware.

However, I suspect your problem is simpler. Are you sure you are
passing the request, or the user, to the second template? It would
help if you posted the code for the relevant view and template.
--
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: Custom formset validation: having a "save?" checkbox for each form

2010-11-08 Thread Knut Ivar Nesheim
Hi,

Every Form subclass defines a method called 'is_valid()', even the
FormSet has one, which will repeatedly call it on every form. After
running is_valid(), form.cleaned_data will contain cleaned data from
the forms.

On subclasses of FormSet you can also override the clean method, which
allows you to do validation that depends on multiple forms, for
example making sure the same day is not reported twice, etc. See
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#custom-formset-validation

Rewriting your view to take advantage of this, as well as a nice idioms:

def my_view(...):
formset = FormsetFactory(request.POST or None)

if formset.is_valid():
for form in formset.forms:
if form.cleaned_data['should_save']:
# save stuff here
return redirect(my_other_view)

return render_to_response('template', { 'formset': formset })

Replace with meaningful variables specific to your forms and models.

As a side note, every subclass of Form allows overriding the clean
method for doing custom validation. This can be extremely helpful in
cases like this, as you can move complex logic from your view, into
the forms which have access to everything.

As another side note, you mentioned in the comment to pause that you
actually want to store a timedelta. See this snippet for a Field which
does exactly that: http://djangosnippets.org/snippets/1060/ See the
following SO question for how to do it yourself:
http://stackoverflow.com/questions/801912/how-to-put-timedelta-in-django-model

Regards
Knut

On Mon, Nov 8, 2010 at 6:48 PM, Carsten Fuchs  wrote:
> Hi all,
>
> my name is Carsten Fuchs, and this is my first post here. I'm normally a C++
> developer for Windows and Linux desktop and server applications, and have
> begun my first (big) database-web project in mid summer. Let me start with
> saying that Django is utterly awesome: I've been able to complete a very
> large part of this project in very short time, reading the excellent Django
> online documentation and the Django online book. A huge thanks to everyone
> who is involved!
>
> My Django application is for recording and managing the work hours of the
> staff of a company with about 1000 employees, implemented on Ubuntu 10.04
> with Django 1.2, Python 2.6, Apache2 as webserver, and an Oracle 10g
> database.
>
> My question is about validating the formset that is used for editing the
> work hours (but I'm happy about all comments on whatever strikes you odd in
> the code below ;-) ).
>
>
> The main model is (slightly simplified for clarity):
>
> # This model should really be named "Workday", not "Erfasst".
> class Erfasst(models.Model):
>    key    = models.ForeignKey(Mitarbeiter, db_column='key', to_field='key')
>    datum  = models.DateField()
>    anfang = models.TimeField()   # Begin of work.
>    ende   = models.TimeField()   # End of work.
>    pause  = models.CharField(max_length=8, blank=True)     # (Need a
> timedelta field...)
>
>
> I wrote a view with a formset for editing the work hours in the above model
> of an entire week or month. The form is:
>
> class ErfasseZeitForm(forms.Form):
>    # ID of "Erfasst" entry, if present in database.
>    ErfasstID = forms.IntegerField(required=False,
> widget=forms.HiddenInput())
>
>    # We must pass the date for days that are not yet mentioned in the
> database.
>    Datum     = forms.DateField(widget=forms.HiddenInput())
>
>    # Begin, end, and pause of work.
>    Anfang    = forms.TimeField(required=False)
>    Ende      = forms.TimeField(required=False)
>    Pause     = forms.TimeField(required=False)
>
>    # A checkbox for "Save this form?" (which is part of a formset that
> covers an entire month)
>    Speichern = forms.BooleanField(required=False)
>
>
> Some notes about this form and the derived formset:
>    - We do not have data in table "Erfasst" for every day in the month, e.g.
> Sundays or days in the future are usually not present, but the Formset is
> still expected to have forms with empty data for such days.
>    - We do not use a ModelForm, so that we can have additional form fields
> that have no correspondence in the model, such as "Speichern" above.
>
> At  I've uploaded a
> screenshot of how the form renders, with default data for days in the
> future, and the "Save?" checkbox that the user can use to have his changes
> saved into the database or not.
> (The full, current source code of the view is at
> .)
>
>
> Now, here is the real question:
> How do I properly validate this formset?
> I want to consider (validate and save) only those forms in the format whose
> "Save?" checkbox is set.
>
> In order words, is this code good Django practice?
>
>    if request.method == 'POST':
>        ErfasseZeitenFormSet = ErfasseZeitenFormSetFactory(request.POST)
>
>        IsFormsetValid = True
>        for Form in 

clean method in a model

2010-11-08 Thread refreegrata
Hello list. I want to use the clean method in a model.
--
class myModel(models.Model):
fields 

def clean(self):
raise ValidationError('The Error.')
---

Thats works fine. My question  is, how can I associate this error to
the field in the modelform?. With this method the form validation can
be controlled, but I can't pick the error dynamically to show at the
user.

Thanks for read.

-- 
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.



Exclude form field when calling form from view

2010-11-08 Thread Ed
I have an image upload form that takes a title and a file for its
field. I have two uses for it. Most of the time I call it, I need both
a title and the image itself. But when I call it simply to grab a
thumbnail, I don't need the title. In fact, the form data is saved to
a different model that doesn't even have title as a field.

I wanted to suppress the "title" field when I call the form. I could
have created two form classes in my forms.py, but this seemed
unnecessarily repetitious.

I included the following in my image form class:

def __init__ (self, show_title=True):
super (BaseClass, self).__init__()
if not show_title:
del self.fields['title']

This works great except for one thing. Now I'm getting validation
errors: "This field is required" whether I suppress the title field or
not. Any time I try to submit the form, it tells me I need to enter
data.  Any advice on how to do this correctly?

class UploadFileForm(forms.Form):
def __init__ (self, show_title=True):
super (BaseClass, self).__init__()
if not show_title:
del self.fields['title']

title = forms.CharField(max_length=50)
file = forms.ImageField(label='Select photo to upload')

-- 
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.



Validator for \t

2010-11-08 Thread Ralf
Hi,

my users put values like 'Paul\t\t' per copy and paste into html-
formfields and suceeded, the values ended up in the database.
I wonder whether there is no build-in-validator to prevent these kind
of invalid input.

Is there a cheap way to validate or strip these kind of input?

-- 
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 Sprint this Saturday!

2010-11-08 Thread Iván Raskovsky
Hello everyone! Here in Argentina we're planning a Sprint[1] this
Saturday to help with Django 1.3
We are going to participate from more than 4 Argentinian locations.
We are very proud to count with Ramiro (cramm) one of the recently
designated core commiters!

There will be also, another Sprint in Berlin going on this Saturday[2].

See you then!

[1] http://code.djangoproject.com/wiki/Sprint201011Argentina
[2] http://code.djangoproject.com/wiki/Sprints

-- 
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.



Obtaining And Caching User Context

2010-11-08 Thread octopusgrabbus
I am able to log into my form page, which is a simple form asking the
user for one value. If that value is entered successfully, I am able
to redirect to another "you were successful" page. However, my
template logic that checks to see if the user is authenticated -- as
far as I can tell the user is logged using Django's admin resources --
says the user is not authenticated.

How is a user's being authenticated cached, so another html template
knows that fact?

-- 
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.



Custom formset validation: having a "save?" checkbox for each form

2010-11-08 Thread Carsten Fuchs

Hi all,

my name is Carsten Fuchs, and this is my first post here. I'm normally a 
C++ developer for Windows and Linux desktop and server applications, and 
have begun my first (big) database-web project in mid summer. Let me 
start with saying that Django is utterly awesome: I've been able to 
complete a very large part of this project in very short time, reading 
the excellent Django online documentation and the Django online book. A 
huge thanks to everyone who is involved!


My Django application is for recording and managing the work hours of 
the staff of a company with about 1000 employees, implemented on Ubuntu 
10.04 with Django 1.2, Python 2.6, Apache2 as webserver, and an Oracle 
10g database.


My question is about validating the formset that is used for editing the 
work hours (but I'm happy about all comments on whatever strikes you odd 
in the code below ;-) ).



The main model is (slightly simplified for clarity):

# This model should really be named "Workday", not "Erfasst".
class Erfasst(models.Model):
key= models.ForeignKey(Mitarbeiter, db_column='key', 
to_field='key')

datum  = models.DateField()
anfang = models.TimeField()   # Begin of work.
ende   = models.TimeField()   # End of work.
pause  = models.CharField(max_length=8, blank=True) # (Need a 
timedelta field...)



I wrote a view with a formset for editing the work hours in the above 
model of an entire week or month. The form is:


class ErfasseZeitForm(forms.Form):
# ID of "Erfasst" entry, if present in database.
ErfasstID = forms.IntegerField(required=False, 
widget=forms.HiddenInput())


# We must pass the date for days that are not yet mentioned in the 
database.

Datum = forms.DateField(widget=forms.HiddenInput())

# Begin, end, and pause of work.
Anfang= forms.TimeField(required=False)
Ende  = forms.TimeField(required=False)
Pause = forms.TimeField(required=False)

# A checkbox for "Save this form?" (which is part of a formset that 
covers an entire month)

Speichern = forms.BooleanField(required=False)


Some notes about this form and the derived formset:
- We do not have data in table "Erfasst" for every day in the 
month, e.g. Sundays or days in the future are usually not present, but 
the Formset is still expected to have forms with empty data for such days.
- We do not use a ModelForm, so that we can have additional form 
fields that have no correspondence in the model, such as "Speichern" above.


At  I've uploaded a 
screenshot of how the form renders, with default data for days in the 
future, and the "Save?" checkbox that the user can use to have his 
changes saved into the database or not.
(The full, current source code of the view is at 
.)



Now, here is the real question:
How do I properly validate this formset?
I want to consider (validate and save) only those forms in the format 
whose "Save?" checkbox is set.


In order words, is this code good Django practice?

if request.method == 'POST':
ErfasseZeitenFormSet = ErfasseZeitenFormSetFactory(request.POST)

IsFormsetValid = True
for Form in ErfasseZeitenFormSet.forms:
# Why does the call to clean() raise "'BoundField' object 
has no attribute 'clean'"?

# Principally, is this right? good practice?
if Form['Speichern'].clean() and not Form.is_valid():
IsFormsetValid = False

if IsFormsetValid:
for Form in ErfasseZeitenFormSet.forms:
if Form['Speichern'].cleaned_data:
# TODO: Process the record specified in 
Form.cleaned_data

pass

# Redirect after POST, so that the request isn't repeated 
when the user hits "Refresh".

return HttpResponseRedirect('/lori/arbeitszeiten/%s/' % MA.key)

else:
# ...


While writing this mail I found that the above code doesn't even work, 
because "'BoundField' object has no attribute 'clean'". How do I do this 
properly?


I'd be very happy and grateful for any related feed-back and advice.

Thank you very much, and best regards,
Carsten



--
   Cafu - the open-source Game and Graphics Engine
for multiplayer, cross-platform, real-time 3D Action
  Learn more at http://www.cafu.de

--
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.



Enclosing intervals with dates on django

2010-11-08 Thread Rogério Carrasqueira
Hello Everybody!

I'm developing a routine that will control the information about scheduled
events and it will avoid that some events override others and prevent that
it cannot happen. I made a query on mysql where that works fine and gives
the results that I need. For example I have an event that begins at 05
november and ends at 22 november, it must lock the agenda to prevent another
event in this date range, so if I try to insert a new event that will hapens
on 09 november and ends at 14 november, the system will return a message
reporting that this operation cannot be done due the collision with another
event previously scheduled.

My goal is translate this query to ORM Django: select * from my_table  where
('2010-11-09' between start_date AND ends_date) or ('2010-11-14' between
start_date AND ends_date )

I've tried with range atribute but I was'n happy on this way

Someone can help?

Thanks so much!

Rogério Carrasqueira

---
e-mail: rogerio.carrasque...@gmail.com
skype: rgcarrasqueira
MSN: rcarrasque...@hotmail.com
ICQ: 50525616
Tel.: (11) 7805-0074

-- 
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 override handle_uncaught_exception ?

2010-11-08 Thread Phlip
On Nov 8, 8:12 am, Phlip  wrote:

> I just need the usual features - to log the actual error, and stick it
> in the programmer's face during a test run.
>
> But when I Google for this subject, I get ten thousand newbies asking
> why they got some other error, and self.handle_uncaught_exception
> appears in their stack trace!

If nobody turns up a nice high-level way (besides overriding
django.contrib.messages.middleware.MessageMiddleware and sticking the
resulting class back into MIDDLEWARE_CLASSES), this settings.py option
simply lets the errors fly:

  DEBUG_PROPAGATE_EXCEPTIONS = True

> --
>   Phlip
>  http://bit.ly/ZeekLand

-- 
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 override handle_uncaught_exception ?

2010-11-08 Thread Phlip
I just need the usual features - to log the actual error, and stick it
in the programmer's face during a test run.

But when I Google for this subject, I get ten thousand newbies asking
why they got some other error, and self.handle_uncaught_exception
appears in their stack trace!

--
  Phlip
  http://bit.ly/ZeekLand

-- 
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: Can extra() be used to implement JOIN?

2010-11-08 Thread Daniel Roseman
On Nov 8, 3:40 pm, Andy  wrote:
> I have a Q type of site with the following models:
>
> class Question(models.Model):
>     title = models.CharField(max_length=70)
>     details = models.TextField()
>
> class Answer(models.Model):
>     question_id = IntegerField()
>     details = models.TextField()
>
> I need to display a specific question together with its answers.
> Normally I'd need 2 queries to do that:
>
> Question.objects.get(id=1)
> Answer.objects.get(question_id=1)[:10]
>
> I'm hoping to retrieve everything using one query. In MySQL it'd be:
>
> SELECT *
> FROM Question JOIN Answer ON Question.id=Answer.question_id
> WHERE Question.id=1
> LIMIT 10
>
> Is there anyway I could do this through Django's ORM?
> Would extra() help in this case?

This is exactly what `select_related()` does. The only gotcha is that
you have to start with the Answer model, rather than Question, but the
result is the same:

answers = Answer.objects.filter(question_id=1).select_related()

Now each answer object has a pre-fetched 'question' attribute, and
accessing it won't hit the db again.
--
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.



Can extra() be used to implement JOIN?

2010-11-08 Thread Andy
I have a Q type of site with the following models:

class Question(models.Model):
title = models.CharField(max_length=70)
details = models.TextField()

class Answer(models.Model):
question_id = IntegerField()
details = models.TextField()

I need to display a specific question together with its answers.
Normally I'd need 2 queries to do that:

Question.objects.get(id=1)
Answer.objects.get(question_id=1)[:10]

I'm hoping to retrieve everything using one query. In MySQL it'd be:

SELECT *
FROM Question JOIN Answer ON Question.id=Answer.question_id
WHERE Question.id=1
LIMIT 10

Is there anyway I could do this through Django's ORM?
Would extra() help in this case?

-- 
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: Making a m2m field required

2010-11-08 Thread Yo'av Moshe
O thank you! I didn't know about self.data! That's exactly what I
was looking for.

It works now. Thanks!

Yo'av

On Nov 8, 4:22 pm, Martin Ostrovsky 
wrote:
> What about checking the raw POST for existence of data? So in your
> form, checking self.data.has_key('some_key')
>
> On Nov 8, 9:15 am, "Yo'av Moshe"  wrote:
>
>
>
> > Hey,
>
> > I tried this method with no success.
>
> > Adding .clean to my Article's ModelForm and checking it's
> > self.instance.tags.all(), gives me this ValueError:
> > 'Article' instance needs to have a primary key value before a many-to-
> > many relationship can be used.
>
> > Actually this seems right, since if my Article isn't even saved yet,
> > how can I check it's tags? They don't even exist AFAIK.
>
> > So I thought the way to go was by by checking the form it self. The
> > problem is that Article's ModelForm .clean_data doesn't include my
> > Tag's form, since it's included inline as a seperated form. If I try
> > to use .clean_data on Tag's inline ModelForm it actually works - I can
> > count and validate whatever the user wrote in the Tag's form - but
> > only if the user typed *something*, which is exactly what I'm trying
> > to validate. If the user didn't put anything in Tag's inline ModelForm
> > - .clean_data doesn't get called at all, and no validation is being
> > done.
>
> > I hope I was understood, it's a bit of a mess...
>
> > Is there anyway to go from here? Did I use .clean correctly?
>
> > Thank you for your kind help,
> > Yo'av
>
> > On Nov 7, 12:53 am, Shawn Milochik  wrote:
>
> > > Add a clean() method to your ModelForm, and raise a forms.ValidationError 
> > > if self.instance.whatever.all().count() == 0.
>
> > > Shawn

-- 
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: Making a m2m field required

2010-11-08 Thread Martin Ostrovsky
What about checking the raw POST for existence of data? So in your
form, checking self.data.has_key('some_key')

On Nov 8, 9:15 am, "Yo'av Moshe"  wrote:
> Hey,
>
> I tried this method with no success.
>
> Adding .clean to my Article's ModelForm and checking it's
> self.instance.tags.all(), gives me this ValueError:
> 'Article' instance needs to have a primary key value before a many-to-
> many relationship can be used.
>
> Actually this seems right, since if my Article isn't even saved yet,
> how can I check it's tags? They don't even exist AFAIK.
>
> So I thought the way to go was by by checking the form it self. The
> problem is that Article's ModelForm .clean_data doesn't include my
> Tag's form, since it's included inline as a seperated form. If I try
> to use .clean_data on Tag's inline ModelForm it actually works - I can
> count and validate whatever the user wrote in the Tag's form - but
> only if the user typed *something*, which is exactly what I'm trying
> to validate. If the user didn't put anything in Tag's inline ModelForm
> - .clean_data doesn't get called at all, and no validation is being
> done.
>
> I hope I was understood, it's a bit of a mess...
>
> Is there anyway to go from here? Did I use .clean correctly?
>
> Thank you for your kind help,
> Yo'av
>
> On Nov 7, 12:53 am, Shawn Milochik  wrote:
>
>
>
>
>
>
>
> > Add a clean() method to your ModelForm, and raise a forms.ValidationError 
> > if self.instance.whatever.all().count() == 0.
>
> > Shawn

-- 
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: Making a m2m field required

2010-11-08 Thread Yo'av Moshe
Hey,

I tried this method with no success.

Adding .clean to my Article's ModelForm and checking it's
self.instance.tags.all(), gives me this ValueError:
'Article' instance needs to have a primary key value before a many-to-
many relationship can be used.

Actually this seems right, since if my Article isn't even saved yet,
how can I check it's tags? They don't even exist AFAIK.

So I thought the way to go was by by checking the form it self. The
problem is that Article's ModelForm .clean_data doesn't include my
Tag's form, since it's included inline as a seperated form. If I try
to use .clean_data on Tag's inline ModelForm it actually works - I can
count and validate whatever the user wrote in the Tag's form - but
only if the user typed *something*, which is exactly what I'm trying
to validate. If the user didn't put anything in Tag's inline ModelForm
- .clean_data doesn't get called at all, and no validation is being
done.

I hope I was understood, it's a bit of a mess...

Is there anyway to go from here? Did I use .clean correctly?

Thank you for your kind help,
Yo'av

On Nov 7, 12:53 am, Shawn Milochik  wrote:
> Add a clean() method to your ModelForm, and raise a forms.ValidationError if 
> self.instance.whatever.all().count() == 0.
>
> Shawn

-- 
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.



Create a simple Editor with image support

2010-11-08 Thread Karim Gorjux
Hi all, I would like to create a "improved" flatpage application
adding a editor and the support of image files. My target is to edit a
static web page load images and see a preview. I can add easily a
editor like tinymce, I would try also FCKeditor, but what about the
handle of images? Could you show me a guide that explain how to handle
images from the editor and django?

Thanks

-- 
K.
Blog Personale: http://www.karimblog.net

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: grouping of fields inside a model into a class

2010-11-08 Thread nitm
thanks for the references, I missed that part.

it does look similar but not exactly what I had in mind...
what this means is that I can now have an abstract model which will be
a base model to all models who can have an address.  this abstract
model will define the different fields which makes an address, but
won't create a table for them.
now, every model who wants to have an address will extend that
abstract model and will automatically gain these fields.

the difference is that all of fields and methods (which will be
defined on those fields) will be part of the extending model instead
of it owning an address object holding the data/functionality.

I will give it a try though.  thanks again.

On Nov 8, 8:24 am, Jani Tiainen  wrote:
> On Friday 05 November 2010 22:53:06 nitm wrote:
>
>
>
>
>
> > Hi,
>
> > Is there a way to combine a set of fields I have in a model class into
> > a different class without it having it's own separate table?
> > An example:
>
> > I want to implement the user profile model class, and in it I would
> > like to have the address of the user.
> > The address is group of fields (city, street, number, zip code) and
> > so, instead of having this:
>
> > class UserProfile(models.Model):
> >     city = models.ForeignKey(City)
> >     street = models.CharField(max_length=200)
> >     number = models.IntegerField()
> >     zip = models.IntegerField()
>
> >     
>
> > I would like to do something similar to:
> > class Address:
> >     city = models.ForeignKey(City)
> >     street = models.CharField(max_length=200)
> >     number = models.IntegerField()
> >     zip = models.IntegerField()
>
> > class UserProfile(models.Model):
> >     address = ???
>
> >     
>
> > It just seems more comfortable if I can group these fields into one
> > class and add methods to it (for example different string
> > representations) but I would still like the actual fields to be part
> > of the user profile table and not a new table just for address (since
> > it's a one to one relationship).
>
> > Is something like that possible ?
> > Thanks.
>
> That can be achieved very easily by using abstract model(s) and inheritance.
> Though it's not that intuitive  but looks similiar. Also you need to be very
> careful about reverse relations.
>
> See more 
> at:http://docs.djangoproject.com/en/1.2/topics/db/models/#abstract-base-...
>
> http://docs.djangoproject.com/en/1.2/topics/db/models/#be-careful-with-
> related-name
>
> --
>
> Jani Tiainen

-- 
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: AuthProfile and querysets

2010-11-08 Thread tom
Hi,

I've solved the issue with these lines
 user_list = request.customer.siteuser_set.values_list('user', flat =
True)
 users = User.objects.in_bulk(list(user_list))
 TeamForm.base_fields['members'].queryset = users

best regards,
tom

On Nov 7, 12:40 am, tom  wrote:
> Hello,
>
> I try to get User objects from a SiteUser queryset. I have following
> models:
>
> class SiteUser(models.Model):
>     user = models.ForeignKey(User, unique = True)
>     company = models.ForeignKey(Company, db_index = True) # that is
> absolutely needed
>
> class Team(models.Model):
>     name = models.CharField(max_length = 500, db_index = True)
>     company = models.ForeignKey(Company, db_index = True, default = 1)
>     members = models.ManyToManyField(User, blank = True)
>
> This Model has a TeamForm
> class TeamForm(forms.ModelForm):
>     members = forms.ModelMultipleChoiceField(widget =
> forms.CheckboxSelectMultiple,
>                                              queryset =
> User.objects.all(),
>                                              required = False)
>     class Meta:
>         model = Team
>         fields = ('name', 'email', 'members')
>
> within a view I need to do this:
> project_members = request.customer.siteuser_set.filter(company =
> request.customer)
> TeamForm.base_fields['members'].queryset = project_members #<--- here
> is a problem, I need to have a query set holding User objects.
>
> Does someone know how i can have a User queryset instead of a SiteUser
> queryset?
>
> thanks, 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.