Re: redirect problems

2011-10-24 Thread nicolas HERSOG
God you'r right !

Thanks to your answer i found why my "named" url didn't work.

I wrote this in my urls.py :
(r'^article/(?P\d+)/$', myAppFront.views.article, name='article'),
instead of :
   *url*(r'^article/(?P\d+)/$', myAppFront.views.article,
name='article'),

AND, you'r right, i didn't use the name i defined (here 'article') in my
redirection.

Thx you Tom :)

On Mon, Oct 24, 2011 at 5:52 PM, Tom Evans  wrote:

> On Mon, Oct 24, 2011 at 12:34 PM, nicolas HERSOG 
> wrote:
> > Hi everyone,
> > I digged more but i'm still stuck.
> > I understood that i have to use namespaceURL.
> > So i modified my url.py this way :
> > from myAppFront.views import article
> > url (r'^article/(?P\d+)/$',
> > myAppFront.views.article,
> > name='article'),
>
> Note: this doesn't namespace it, it gives it the explicit name
> 'article'. If you gave it a name like 'myApp:article' it would be in
> the myApp namespace, or if the entire urlconf is included in the main
> urlconf with a namespace, but you don't mention doing that.
>
> > and this is my addComment view :
> > ...
> > #return HttpResponseRedirect(reverse('myAppFront.views.article',
> > args=(id,)))
> > return HttpResponseRedirect(reverse('myAppFront.views.article',
> > kwargs={'id': id}))
>
> Having named it, you can (and should) use the name when reversing the
> URL, not the view definition, eg:
>
>  return HttpResponseRedirect(reverse('article', args=(id,)))
>
> You could also use the dict syntax as well, I prefer the tuple version
> for simple single argument URLs like this.
>
> Hope that helps
>
> Cheers
>
> Tom
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@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-users@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: Field.Choices in Template

2011-10-24 Thread Kurtis
Thank you so much for this, Tom! I've asked this question quite a few
times in IRC and couldn't come across the answer I was looking for. I
figured it was possible, I just had no idea how to access it. Much
appreciation!

On Oct 24, 11:26 am, Tom Evans  wrote:
> On Thu, Oct 20, 2011 at 8:37 PM, Kurtis  wrote:
> > Hey,
>
> > I'm trying to build a custom template for my ModelForm. My ModelForm
> > contains several M2M fields. If I run the ModelForm.as_view and then
> > in my template print {{ form.as_p }} it'll automagically display those
> > choices.
>
> > Now what I want to do is take advantage of that magic and print out
> > those choices myself in my template. For example:
>
> > {% for choice in form.genres.choices %}
> >    {{ choice }}
> > {% endfor %}
>
> > ... but it doesn't work. it doesn't print anything. I tried reading
> > through the source code of the forms.py and fields.py from 1.3 but
> > didn't get very far.
>
> When you access a form field from a template, the field returned is a
> BoundField, not the field attribute from the form class. From the
> BoundField object, you can access the form field on the field
> attribute, eg:
>
> {% for choice in form.genres.field.choices %}
>    {{ choice }}
> {% endfor %}
>
> Cheers
>
> Tom

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



Inline element not working as expected.

2011-10-24 Thread jenia ivlev
In the admin I want to use inline elements. I want category to display
the items it is related to.

But I get this error:
Exception at /admin/store/category/7/
 has no ForeignKey to 

It's true, of-course, since I chose to use Category to point to the
items it has.
But, how can I get the admin to list in-line all the items that a
given Category has?
How can I get around this error?


CONTEXT:

class Category:
items=models.ManyToManyField(Item,through='Categoryhasitem')'

class Categoryhasitem(models.Model):
category = models.ForeignKey(Category, db_column='category')
item = models.ForeignKey(Item, db_column='item')

class Item(models.Model):
id = models.AutoField(primary_key=True)

This is my admin.py file.

class ItemInline(admin.TabularInline):
model=Item
class CategoryAdmin(admin.ModelAdmin):
inlines=[ItemInline,]
class ItemAdmin(admin.ModelAdmin):
pass
admin.site.register(Category, CategoryAdmin)
admin.site.register(Item, ItemAdmin)



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Models non-relational sources and multiple sources

2011-10-24 Thread dabent
I'm building a Django app that's becoming more complex and it's quite
apparent I'm going to need models whose source is not always a
relational database.  e.g.: thrift, json, text files in custom
formatted syntax.

Are there any standard approaches on how to handle this situation?  I
assume there are many Django apps out there that interface with APIs
to build views and take data from forms and save that data to non-
relational stores and I'd like to hear how others have approached this
problem.

Also, I'll likely need a model that may come from a db or one or
multiple apis.  Are there any patterns I can used to have these sorts
of models?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



OneToOneField causes NotFound exception?

2011-10-24 Thread Paolo
Hi,

It looks like if I'm using a OneToOne field (with blank=True etc set) and 
happen to try and access this field when it's Null (or None) then I get a 
NotFound exception?  

My expectation was it would return None of nothing was set, not raise an 
exception?

I could of course catch this exception each time, but I need to keep 
remembering which fields I've set as OneToOne and which are plan old 
ForeignKey!

Thanks,

Paul

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/wf7ZOZlnAc4J.
To post to this group, send email to django-users@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.



User data being exposed with mod_wsgi/apache

2011-10-24 Thread Jennifer Bell
On my site, some user data is automatically filled in to a form if a
user is logged in by accessing request.user in the view code.

On deployment, it seems that if *any* user is logged in, forms
requested via another browser will be filled in with their data.  The
data is not filled in if no user is logged in.

I'm mystified.  Where is this coming from?  I'm using django 1.3, and
caching is not enabled in my settings (though I have set
CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True just in case).

The WSGIDeamonProcess is set up like this:
WSGIDaemonProcess lalala user=lalala group=lalala threads=1
processes=3

Is this apache?  mod_wsgi?

Jennifer

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django as a Standalone Desktop Application

2011-10-24 Thread graeme
On Oct 24, 3:42 pm, Tom Evans  wrote:

> I have a number of non-web django processes, so I'm not against that
> in general. However, installing a full LAMP/WAMP stack, django and all

You do not necessarilly need a full lamp stack. Use Cherrpy (or
similar) and SQLite for example.

I can think of plenty of desktop apps that it would be nice to use as
a web app in a home or  small business environment.

> only will maintenance be disaster, but you have no data consistency -
> each user has their own stack, including DB. If you have each machine

Its useful in situations like this. One person has something on their
desktop. They realise it would be useful for others to be able to
share the data. You copy it to a small server (so its always on) and
everyone uses that. No inconsistency, and only one copy of the stack.

I found myself wishing to be able to do this (with Calibre ebook
mangement) just yesterday (it does have a web interface, but limited
to downloading only).

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django as a Standalone Desktop Application

2011-10-24 Thread Alex Mandel
On 10/24/2011 03:42 AM, Tom Evans wrote:
> On Sun, Oct 23, 2011 at 2:32 AM, Alex Mandel  
> wrote:
>> Also the best part of this design is that you can turn it into a web app
>> at any time by simply opening a port on a machine to allow others to
>> connect.
>>
> 
> Is that supposed to be a plus? Sounds like a nightmare.
> 
> The smart way to do this is to build a simple wxpython application
> that consumes django web services to CRUD data. You can build your
> reporting tools using django, use the built-in admin, etc, whilst
> exposing only the minimum of web services to allow your app to enter
> information into the system.
> 
> I have a number of non-web django processes, so I'm not against that
> in general. However, installing a full LAMP/WAMP stack, django and all
> required packages onto a single users machine, and have them enter
> data via their browser to their personal django instance is crazy. Not
> only will maintenance be disaster, but you have no data consistency -
> each user has their own stack, including DB. If you have each machine
> connecting to a shared database, well that is even worse, as each user
> would be able to discern credentials which they can use to access the
> DB and meddle directly.
> 
> Cheers
> 
> Tom
> 

In my world the paradigm this replaces is MS Access, which is commonly
used in many government agencies and businesses. My point about doing it
with Django on sqlite using the built in Django server (not apache or a
real server db) is that you build it once and it can scale.

Yes a full web application would actually be the preferred end goal, and
such a desktop deployment could be upscaled to be a server deploy with
very little modification to the Django part.

If you spend a lot of time making a Wx or Qt then want to make it web,
you have write a separate web app and connect via CRUD as you implied.
Basically if I have time to make a great UI and the app doesn't have to
be offline I'll be looking at AJAX stuff in the browser rather than Wx
or Qt because a shared network db might as well run via the browser and
get out of platform dependencies.

Yes, I've built both Wx and Qt apps and found maintenance and
scalability to be a problem for this type of use case.

Thanks,
Alex

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Problem with saving many to many relationships

2011-10-24 Thread basd basd
I'm trying to set up a many to many relationship, but when I save the model
I get "TypeError: 'layer_set' is an invalid keyword argument for this
function".

In class Experiment(Job) I declare the model with:

   layer_set = models.ManyToManyField(LayerSet, blank=True, default =
"default layer")

In class ExperimentForm(forms.Form) I assign input with:

   layer_set =
forms.ModelMultipleChoiceField(queryset=LayerSet.objects.all(),
widget=forms.CheckboxSelectMultiple, required = False)

In my views.py:

   if request.method == "POST":
   form = ExperimentForm(request.POST, request.FILES)

   if form.is_valid():
   experiment = Experiment(**form.cleaned_data)
   experiment.owner = request.user
   experiment.save()

The problem is occurring in experiment = Experiment(**form.cleaned_data).
The constructor for this is:

   def __init__(self, *args, **kwargs):
   kwargs = _append_type(kwargs)
   super(Experiment, self).__init__(*args, **kwargs)

I believe the problem lies in super() trying to find a layer_set in
Experiment, which doesn't exist since layer_set needs to be a 2nd table that
points to Experiment and LayerSet. So far my best guess is that in views.py
I need to add something like:

   if form.is_valid():
   temp_layer_set = form.cleaned_data['layer_set']<-
   del form.cleaned_data['layer_set']
<-
   experiment = Experiment(**form.cleaned_data)
   experiment.owner = request.user
   experiment.save()
   (something to save temp_layer_set to its own table)   <-

But at this point I have no idea how to actually save the temp_layer_set. It
doesn't have its own class or anything so I can't call
experiment_layer_set.save().

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to make a foreign key field of type other than int?

2011-10-24 Thread Carl Meyer
Hi,

On Oct 24, 10:53 am, Kayode Odeyemi  wrote:
> I'm sorry but it doesn't just seem to work for me. I have tried
>
> possibilities like:
>
> self.fields['branch_name'].choices =
> Branch.objects.all().values('name_branch', 'name_branch')
> self.fields['branch_name'].choices =
> Branch.objects.all().values('name_branch')

I don't think you've read Tom's responses carefully. You're still
trying to use ".values()" here, resulting in a ValuesQuerySet which
returns dictionaries instead of a regular QuerySet which returns model
objects. That simply won't ever work. And that is the reason for the
"need more than one value to unpack" error; it has to do with the
format of the results returned, nothing to do with how many results
are returned by the query.

Carl

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to make a foreign key field of type other than int?

2011-10-24 Thread Kayode Odeyemi
On Mon, Oct 24, 2011 at 4:34 PM, Tom Evans  wrote:

> On Mon, Oct 24, 2011 at 4:21 PM, Kayode Odeyemi  wrote:
> > On Mon, Oct 24, 2011 at 2:57 PM, Tom Evans 
> wrote:
> >>
> >> On Mon, Oct 24, 2011 at 11:14 AM, Kayode Odeyemi 
> >> wrote:
> >> > Hello all,
> >> >
> >> > class BranchModelChoiceField(ModelChoiceField):
> >> > def label_from_instance(self, obj):
> >> > return obj
> >> >
> >> > class TransactionUpdateForm(forms.ModelForm):
> >> > branchqs = Branch.objects.values_list(u'name_branch', flat=True) #
> >> > use
> >> > flat=True if values_list is called with a single field
> >> > branch_name = BranchModelChoiceField(branchqs)
> >> > class Meta:
> >> > model = Transaction
> >> > fields = ('teller_no', 'paid')
> >>
> >>
> >> Two things here. ModelChoiceField wants a real queryset, not a
> >> ValuesQuerySet. The values of the model choice field should be the
> >> primary keys of the model being chosen, which is not the case here
> >> (which is why it fails).
> >>
> >> The second thing is that queryset is evaluated precisely once, when
> >> the form is instantiated for the first time. When you add a branch, it
> >> will not appear in that form until the server is restarted.
> >>
> >> Judging from your other reply, you don't actually want a foreign key
> >> link to the branch, you simply want to store the name of the branch on
> >> the transaction? If so, you should simply declare a ChoiceField and
> >> supply it with choices derived from Branch.
> >>
> >> Eg:
> >>
> >> class TransactionUpdateForm(forms.ModelForm):
> >>  branch_name = ChoiceField(required=True)
> >>  def __init__(self, *args, **kwargs):
> >>super(TransactionUpdateForm, self).__init__(*args, **kwargs)
> >>self.fields['branch_name'].choices =
> >> Branch.objects.all().values('name_branch', 'name_branch')
> >>
> > Thanks for writing in Tom.
> >
> > I think what you did is the same as:
> >
> > class TransactionUpdateForm(forms.ModelForm):
> > branchqs = Branch.objects.values_list('bid', u'name_branch')
> > branch_name = BranchModelChoiceField(branchqs)
>
> No! It really isn't.
>
> 1) In my one the queryset is created inside the form's __init__
> method, so it gets executed correctly every time the form is
> instantiated. In yours, the queryset is only evaluated once, so has
> incorrect values as soon as a branch is added or deleted.
> 2) If you are using a ModelChoiceField, give it a QuerySet, not a
> ValuesListQuerySet - really! This is why you get your unpacking
> errors. However, don't you want to store the name of the branch on the
> transaction, not the id of the branch? If so, you want a Choice field,
> since you are not linking to another object, just denormalizing some
> data from it into the Transaction model.
>
> >
> > I did try this earlier as well but didn't go to far with it.
> >
> > But then in the template file, I have {{form.branch_name}} which results
> > into "Need more than 1 value to unpack error". How am I expected to print
> > the form
> > widget (select field) in a template?
> >
>
> Assuming you don't give a ModelChoiceField an incorrect value for it's
> queryset, it is just this:
>
> {{ form.name_of_field }}
>
> I'm sorry but it doesn't just seem to work for me. I have tried
possibilities like:

self.fields['branch_name'].choices =
Branch.objects.all().values('name_branch', 'name_branch')
self.fields['branch_name'].choices =
Branch.objects.all().values('name_branch')

in template

{{form.branch_name}}

and


  {% for choice in form.branch_name.field.choices %}
 {% choice.name_branch %}
  {% choice.name_branch %}
  {% endfor %}
  

Both reporting "Need more than 1 value to unpack error". Does this have
anything to do with if perhaps the branch_name db field contains NULL.
>From the interactive shell, I get more that 1 result.

Thanks



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: redirect problems

2011-10-24 Thread Tom Evans
On Mon, Oct 24, 2011 at 12:34 PM, nicolas HERSOG  wrote:
> Hi everyone,
> I digged more but i'm still stuck.
> I understood that i have to use namespaceURL.
> So i modified my url.py this way :
> from myAppFront.views import article
>     url (r'^article/(?P\d+)/$',
>         myAppFront.views.article,
>         name='article'),

Note: this doesn't namespace it, it gives it the explicit name
'article'. If you gave it a name like 'myApp:article' it would be in
the myApp namespace, or if the entire urlconf is included in the main
urlconf with a namespace, but you don't mention doing that.

> and this is my addComment view :
> ...
>     #return HttpResponseRedirect(reverse('myAppFront.views.article',
> args=(id,)))
>     return HttpResponseRedirect(reverse('myAppFront.views.article',
> kwargs={'id': id}))

Having named it, you can (and should) use the name when reversing the
URL, not the view definition, eg:

  return HttpResponseRedirect(reverse('article', args=(id,)))

You could also use the dict syntax as well, I prefer the tuple version
for simple single argument URLs like this.

Hope that helps

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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 make a foreign key field of type other than int?

2011-10-24 Thread Tom Evans
On Mon, Oct 24, 2011 at 4:21 PM, Kayode Odeyemi  wrote:
> On Mon, Oct 24, 2011 at 2:57 PM, Tom Evans  wrote:
>>
>> On Mon, Oct 24, 2011 at 11:14 AM, Kayode Odeyemi 
>> wrote:
>> > Hello all,
>> >
>> > class BranchModelChoiceField(ModelChoiceField):
>> >     def label_from_instance(self, obj):
>> >     return obj
>> >
>> > class TransactionUpdateForm(forms.ModelForm):
>> >     branchqs = Branch.objects.values_list(u'name_branch', flat=True) #
>> > use
>> > flat=True if values_list is called with a single field
>> >     branch_name = BranchModelChoiceField(branchqs)
>> >     class Meta:
>> >     model = Transaction
>> >     fields = ('teller_no', 'paid')
>>
>>
>> Two things here. ModelChoiceField wants a real queryset, not a
>> ValuesQuerySet. The values of the model choice field should be the
>> primary keys of the model being chosen, which is not the case here
>> (which is why it fails).
>>
>> The second thing is that queryset is evaluated precisely once, when
>> the form is instantiated for the first time. When you add a branch, it
>> will not appear in that form until the server is restarted.
>>
>> Judging from your other reply, you don't actually want a foreign key
>> link to the branch, you simply want to store the name of the branch on
>> the transaction? If so, you should simply declare a ChoiceField and
>> supply it with choices derived from Branch.
>>
>> Eg:
>>
>> class TransactionUpdateForm(forms.ModelForm):
>>  branch_name = ChoiceField(required=True)
>>  def __init__(self, *args, **kwargs):
>>    super(TransactionUpdateForm, self).__init__(*args, **kwargs)
>>    self.fields['branch_name'].choices =
>> Branch.objects.all().values('name_branch', 'name_branch')
>>
> Thanks for writing in Tom.
>
> I think what you did is the same as:
>
> class TransactionUpdateForm(forms.ModelForm):
>     branchqs = Branch.objects.values_list('bid', u'name_branch')
>     branch_name = BranchModelChoiceField(branchqs)

No! It really isn't.

1) In my one the queryset is created inside the form's __init__
method, so it gets executed correctly every time the form is
instantiated. In yours, the queryset is only evaluated once, so has
incorrect values as soon as a branch is added or deleted.
2) If you are using a ModelChoiceField, give it a QuerySet, not a
ValuesListQuerySet - really! This is why you get your unpacking
errors. However, don't you want to store the name of the branch on the
transaction, not the id of the branch? If so, you want a Choice field,
since you are not linking to another object, just denormalizing some
data from it into the Transaction model.

>
> I did try this earlier as well but didn't go to far with it.
>
> But then in the template file, I have {{form.branch_name}} which results
> into "Need more than 1 value to unpack error". How am I expected to print
> the form
> widget (select field) in a template?
>

Assuming you don't give a ModelChoiceField an incorrect value for it's
queryset, it is just this:

{{ form.name_of_field }}


Cheers

Tom

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



Fixed fields in forms

2011-10-24 Thread Torsten Bronger
Hallöchen!

I have some fields in a model form that the user is not allowed to
change.  The set of fields must be determined at runtime because it
depends on the permissions of the current user.

Thus, I have defined a self.fixed_fields in my form's constructor
which is a set of str.  It contains the fixed fields' names.  Then I
can say at the end of the constructor:

for field_name in self.fixed_fields:
self.fields[field_name].widget.attrs["disabled"] = "disabled"
self.fields[field_name].required = False

And a clean method says:

def clean_my_field(self):
if "my_field" in self.fixed_fields:
return self.task.my_field
return self.cleaned_data["my_field"]

>From security's point of view, this is sufficient.  However, if the
validation fails and the form has to be re-dislayed, the disabled
fields are empty -- because they were not in request.POST.  While
still not problematic per se, this is confusing for the user.

I can solve it by making the "data" parameter a *mutable* QueryDict
and inject the missing values, basing on "instance" or "initial" --
whatever is available.  However, here this is getting really
cumbersome and error-prone.

Is there an easier way?

Tschö,
Torsten.

-- 
Torsten BrongerJabber 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-users@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: Field.Choices in Template

2011-10-24 Thread Tom Evans
On Thu, Oct 20, 2011 at 8:37 PM, Kurtis  wrote:
> Hey,
>
> I'm trying to build a custom template for my ModelForm. My ModelForm
> contains several M2M fields. If I run the ModelForm.as_view and then
> in my template print {{ form.as_p }} it'll automagically display those
> choices.
>
> Now what I want to do is take advantage of that magic and print out
> those choices myself in my template. For example:
>
> {% for choice in form.genres.choices %}
>    {{ choice }}
> {% endfor %}
>
> ... but it doesn't work. it doesn't print anything. I tried reading
> through the source code of the forms.py and fields.py from 1.3 but
> didn't get very far.
>

When you access a form field from a template, the field returned is a
BoundField, not the field attribute from the form class. From the
BoundField object, you can access the form field on the field
attribute, eg:

{% for choice in form.genres.field.choices %}
   {{ choice }}
{% endfor %}

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Problem with GaoDjango models

2011-10-24 Thread Odagi
Hello all. I'm playing with geodjango and have some
doubts. I'll really appreciate any comment and suggestion.
This is my problem. First, I've defined this (abstract) class:


from django.contrib.gis.db import models
from django.contrib.gis.geos import *

class LocatableModel(models.Model):
country = models.CharField(max_length=48, blank=True)
country_code = models.CharField(max_length=2, blank=True)
locality = models.CharField(max_length=48, blank=True)
sub_locality = models.CharField(max_length=48, blank=True)
street = models.CharField(max_length=48, blank=True)
address = models.CharField(max_length=120, blank=True)
point = models.PointField(null=True)
objects = models.GeoManager()

class Meta:
abstract = True



Second, I've defined this other 'Entity' class, which
represents a person or organization related to my site:


from django.db import models

class Entity(models.Model):
name = models.CharField(_("name"), max_length=64)
slug = models.SlugField(_("slug"), max_length=64, unique=True)
website = models.URLField(_("website"), verify_exists=False,
blank=True)
email = models.EmailField(_("email"), blank=True)
... (etc)

Finally, I've created a class from the previous ones:

import LocatableModel
import Entity

class Organization(Entity, LocatableModel):
timetable = models.CharField(max_length=64)
... (etc)

Now, In my views, I'd like to find organizations
near a specific point:

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D

def index(request):
"""
General view for listing organization.
"""
pnt = Point(12.4604, 43.9420)
dic = { 'orgs':
Organization.objects.filter(point__distance__lte=(pnt, D(km=7))) }
return render_to_response('index.html', dic)

But I receive the error:
"Join on field 'point' not permitted. Did you misspell 'distance' for
the lookup type?"


I think I'm doing a mess with the model 'objects' property,
but I'm not sure. Any ideas?

Thanks in advance





-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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 make a foreign key field of type other than int?

2011-10-24 Thread Kayode Odeyemi
On Mon, Oct 24, 2011 at 2:57 PM, Tom Evans  wrote:

> On Mon, Oct 24, 2011 at 11:14 AM, Kayode Odeyemi 
> wrote:
> > Hello all,
> >
> > class BranchModelChoiceField(ModelChoiceField):
> > def label_from_instance(self, obj):
> > return obj
> >
> > class TransactionUpdateForm(forms.ModelForm):
> > branchqs = Branch.objects.values_list(u'name_branch', flat=True) #
> use
> > flat=True if values_list is called with a single field
> > branch_name = BranchModelChoiceField(branchqs)
> > class Meta:
> > model = Transaction
> > fields = ('teller_no', 'paid')
>
>
> Two things here. ModelChoiceField wants a real queryset, not a
> ValuesQuerySet. The values of the model choice field should be the
> primary keys of the model being chosen, which is not the case here
> (which is why it fails).
>
> The second thing is that queryset is evaluated precisely once, when
> the form is instantiated for the first time. When you add a branch, it
> will not appear in that form until the server is restarted.
>
> Judging from your other reply, you don't actually want a foreign key
> link to the branch, you simply want to store the name of the branch on
> the transaction? If so, you should simply declare a ChoiceField and
> supply it with choices derived from Branch.
>
> Eg:
>
> class TransactionUpdateForm(forms.ModelForm):
>  branch_name = ChoiceField(required=True)
>  def __init__(self, *args, **kwargs):
>super(TransactionUpdateForm, self).__init__(*args, **kwargs)
>self.fields['branch_name'].choices =
> Branch.objects.all().values('name_branch', 'name_branch')
>
> Thanks for writing in Tom.

I think what you did is the same as:

class TransactionUpdateForm(forms.ModelForm):
branchqs = Branch.objects.values_list('bid', u'name_branch')
branch_name = BranchModelChoiceField(branchqs)

I did try this earlier as well but didn't go to far with it.

But then in the template file, I have {{form.branch_name}} which results
into "Need more than 1 value to unpack error". How am I expected to print
the form
widget (select field) in a template?

 --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>


-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: VirtualHost/Cache

2011-10-24 Thread Didex
Okay,

I will change the ServerName, but my version of Django is 1.2.5.

Thank you.



On 24 Out, 15:14, Tom Evans  wrote:
> On Fri, Oct 21, 2011 at 10:57 AM, Didex  wrote:
> > Hello everyone,
>
> > I am trying setup a webserver(Centos) with two django sites, but i am
> > havecacheproblems.
>
> > http.config:
>
> > NameVirtualHost *:80
> > WSGIPythonEggs /usr/local/django/eggs
> > WSGIPythonPath /usr/local/django:/usr/local/django/site1:/usr/local/
> > django/site2
>
> > site1.config:
>
> > 
> >        ServerAdmin  "my-e-m...@mail.com"
> >        ServerName site.com
> >        ServerAliaswww.site.com
> >        DocumentRoot /usr/local/django/site1
> >        Alias /media/ /usr/local/django/site1/media/
> >        WSGIScriptAlias / /usr/local/django/site1/site1.wsgi
> > 
>
> > site1.config:
>
> > 
> >        ServerAdmin  "my-e-m...@mail.com"
> >        ServerName site.com
> >        ServerAlias sub.site.com
> >        DocumentRoot /usr/local/django/site2
> >        Alias /media/ /usr/local/django/site2/media/
> >        WSGIScriptAlias / /usr/local/django/site2/site2.wsgi
> > 
>
> > bind(e.g.):
>
> > site.com.       IN      A       192.168.1.2 #e.g.
> > sub.site.com.   IN      A       192.168.1.2 #e.g.
>
> > in the wsgi file i have (x=site1, x=site2):
>
> > import os
> > import sys
>
> > os.environ['DJANGO_SETTINGS_MODULE'] = 'x.settings'
>
> > import django.core.handlers.wsgi
> > application = django.core.handlers.wsgi.WSGIHandler()
>
> > Django settings file:
>
> > site1:
> > CACHE_BACKEND = "locmem:///"
> > CACHE_TIMEOUT = 60*5
> > CACHE_PREFIX = "site:1"
>
> > CACHE_BACKEND = "dummy:///"
> > CACHE_TIMEOUT = 60*5
> > CACHE_PREFIX = "site:2"
>
> > but this is not working.
> > I access the site1 and site2 also changes.
>
> > could anyone tell me what am I doing wrong?
> > Thank you.
>
> Are you sure you are hitting the second vhost? It is incorrect to have
> "ServerName site.com" in both vhosts…
>
> Check by enabling different access logs in each vhost, and see which
> site is logged.
>
> One other possible thing to check is that in 1.3,cachesettings come
> from the settings.CACHES dict, not settings.CACHE_* settings.
>
> Cheers
>
> Tom

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

2011-10-24 Thread Sid
It would help us in answering your question, if you would explain what all 
you tried + what error you're getting.

I've used social-auth a number of times, it was a breeze to setup. The only 
frictional part was in custom settings, domain(callback url) white-listing 
that needed to happen on some backends like google.
-Sid

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/nT7NGnu0EC8J.
To post to this group, send email to django-users@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: VirtualHost/Cache

2011-10-24 Thread Tom Evans
On Fri, Oct 21, 2011 at 10:57 AM, Didex  wrote:
> Hello everyone,
>
> I am trying setup a webserver(Centos) with two django sites, but i am
> have cache problems.
>
>
> http.config:
>
> NameVirtualHost *:80
> WSGIPythonEggs /usr/local/django/eggs
> WSGIPythonPath /usr/local/django:/usr/local/django/site1:/usr/local/
> django/site2
>
>
> site1.config:
>
> 
>        ServerAdmin  "my-e-m...@mail.com"
>        ServerName site.com
>        ServerAlias www.site.com
>        DocumentRoot /usr/local/django/site1
>        Alias /media/ /usr/local/django/site1/media/
>        WSGIScriptAlias / /usr/local/django/site1/site1.wsgi
> 
>
>
> site1.config:
>
> 
>        ServerAdmin  "my-e-m...@mail.com"
>        ServerName site.com
>        ServerAlias sub.site.com
>        DocumentRoot /usr/local/django/site2
>        Alias /media/ /usr/local/django/site2/media/
>        WSGIScriptAlias / /usr/local/django/site2/site2.wsgi
> 
>
>
> bind(e.g.):
>
> site.com.       IN      A       192.168.1.2 #e.g.
> sub.site.com.   IN      A       192.168.1.2 #e.g.
>
>
> in the wsgi file i have (x=site1, x=site2):
>
> import os
> import sys
>
> os.environ['DJANGO_SETTINGS_MODULE'] = 'x.settings'
>
> import django.core.handlers.wsgi
> application = django.core.handlers.wsgi.WSGIHandler()
>
>
>
> Django settings file:
>
> site1:
> CACHE_BACKEND = "locmem:///"
> CACHE_TIMEOUT = 60*5
> CACHE_PREFIX = "site:1"
>
>
> CACHE_BACKEND = "dummy:///"
> CACHE_TIMEOUT = 60*5
> CACHE_PREFIX = "site:2"
>
>
> but this is not working.
> I access the site1 and site2 also changes.
>
> could anyone tell me what am I doing wrong?
> Thank you.
>

Are you sure you are hitting the second vhost? It is incorrect to have
"ServerName site.com" in both vhosts…

Check by enabling different access logs in each vhost, and see which
site is logged.

One other possible thing to check is that in 1.3, cache settings come
from the settings.CACHES dict, not settings.CACHE_* settings.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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: django, celery and rabbitmq. Task gets added twice

2011-10-24 Thread tom
problem has been solved.

Actually, the post_save signal was issued twice. This page helped me:
https://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwiceforeachsave


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/X17RMokBFbQJ.
To post to this group, send email to django-users@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: Iteration over queryset in a model

2011-10-24 Thread eyscooby
So with the items that are still waiting to be complete i wanted to
show how many days the ticket has been open by doing something
like ...

return date.today() - self.issued_date

and then those that are complete ...

return self.competion_date - self.issued_date

Can i create 2 managers for this?? one to return completed, and one to
return not completed??


On Oct 18, 12:04 pm, eyscooby  wrote:
> Ok, this is helping, believe it or not your are helping, I'm probably
> confusing myself mostly.
>
> So the model method explanation was very helpful and you are correct
> that works great, as long as all dates have a completion_date.  If a
> new ticket is entered it will fail due to a "NoneType field with
> DateField".
> That line in my model is as such  "completed_date =
> DateField(blank=True, null=True)".
>
> The Manager is doing nothing more than returning data from the
> database as a query so that makes sense also.
>
> Step two .. is it because of the NULL=True?  can't subtract date field
> from null field (which makes sense), is there a way around that?
> I think this is why i was trying to calculate on a specific filter.
>
> On Oct 18, 3:47 am, Daniel Roseman  wrote:
>
>
>
> > On Monday, 17 October 2011 20:28:47 UTC+1, eyscooby wrote:
>
> > > Ok, sorry I thought I was starting to understand it a little better,
> > > but now I think I took a step backwards, so if it is ok with you let's
> > > step back and take it a step at a time.
>
> > > So, my first step is wondering if I really need a manager or not??
> > > I was thinking from your first response to me that you might be
> > > suggesting that I did.  Let's start there.
> > > If I understand it correctly the Manager is a way of retrieving
> > > specific information.
>
> > > thanks
>
> > Sorry for confusing you. There are two things going on here.
>
> >  A Manager is for making custom queries to the database, to return new
> > objects - either one or aquerysetof many. Your original code was using
> > `Model.filter()` and modifying the result, so I suggested that it belonged
> > in a manager.
>
> > A model method is useful when you want to do a separate, non-database,
> > operation on a single object. That's what you really want to do here - given
> > an instance of RequestTicket, calculate how old it is. There's noiteration
> > contained in the method - you iterate through your existingqueryset
> > elsewhere (say in the template) and call days_old on each instance:
>
> >     {% for ticket in completed_tickets %}
> >        {{ ticket.name }}: {{ ticket.days_old }}
> >     {% endif %}
>
> > Or, in your particular circumstance, you simply give the `days_old` method
> > as one of the elements of the `list_display` tuple, and Django takes care of
> > the iterating, calling `days_old` on each row in the changelist.
>
> > So in both of these circumstances, `days_old` simply needs to look like
> > this:
>
> >     def days_old(self):
> >         return self.competion_date - self.issued_date
>
> > - so it returns a single value, for the one particular ticket instance which
> > it has been called on.
>
> > Hope that helps.
> > --
> > DR.- Hide quoted text -
>
> - Show quoted text -

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: sprintf in python (not strictly django, but used all the time in django webapps)

2011-10-24 Thread Cal Leeming [Simplicity Media Ltd]
You're correct :L

Thanks for this - I think I might replace my daily break with random Python
docs pages, rather than 'theregister' for a few weeks!

Cal

On Mon, Oct 24, 2011 at 3:09 PM, Tom Evans  wrote:

> On Thu, Oct 20, 2011 at 7:17 PM, Cal Leeming [Simplicity Media Ltd]
>  wrote:
> > So, just out of curiosity, how many other people didn't realise you
> > could do this:
> >
>  print '%(language)s has %(number)03d quote types.' % \
> > ...   {"language": "Python", "number": 2}
> >
> >
> > Instead of this:
> >
> > print "%s has %03d" % ( "python", "2" )
> >
> > 6 years of python development, and I never found this little beauty.
> Fail.
> >
> > Hope this helps someone else.
> >
> > Cal
> >
>
> Crikey, if you didn't know about that one, you probably don't know
> about this one either:
>
> >>> fmt = "{} shalt thou not count, neither count thou {}, excepting that
> thou then proceed to {}. {} is right out!"
> >>> fmt.format('four', 'two', 'three', 'five')
> 'four shalt thou not count, neither count thou two, excepting that
> thou then proceed to three. five is right out!'
>
>
> http://docs.python.org/library/string.html#format-string-syntax
>
> Cheers
>
> Tom
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@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-users@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: sprintf in python (not strictly django, but used all the time in django webapps)

2011-10-24 Thread Tom Evans
On Thu, Oct 20, 2011 at 7:17 PM, Cal Leeming [Simplicity Media Ltd]
 wrote:
> So, just out of curiosity, how many other people didn't realise you
> could do this:
>
 print '%(language)s has %(number)03d quote types.' % \
> ...       {"language": "Python", "number": 2}
>
>
> Instead of this:
>
> print "%s has %03d" % ( "python", "2" )
>
> 6 years of python development, and I never found this little beauty. Fail.
>
> Hope this helps someone else.
>
> Cal
>

Crikey, if you didn't know about that one, you probably don't know
about this one either:

>>> fmt = "{} shalt thou not count, neither count thou {}, excepting that thou 
>>> then proceed to {}. {} is right out!"
>>> fmt.format('four', 'two', 'three', 'five')
'four shalt thou not count, neither count thou two, excepting that
thou then proceed to three. five is right out!'


http://docs.python.org/library/string.html#format-string-syntax

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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 make a foreign key field of type other than int?

2011-10-24 Thread Tom Evans
On Mon, Oct 24, 2011 at 11:14 AM, Kayode Odeyemi  wrote:
> Hello all,
>
> class BranchModelChoiceField(ModelChoiceField):
>     def label_from_instance(self, obj):
>     return obj
>
> class TransactionUpdateForm(forms.ModelForm):
>     branchqs = Branch.objects.values_list(u'name_branch', flat=True) # use
> flat=True if values_list is called with a single field
>     branch_name = BranchModelChoiceField(branchqs)
>     class Meta:
>     model = Transaction
>     fields = ('teller_no', 'paid')


Two things here. ModelChoiceField wants a real queryset, not a
ValuesQuerySet. The values of the model choice field should be the
primary keys of the model being chosen, which is not the case here
(which is why it fails).

The second thing is that queryset is evaluated precisely once, when
the form is instantiated for the first time. When you add a branch, it
will not appear in that form until the server is restarted.

Judging from your other reply, you don't actually want a foreign key
link to the branch, you simply want to store the name of the branch on
the transaction? If so, you should simply declare a ChoiceField and
supply it with choices derived from Branch.

Eg:

class TransactionUpdateForm(forms.ModelForm):
  branch_name = ChoiceField(required=True)
  def __init__(self, *args, **kwargs):
super(TransactionUpdateForm, self).__init__(*args, **kwargs)
self.fields['branch_name'].choices =
Branch.objects.all().values('name_branch', 'name_branch')

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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: Setting default values in a form from DB table

2011-10-24 Thread Swaroop Shankar V
Thank a lot Andre, this is my first project in Django so kind of confused at
many parts. The links will help me to fix my issue.

Thanks and Regards,

Swaroop Shankar V



On Mon, Oct 24, 2011 at 6:03 PM, Andre Terra  wrote:

> You should always populate your form in forms.py. This is done using the
> 'initial' kwarg and is thoroughly explained in the docs! [1]
>
> Borrowing from the tutorial's Poll model [2]:
>
> Class PollsForm(forms.Form):
> def __init__ (self, *args, **kwargs):
> self.instance = kwargs.pop('instance', None)
>
> if self.instance.pk is not None:
> kwargs['initial'] = kwargs.get('initial', {})
> kwargs['initial'] = {'question': self.instance.question}
>
> super(PollsForm, self).__init__(*args, **kwargs)
>
> This way, you can edit a Poll object by calling
> PollsForm(instance=some_poll_object), and it will automatically populate
> 'question' with the instance's
> question attribute.
>
>
> Cheers,
> AT
>
> [1]
> https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
> [2]
> https://docs.djangoproject.com/en/dev/intro/tutorial01/#creating-models
>
>
>
>
> On Sun, Oct 23, 2011 at 4:08 PM, Swaroop Shankar V wrote:
>
>> Hello All,
>>
>> I am trying to create a Edit form to edit user information. I would like
>> to display the default values in the form fields rendered and am getting the
>> values from the db table. I can take an approach by creating a dictionary
>> with the values that needs to be populated in the form fields in my view
>> file and then pass it to the html. Then in the html, i can manually set the
>> values using the django-widget_tweaks. But the problem here is that there
>> are few select box for which this approach wont work. So the next option is
>> to do it from the forms.py but there i need to get the currently logged in
>> user and since request object is not available i created an __init__
>> function with the following statements
>>
>> def __init__(self, *args, **kwargs):
>> self.request = kwargs.pop('request', None)
>> super(UserEditForm, self).__init__(*args, **kwargs)
>>
>> but now i am not sure on how to set up the form values. My form's class
>> code can be accessed via the url http://pastebin.com/1TuRmNhH . Please
>> help.
>>
>> Thanks and Regards,
>> Swaroop Shankar V
>>
>>  --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@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-users@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-users@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 make a foreign key field of type other than int?

2011-10-24 Thread Kayode Odeyemi
On Mon, Oct 24, 2011 at 1:11 PM, Jani Tiainen  wrote:

> Hi,
>
> It really depends what is the result you're after.
>

What I'm really after is such that whenever a transaction is edited and the
branch name on that
transaction is changed, the model Transaction should save the changed value
in the database.

>
> Since your post doesn't indicate I made two guesses:
>
> 1) You want to store transaction in denormalized form. Meaning that branch
> name will be stored as a string without any relation to existing data.
>

It will have relation to Branch model name_branch field. So a transaction
just lookup the branch name from Branch model. This is the reason I made it
a ForeignKey.

>
> This is good for history record keeping so if branches do change, value
> stored in transaction is kept unchanged. I assume that this is also your
> case.
>
> Trick there is to define branch as a charfield, not foreign key.
>
> class Transaction(models.Model):
>  branch_name = models.CharField(max_length=**255)
>
> And in a form you use form.ChoiceField (since it will be simple list of
> choices, not list of model instances)
>

If I use form.ChoiceField, how do I get the records from the database? The
choices are dynamic, which is why I have opted to go for ModelChoiceField.
Also, I don't really want to care if the ForeignKey field in Transaction
model is of type int or varchar, since I see that Mysql doesn't care about
this either. My major concern is why is Django reporting the error:

branch_n
ameSelect a
valid choice.
 That choice is not one of the available choices.

Hence, saying the form is invalid? Is there any special thing I'm missing. I
have tried
to check the admin module source to see how it is done in there, but I've
not been able
to see much.

Please, what do I do in this case?

>
> 2) You want to use character field as a primary key.
>
> This is very easy and doable, though it will kill relational queries quite
> easily - strings do not make great indexes.
>
> Just change your primary key to be something like:
>
> class Branch(models.Model):
>name = models.CharField(max_length=**255, primary_key=True)
>
> This approach has it's caveats specially when removing/renaming entries. I
> wouldn't suggest this approach.


This is not the issue in this use case.

Thanks for the help.

>
>
> On 24.10.2011 13:14, Kayode Odeyemi wrote:
>
>> Hello all,
>>
>> Is there a way to have a foreign key on a model which uses a type other
>> than Django's forceful
>> int type to make the storage for a ModelChoiceField widget?
>>
>> I have something like this I'm working with:
>>
>> forms.py
>> 
>>
>> class BranchModelChoiceField(**ModelChoiceField):
>> def label_from_instance(self, obj):
>> return obj
>>
>> class TransactionUpdateForm(forms.**ModelForm):
>> branchqs = Branch.objects.values_list(u'**name_branch', flat=True) #
>> use flat=True if values_list is called with a single field
>> branch_name = BranchModelChoiceField(**branchqs)
>> class Meta:
>> model = Transaction
>> fields = ('teller_no', 'paid')
>>
>> models.py
>> --
>> class Branch(models.Model):
>> """ Branch """
>> bid = models.AutoField(primary_key=**True)
>> name_branch = models.CharField(max_length=**255)
>>
>> class Meta:
>> db_table = u'branch'
>>
>> def __unicode__(self):
>> return self.name_branch
>>
>> class Transaction(models.Model):
>> id = models.AutoField(primary_key=**True)
>> branch_name = models.ForeignKey(Branch, blank=True, null=True,
>> related_name='transaction')
>> paid = models.BooleanField(default=**False)
>> teller_no = models.CharField(max_length=**20, blank=True)
>> created = models.DateTimeField(auto_now_**add=True)
>> updated = models.DateTimeField(auto_now=**True)
>>
>> in views.py
>> ---
>> if request.POST:
>> update_form = TransactionUpdateForm(request.**POST, instance=txn)
>> txn.branch_name = Branch([int(k) for k,v in dic.iteritems() if
>> v == update_form.cleaned_data['**branch_name']][0]) # Forcefully store
>> the key
>> if update_form.is_valid():
>> update_form.save()
>>
>> The form worked perfectly in admin but not from my own custom ModelForm.
>>
>> I don't know if my title is correct as I can see that Django saves the
>> selected element key in
>> the db and not its value which will be of type integer
>>
>> I'm getting the error from my oen custom ModelForm:
>> branch_**nameSelect a
>> valid choice.
>>  That choice is not one of the available choices.
>>
>> Please how do I get the form saved with the selected branch value?
>>
>> Please help.
>>
>> Thanks
>>
>> --
>> Odeyemi 'Kayode O.
>> http://www.sinati.com. t: @charyorde
>>
>> --
>> You received this message because you are subscribed to the Google
>> Groups "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-u

Re: Setting default values in a form from DB table

2011-10-24 Thread Andre Terra
You should always populate your form in forms.py. This is done using the
'initial' kwarg and is thoroughly explained in the docs! [1]

Borrowing from the tutorial's Poll model [2]:

Class PollsForm(forms.Form):
def __init__ (self, *args, **kwargs):
self.instance = kwargs.pop('instance', None)

if self.instance.pk is not None:
kwargs['initial'] = kwargs.get('initial', {})
kwargs['initial'] = {'question': self.instance.question}

super(PollsForm, self).__init__(*args, **kwargs)

This way, you can edit a Poll object by calling
PollsForm(instance=some_poll_object),
and it will automatically populate 'question' with the instance's
question attribute.


Cheers,
AT

[1]
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
[2] https://docs.djangoproject.com/en/dev/intro/tutorial01/#creating-models




On Sun, Oct 23, 2011 at 4:08 PM, Swaroop Shankar V wrote:

> Hello All,
>
> I am trying to create a Edit form to edit user information. I would like to
> display the default values in the form fields rendered and am getting the
> values from the db table. I can take an approach by creating a dictionary
> with the values that needs to be populated in the form fields in my view
> file and then pass it to the html. Then in the html, i can manually set the
> values using the django-widget_tweaks. But the problem here is that there
> are few select box for which this approach wont work. So the next option is
> to do it from the forms.py but there i need to get the currently logged in
> user and since request object is not available i created an __init__
> function with the following statements
>
> def __init__(self, *args, **kwargs):
> self.request = kwargs.pop('request', None)
> super(UserEditForm, self).__init__(*args, **kwargs)
>
> but now i am not sure on how to set up the form values. My form's class
> code can be accessed via the url http://pastebin.com/1TuRmNhH . Please
> help.
>
> Thanks and Regards,
> Swaroop Shankar V
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@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-users@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 set up Apache to serve up django websites?

2011-10-24 Thread Andre Terra
ImportError: Could not import settings 'portal.settings' (Is it on
sys.path?): No module named portal.settings

I tried to add this to my apache envvars file as:


export
PATH=/home/roger/projects/playground/feincms_env/bin:/home/roger/projects/portal:$PATH


You need to add /home/roger/projects to your path, so that
portal.settingscan get imported.


Cheers,
AT

On Mon, Oct 24, 2011 at 4:39 AM, Roger Marcus wrote:

> I have the django project Mezzanine up and working well. They have done a
> much better job in making it easier for the user
> to install and run their project.
>
> I am now fighting to get this all working with apache.
>
> From the django documentation, chapter 20, i have inserted:
>
>
> 
> SetHandler python-program
> PythonHandler django.core.handlers.modpython
> SetEnv DJANGO_SETTINGS_MODULE portal.settings
> PythonDebug On
> 
>
> Into my apache default settings.
> Once again, however, I have path problems. Assuming my portal is called
> portal, when I run another small python web service
> I get the following traceback error:
>
>  File 
> "/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/core/handlers/base.py",
>  line 39, in load_middleware
> for middleware_path in settings.MIDDLEWARE_CLASSES:
>
>   File 
> "/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/utils/functional.py",
>  line 276, in __getattr__
> self._setup()
>
>   File 
> "/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/conf/__init__.py",
>  line 42, in _setup
> self._wrapped = Settings(settings_module)
>
>   File 
> "/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/conf/__init__.py",
>  line 89, in __init__
> raise ImportError("Could not import settings '%s' (Is it on sys.path?): 
> %s" % (self.SETTINGS_MODULE, e))
>
> ImportError: Could not import settings 'portal.settings' (Is it on 
> sys.path?): No module named portal.settings
>
> I tried to add this to my apache envvars file as:
> export
> PATH=/home/roger/projects/playground/feincms_env/bin:/home/roger/projects/portal:$PATH
>
> Can someone help me resolve this final path problem? Thanks.
> Roger
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/django-users/-/bAnugUREnzQJ.
> To post to this group, send email to django-users@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-users@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: Help w/ optimization

2011-10-24 Thread Flavia Missi
I'm sorry, I think I didn't explain myself right. I always use
select_related when I need a join, thus, I avoid more then one query. When I
don't need a join I don't use it :)

[]'s

On Mon, Oct 24, 2011 at 9:34 AM, Tom Evans  wrote:

> On Mon, Oct 24, 2011 at 12:30 PM, Flavia Missi 
> wrote:
> > Looks like a genre has a genre group associated with it, right? You could
> > use select_related [1] method when selecting all genres, so, when Django
> > executes the query, all the relation comes in only one query.
> >
> > [1]
> https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.select_related
> > That is all the improvement that I can see in your code, and I agree with
> > Tom, but I don't consider using select_related as a premature
> optimization,
> > I always use it. :)
>
> That is what I would call the definition of premature optimization! If
> you always use it, there will be times when you join to tables/extract
> data from the DB that you do not need at that time.
>
> Cheers
>
> Tom
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@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.
>
>


-- 
Flávia Missi
@flaviamissi 
flaviamissi.com.br
https://github.com/flaviamissi

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: How to make a foreign key field of type other than int?

2011-10-24 Thread Jani Tiainen

Hi,

It really depends what is the result you're after.

Since your post doesn't indicate I made two guesses:

1) You want to store transaction in denormalized form. Meaning that 
branch name will be stored as a string without any relation to existing 
data.


This is good for history record keeping so if branches do change, value 
stored in transaction is kept unchanged. I assume that this is also your 
case.


Trick there is to define branch as a charfield, not foreign key.

class Transaction(models.Model):
  branch_name = models.CharField(max_length=255)

And in a form you use form.ChoiceField (since it will be simple list of 
choices, not list of model instances)


2) You want to use character field as a primary key.

This is very easy and doable, though it will kill relational queries 
quite easily - strings do not make great indexes.


Just change your primary key to be something like:

class Branch(models.Model):
name = models.CharField(max_length=255, primary_key=True)

This approach has it's caveats specially when removing/renaming entries. 
I wouldn't suggest this approach.


On 24.10.2011 13:14, Kayode Odeyemi wrote:

Hello all,

Is there a way to have a foreign key on a model which uses a type other
than Django's forceful
int type to make the storage for a ModelChoiceField widget?

I have something like this I'm working with:

forms.py


class BranchModelChoiceField(ModelChoiceField):
 def label_from_instance(self, obj):
 return obj

class TransactionUpdateForm(forms.ModelForm):
 branchqs = Branch.objects.values_list(u'name_branch', flat=True) #
use flat=True if values_list is called with a single field
 branch_name = BranchModelChoiceField(branchqs)
 class Meta:
 model = Transaction
 fields = ('teller_no', 'paid')

models.py
--
class Branch(models.Model):
""" Branch """
 bid = models.AutoField(primary_key=True)
 name_branch = models.CharField(max_length=255)

 class Meta:
 db_table = u'branch'

 def __unicode__(self):
 return self.name_branch

class Transaction(models.Model):
 id = models.AutoField(primary_key=True)
 branch_name = models.ForeignKey(Branch, blank=True, null=True,
related_name='transaction')
 paid = models.BooleanField(default=False)
 teller_no = models.CharField(max_length=20, blank=True)
 created = models.DateTimeField(auto_now_add=True)
 updated = models.DateTimeField(auto_now=True)

in views.py
---
if request.POST:
 update_form = TransactionUpdateForm(request.POST, instance=txn)
 txn.branch_name = Branch([int(k) for k,v in dic.iteritems() if
v == update_form.cleaned_data['branch_name']][0]) # Forcefully store the key
 if update_form.is_valid():
 update_form.save()

The form worked perfectly in admin but not from my own custom ModelForm.

I don't know if my title is correct as I can see that Django saves the
selected element key in
the db and not its value which will be of type integer

I'm getting the error from my oen custom ModelForm:
branch_nameSelect a
valid choice.
  That choice is not one of the available choices.

Please how do I get the form saved with the selected branch value?

Please help.

Thanks

--
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde

--
You received this message because you are subscribed to the Google
Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.


--

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-users@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: Django and Shibboleth

2011-10-24 Thread Tom Evans
On Fri, Oct 21, 2011 at 2:45 PM, Alfred Buterol  wrote:
> I'm investigating the options for using Shibboleth in a Django
> deployment. From what I've found, things look somewhat sparse. Can
> anyone comment on the following?
>
> *  Is anyone using the django_shibboleth module (see
> http://code.arcs.org.au/gitorious/django/django-shibboleth/trees/1.1)?
> If so, what experiences have you had with this module?
>
> *  SAML 2 implementations for Django (e.g., django-saml2-sp) and
> Python in general (e.g., pysaml2) appear to be somewhat experimental
> and include little documentation. Does anyone know of stable SAML 2
> solutions for Django/Python?
>
> Thanks in advance for any help!
>

Are you trying to build a SP or an IdP? We've built both using a C
library, lasso[1], which has python bindings. Entrouvert is a french
company, backed by government grants, which produces open source
software for identity management. Plus facile si tu parle français
though.

If it is just a SP, you only really have to implement
AssertionConsumerService and SingleLogoutService, and be able to
initiate a SSO request to the IdP - its not masses of work,
particularly with lasso.

We've not hooked into a Shibboleth federation yet however, there may
be intricacies to their federation.

Cheers

Tom

[1] http://lasso.entrouvert.org/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: redirect problems

2011-10-24 Thread nicolas HERSOG
Hi everyone,
I digged more but i'm still stuck.
I understood that i have to use namespaceURL.
So i modified my url.py this way :

from myAppFront.views import article

url (r'^article/(?P\d+)/$',
myAppFront.views.article,
name='article'),

and this is my addComment view :

def addComment(request, id):
article = article.objects.get(id=id)
if request.method == 'POST':
form = CommentForms(data=request.POST)
if form.is_valid():
cf_comment = form.cleaned_data['cf_comment']
cf_writer = request.user
cf_date = datetime.datetime.now()
cf_video = video
c1 = Commentaire.objects.create(comment=cf_comment,
dateComment=cf_date, writer=cf_writer, article=cf_article)
c1.save()
#return HttpResponseRedirect(reverse('myAppFront.views.article',
args=(id,)))
return HttpResponseRedirect(reverse('myAppFront.views.article',
kwargs={'id': id}))

It's still doesn't work, i have this error :
NoReverseMatch at /article/1/addComment/

Reverse for 'myAppFront.views.article' with arguments '()' and keyword
arguments '{'id': u'1'}' not found.


I don't know if it can help but this is my article view :

def article(request, id):
article = article.objects.get(id=id)
commentaires = Commentaire.objects.filter(article=article.id
).order_by("-dateComment")
date = datetime.datetime.now()
c = Context({
'article' : article,
'commentaires' : commentaires,
'now' : date,
})
form = CommentForms()
c['form'] = form
return render_to_response('myAppFront/article.html', c,
context_instance=RequestContext(request))

thx for your help :)



On Sun, Oct 23, 2011 at 5:01 PM, nicolas HERSOG  wrote:

> Hi everyone,
>
> I'm stuck with the redirection in django.
>
> This is my url.py
>
> (r'^article/(?P\d+)/$', 'myapp.myappFront.views.article'),
> (r'^article/(?P\d+)/addComment/$',
> 'myapp.myappFront.views.addComment'),
>
> I developed a little view in order to add comment to my article, this is my
> view.py
>
> def article(request, id):
> article = article.objects.get(id=id)
> commentaires = Commentaire.objects.filter(article=article.id
> ).order_by("-dateComment")
>  #dateTime
> date = datetime.datetime.now()
>
> c = Context({
>  'article' : video,
> 'commentaires' : commentaires,
> 'now' : date,
>  })
> form = CommentForms()
> c['form'] = form
> return render_to_response('myappFront/article.html', c,
> context_instance=RequestContext(request))
>  def addComment(request, id):
> article = article.objects.get(id=id)
> if request.method == 'POST':
> form = CommentForms(data=request.POST)
> if form.is_valid():
> cf_comment = form.cleaned_data['cf_comment']
> cf_writer = request.user
> cf_date = datetime.datetime.now()
> cf_video = video
> c1 = Commentaire.objects.create(comment=cf_comment,
> dateComment=cf_date, writer=cf_writer, video=cf_video)
> c1.save()
> else:
> c = Context({
> 'id' : id,
> })
> #return render_to_response('myappFront/article.html', c,
> context_instance=RequestContext(request))
> #return HttpResponseRedirect(reverse('myappFront.views.article',
> args=(id,)))
> #return HttpResponseRedirect(reverse('myappFront.views.article',
> kwargs={'id': id}))
> return HttpResponseRedirect(reverse('myappFront.views.article',
> args=(id,)))
>
> The view article works well, my form for add comment seems ok, i can add
> comment to my article, but the problem is
> the redirection at the end of the addComment method.
> As u see, I tried many many syntax in order to redirect the user to the
> article, but all of this test failed.
> Every time i have this kind of error :
>
> NoReverseMatch at /article/9/addComment/
> Reverse for 'myAppFront.views.article' with arguments '(u'9',)' and keyword
> arguments '{}' not found.
>
> Any idea ?
>
> Thx for all :)
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



How to set up Apache to serve up django websites?

2011-10-24 Thread Roger Marcus
I have the django project Mezzanine up and working well. They have done a 
much better job in making it easier for the user
to install and run their project.

I am now fighting to get this all working with apache.

>From the django documentation, chapter 20, i have inserted:


SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE portal.settings
PythonDebug On


Into my apache default settings.
Once again, however, I have path problems. Assuming my portal is called 
portal, when I run another small python web service 
I get the following traceback error:

 File 
"/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/core/handlers/base.py",
 line 39, in load_middleware
for middleware_path in settings.MIDDLEWARE_CLASSES:

  File 
"/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/utils/functional.py",
 line 276, in __getattr__
self._setup()

  File 
"/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/conf/__init__.py",
 line 42, in _setup
self._wrapped = Settings(settings_module)

  File 
"/home/roger/projects/playground/feincms_env/lib/python2.6/site-packages/django/conf/__init__.py",
 line 89, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" 
% (self.SETTINGS_MODULE, e))

ImportError: Could not import settings 'portal.settings' (Is it on sys.path?): 
No module named portal.settings

I tried to add this to my apache envvars file as:
export 
PATH=/home/roger/projects/playground/feincms_env/bin:/home/roger/projects/portal:$PATH

Can someone help me resolve this final path problem? Thanks.
Roger

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/bAnugUREnzQJ.
To post to this group, send email to django-users@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: Help w/ optimization

2011-10-24 Thread Tom Evans
On Mon, Oct 24, 2011 at 12:30 PM, Flavia Missi  wrote:
> Looks like a genre has a genre group associated with it, right? You could
> use select_related [1] method when selecting all genres, so, when Django
> executes the query, all the relation comes in only one query.
>
> [1] https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.select_related
> That is all the improvement that I can see in your code, and I agree with
> Tom, but I don't consider using select_related as a premature optimization,
> I always use it. :)

That is what I would call the definition of premature optimization! If
you always use it, there will be times when you join to tables/extract
data from the DB that you do not need at that time.

Cheers

Tom

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

2011-10-24 Thread Kurtis Mullins
Thanks guys! I appreciate the great answers!

On Mon, Oct 24, 2011 at 7:30 AM, Flavia Missi  wrote:

> Looks like a genre has a genre group associated with it, right? You could
> use select_related [1] method when selecting all genres, so, when Django
> executes the query, all the relation comes in only one query.
>
> [1]
> https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.select_related
>
> That is all the improvement that I can see in your code, and I agree with
> Tom, but I don't consider using select_related as a premature optimization,
> I always use it. :)
>
> []'s
>
>
> On Mon, Oct 24, 2011 at 9:17 AM, Tom Evans wrote:
>
>> On Mon, Oct 24, 2011 at 11:59 AM, Kurtis 
>> wrote:
>> > Hey guys,
>> >
>> > I have some custom context in a view. I'm going to be replicating this
>> > context three times for different object relationships. I didn't
>> > count, but looking at django-debug-toolbar I'm thinking this block of
>> > code runs at around 10 queries. Times that by 3 and I'm going to be
>> > bogging my application down in no time.
>> >
>> > The code is here: http://dpaste.com/640165/
>> >
>> > Thanks!
>> >
>>
>> Couple of suggestions:
>>
>> 1) Cache the data. You will need to work out a good (correct) key
>> based upon the kwargs. If the info will only be useful on this
>> request, but you need to access it multiple times within that request,
>> you can simply add it as an attribute on the request. Otherwise, stick
>> it in memcached, with a short TTL (and make sure you invalidate the
>> cache when the data behind it changes).
>> You could also cache individual components of this. The Genre and
>> GenreGroup information is distinct and unchanging from the item
>> specific components of it.
>>
>> 2) Get dirty into raw SQL and hand tune the queries you issue so that
>> you can optimize this function. It's possible that you could work this
>> out into one (complex) query.
>>
>> 3) "We should forget about small efficiencies, say about 97% of the
>> time: premature optimization is the root of all evil" Knuth knows what
>> he is talking about, if you haven't noticed a problem, just remember
>> that this code is a possible optimization win, and revisit when it
>> actually is slow.
>>
>> BTW, I only count 3 queries there…
>>
>> Cheers
>>
>> Tom
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@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.
>>
>>
>
>
> --
> Flávia Missi
> @flaviamissi 
> flaviamissi.com.br
> https://github.com/flaviamissi
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> 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-users@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 do you pinpoint a performance issue?

2011-10-24 Thread Tom Evans
On Fri, Oct 21, 2011 at 8:08 PM, Shawn Milochik  wrote:
> Real-life situation:
>
>    I deployed a week's worth of code changes to production. Upon
> restart, site wouldn't load anymore. Nothing but a 404 error.
>
> Long story short:
>
>    By using Django's logging, I discovered that a query was being run
> tens thousands of times -- obviously in a loop. I inserted
> traceback.format_stack() logging into Django's code temporarily to
> pinpoint the culprit. I discovered that when the URLs were imported
> and admin.autodiscover() was called it imported an admin.py file,
> which imported a models.py file, which imported a forms.py file, which
> contained a Form subclass that was doing something woefully
> inefficient with a "choices" kwarg. Optimized query, moved it into the
> form's __init__, problem solved.
>
> But in the meantime:
>
>    The site was down for about a half-hour in the time it took me to
> work around the problem by realizing that gunicorn workers were timing
> out and increasing the timeout in my supervisord config. And that was
> just a quick & dirty "fix" to give me time to find the real problem,
> which took considerably longer.
>
> What I need:
>
>    What's the best way to start looking for a problem like this? I
> started with pdb, but it's a ridiculously inefficient tool for this
> kind of problem, and I went off in the wrong direction a couple of
> times trying to zero in on the issue. It's just a pleasant coincidence
> that when I checked the log there was a huge number of queries which
> set me off in the right direction.
>
>    Maybe part of the problem is that I'm not familiar with Django's
> bootstrapping process, so I don't know where to sprinkle logging
> statements to isolate the issue.
>
>    I'm looking for a general solution. Don't assume the issue is
> necessarily ORM-related or anything in particular. Just that something
> is slow and I'm trying to find out what it is.
>
> Thanks in advance for any wisdom and hard-earned experience you can share.
>
> Shawn

Hi Shawn

30 minutes to go from "wtf? now nothing is working" to "ok, that was
silly, fixed" doesn't seem too bad. The important thing is to not
expose that to end users.

We do this by having an insulated integration environment, which
duplicates the conditions on the frontend, and allows us to run a test
load through the site. Anything which looks hinky on integration
doesn't make it to production.

Finally, we run two app servers, backed by a MySQL master-master
replication - this is for reliability and recovery, not performance.
When we do an upgrade, we temporarily send all http traffic to one of
the app servers, and upgrade the other one. At that point, we change
and push all traffic through the updated app server and let it run for
a good few hours.

If anything goes wrong at this point, we can go back to the un-updated
version and revert the other app server back, otherwise we can
complete the update on the other app server, and push traffic equally
to both servers.

Our integration infrastructure uses Squid and Apache to 'fake up' our
DC - we change proxy to the one in the integration infra, which then
redirects public names into the integration infra. Our app servers run
apache/mod_fcgi, and our frontends run apache and HAproxy.

Cheers

Tom

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

2011-10-24 Thread Flavia Missi
Looks like a genre has a genre group associated with it, right? You could
use select_related [1] method when selecting all genres, so, when Django
executes the query, all the relation comes in only one query.

[1]
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.select_related

That is all the improvement that I can see in your code, and I agree with
Tom, but I don't consider using select_related as a premature optimization,
I always use it. :)

[]'s

On Mon, Oct 24, 2011 at 9:17 AM, Tom Evans  wrote:

> On Mon, Oct 24, 2011 at 11:59 AM, Kurtis  wrote:
> > Hey guys,
> >
> > I have some custom context in a view. I'm going to be replicating this
> > context three times for different object relationships. I didn't
> > count, but looking at django-debug-toolbar I'm thinking this block of
> > code runs at around 10 queries. Times that by 3 and I'm going to be
> > bogging my application down in no time.
> >
> > The code is here: http://dpaste.com/640165/
> >
> > Thanks!
> >
>
> Couple of suggestions:
>
> 1) Cache the data. You will need to work out a good (correct) key
> based upon the kwargs. If the info will only be useful on this
> request, but you need to access it multiple times within that request,
> you can simply add it as an attribute on the request. Otherwise, stick
> it in memcached, with a short TTL (and make sure you invalidate the
> cache when the data behind it changes).
> You could also cache individual components of this. The Genre and
> GenreGroup information is distinct and unchanging from the item
> specific components of it.
>
> 2) Get dirty into raw SQL and hand tune the queries you issue so that
> you can optimize this function. It's possible that you could work this
> out into one (complex) query.
>
> 3) "We should forget about small efficiencies, say about 97% of the
> time: premature optimization is the root of all evil" Knuth knows what
> he is talking about, if you haven't noticed a problem, just remember
> that this code is a possible optimization win, and revisit when it
> actually is slow.
>
> BTW, I only count 3 queries there…
>
> Cheers
>
> Tom
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@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.
>
>


-- 
Flávia Missi
@flaviamissi 
flaviamissi.com.br
https://github.com/flaviamissi

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Help w/ optimization

2011-10-24 Thread Tom Evans
On Mon, Oct 24, 2011 at 11:59 AM, Kurtis  wrote:
> Hey guys,
>
> I have some custom context in a view. I'm going to be replicating this
> context three times for different object relationships. I didn't
> count, but looking at django-debug-toolbar I'm thinking this block of
> code runs at around 10 queries. Times that by 3 and I'm going to be
> bogging my application down in no time.
>
> The code is here: http://dpaste.com/640165/
>
> Thanks!
>

Couple of suggestions:

1) Cache the data. You will need to work out a good (correct) key
based upon the kwargs. If the info will only be useful on this
request, but you need to access it multiple times within that request,
you can simply add it as an attribute on the request. Otherwise, stick
it in memcached, with a short TTL (and make sure you invalidate the
cache when the data behind it changes).
You could also cache individual components of this. The Genre and
GenreGroup information is distinct and unchanging from the item
specific components of it.

2) Get dirty into raw SQL and hand tune the queries you issue so that
you can optimize this function. It's possible that you could work this
out into one (complex) query.

3) "We should forget about small efficiencies, say about 97% of the
time: premature optimization is the root of all evil" Knuth knows what
he is talking about, if you haven't noticed a problem, just remember
that this code is a possible optimization win, and revisit when it
actually is slow.

BTW, I only count 3 queries there…

Cheers

Tom

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

2011-10-24 Thread Kayode Odeyemi
On Sun, Oct 23, 2011 at 8:52 AM, Chen Xu  wrote:

> Hi, Every one:
> I am trying to create a user registration form.
> The default of User table has limited number of fields, but I want to add
> more into it.
> Therefore, I am wondering what is the better way to do it? Creating another
> UserProfile class, and adding  "AUTH_PROFILE_MODULE = account.UserProfile",
> or using Model inheritance?
>
> I don't think itis appropriate to add to the existing User table provided
by Auth.
You can use the UserProfile model and add new fields to it and those other
fields
will be made available when you need User object.

>
>
> --
> ⚡ Chen Xu ⚡
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Login problems under heavy load

2011-10-24 Thread Tom Evans
On Fri, Oct 21, 2011 at 6:15 PM, Alpesh Gajbe  wrote:
>
>  File "/usr/local/lib/python2.6/dist-packages/django/http/__init__.py",
> line 296, in read
>   return self._stream.read(*args, **kwargs)
>
> IOError: request data read error
>

tl;dr - the user got bored waiting, pressed 'stop' on their browser.

This means the users browser stopped sending information. When your
server is busy (fully loaded), incoming requests to Apache's listen
socket are queued up to whatever you have configured ListenBacklog to.
At the same time, the OS is doing you a favour by pre-reading the
request into memory (AcceptFilter).

When the request is finally handled by Apache (reaches the front of
the backlog queue), the request has been pre-read, and processes
through Apache until it is delivered to mod_wsgi. Django then attempts
to read the rest of the request (if there is any).

This point is the first time that the socket has been read from since
the request was accepted by the kernel, and if the user has pressed
'stop', then there will be an error when trying to read from the
socket, which will get raised as an IOError.

Actually, thinking about it, there are another couple of possibilities
as to how the user disconnected. Apache could have read the request,
but was waiting for a mod_wsgi thread/child to be available, and the
user pressed stop there. This is probably more likely on Linux, which
only has extremely primitive accept filters.

The important thing to take away is that if you get an IOError when
reading/writing from/to a client, then the user isn't connected to the
other end any-more. It's not a django bug, buy a faster web server, db
server, ISP or shard your users so that they spend less time waiting.

Cheers

Tom

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



Help w/ optimization

2011-10-24 Thread Kurtis
Hey guys,

I have some custom context in a view. I'm going to be replicating this
context three times for different object relationships. I didn't
count, but looking at django-debug-toolbar I'm thinking this block of
code runs at around 10 queries. Times that by 3 and I'm going to be
bogging my application down in no time.

The code is here: http://dpaste.com/640165/

Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Django as a Standalone Desktop Application

2011-10-24 Thread Tom Evans
On Sun, Oct 23, 2011 at 2:32 AM, Alex Mandel  wrote:
> Also the best part of this design is that you can turn it into a web app
> at any time by simply opening a port on a machine to allow others to
> connect.
>

Is that supposed to be a plus? Sounds like a nightmare.

The smart way to do this is to build a simple wxpython application
that consumes django web services to CRUD data. You can build your
reporting tools using django, use the built-in admin, etc, whilst
exposing only the minimum of web services to allow your app to enter
information into the system.

I have a number of non-web django processes, so I'm not against that
in general. However, installing a full LAMP/WAMP stack, django and all
required packages onto a single users machine, and have them enter
data via their browser to their personal django instance is crazy. Not
only will maintenance be disaster, but you have no data consistency -
each user has their own stack, including DB. If you have each machine
connecting to a shared database, well that is even worse, as each user
would be able to discern credentials which they can use to access the
DB and meddle directly.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@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 make a foreign key field of type other than int?

2011-10-24 Thread Kayode Odeyemi
Hello all,

Is there a way to have a foreign key on a model which uses a type other than
Django's forceful
int type to make the storage for a ModelChoiceField widget?

I have something like this I'm working with:

forms.py


class BranchModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj

class TransactionUpdateForm(forms.ModelForm):
branchqs = Branch.objects.values_list(u'name_branch', flat=True) # use
flat=True if values_list is called with a single field
branch_name = BranchModelChoiceField(branchqs)
class Meta:
model = Transaction
fields = ('teller_no', 'paid')

models.py
--
class Branch(models.Model):
""" Branch """
bid = models.AutoField(primary_key=True)
name_branch = models.CharField(max_length=255)

class Meta:
db_table = u'branch'

def __unicode__(self):
return self.name_branch

class Transaction(models.Model):
id = models.AutoField(primary_key=True)
branch_name = models.ForeignKey(Branch, blank=True, null=True,
related_name='transaction')
paid = models.BooleanField(default=False)
teller_no = models.CharField(max_length=20, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

in views.py
---
if request.POST:
update_form = TransactionUpdateForm(request.POST, instance=txn)
txn.branch_name = Branch([int(k) for k,v in dic.iteritems() if v ==
update_form.cleaned_data['branch_name']][0]) # Forcefully store the key
if update_form.is_valid():
update_form.save()

The form worked perfectly in admin but not from my own custom ModelForm.

I don't know if my title is correct as I can see that Django saves the
selected element key in
the db and not its value which will be of type integer

I'm getting the error from my oen custom ModelForm:
branch_nameSelect a
valid choice.
 That choice is not one of the available choices.

Please how do I get the form saved with the selected branch value?

Please help.

Thanks

-- 
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Subclassing the ForeignKey field type

2011-10-24 Thread Tobia Conforto
Hi Guy

I do think my approach is better. Remember the Django motto "Don't
Repeat Yourself"! The serialization logic belongs to a library class,
not in your models. I can't give you my entire code (it belongs to my
employer) but I can point you to the right direction.

-Tobia

# your model:

class Risk(XmlModel):
# optionally supply an xpath to Xml fields:
# id = XmlAutoField(primary_key=True, xpath='@id')
name = XmlCharField(max_length=50, blank=True)
user = XmlForeignKey(User, related_name='risk')

# library classes:

class XmlModel:
class Meta:
abstract = True
def to_xml(self):
# here goes generic code (written and tested only once!) to
serialize
# any XmlModel instance to xml (I used ElementTree by the way).
# iterate over fields and only serialize instances of 
XmlBaseField,
# using special logic for instances of models.ForeignKey and
# related.ManyToOneRel, calling to_xml() on the related objects.

class XmlBaseField(object):
def __init__(self, *args, **kwargs):
# accept 'xpath' keyword argument, pop it and store it in self,
# defaulting to the field name if not provided, then call super

class XmlCharField(XmlBaseField, CharField):
__metaclass__ = SubfieldBase
def __init__(self, *args, **kwargs):
# just call super here

class XmlForeignKey(XmlBaseField, ForeignKey):
# no __metaclass__ goes here, which was my stumbling block
def __init__(self, *args, **kwargs):
# just call super here

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Subclassing the ForeignKey field type

2011-10-24 Thread guyf
Hi Tobia,

I have just discovered your post and I am trying to do something very
similar (create and XML doc from an object hierarchy).
I have started by trying to use the @toxml decorator and override the
__serialize__ method on my model. See (partially working) code below.

@toxml
class Risk(models.Model):
name = models.CharField(max_length=50, blank=True)
user = models.ForeignKey(User, related_name='risk')

def __unicode__(self):
return self.name

def __serialize__(self, stream):
stream.startElement(self._meta.object_name, {})
for field in self._meta.fields:
stream.startElement(field.name, {})
stream.characters(field.value_to_string(self))
stream.endElement(field.name)
for relobj in self._meta.get_all_related_objects():
o = relobj.name.partition(':')
m = models.get_model(o[0], o[2])
stream.startElement(m._meta.object_name, {})
for f in m._meta.fields:
stream.startElement(f.name, {})
stream.characters(f.value_to_string(m))
stream.endElement(f.name)
stream.endElement(o[2])
stream.endElement(self._meta.object_name)

My problem is 'stream.characters(f.value_to_string(m))' raises an
exception when the field is a Foreign Key.

However reading your question I am wondering if I am using the right
approach at all. Could you let me know if you think your method is
better and maybe provide a few code snippets to point me in the right
direction (if you think I am on the wrong track).

Thanks, Guy.


On Sep 15, 5:43 pm, Tobia Conforto  wrote:
> Hi all
>
> I'm adding an XML mapping feature to Django db models.
>
> The idea is to add as little XML mapping information as possible to existing
> models (such as: which fields get mapped to XML, what is their XPath...) in
> order to be able to automatically:
> 1. produce an XML representation of an object;
> 2. parse a valid XML representation into a new object; and
> 3. get an XSD schema of the model.
>
> I'm well ahead. I have all three features working for some simple models.
> But I've hit a wall with regard to object relations, or ForeignKey fields.
>
> Apparently any subclasses of ForeignKey are completely ignored by Django at
> runtime, even if they declare __metaclass__ = SubfieldBase
>
> I guess they would need a special kind of metaclass, which I guess has not
> been written yet.
>
> Can anybody help me understand what piece is failing?
> How can I make it work?
>
> -Tobia
>
> Here is a (non) working example:
>
> ### test/models.py:
>
> from django.db.models import *
>
> # subclassing works for any simple field type, why not related fields?
> class MyForeignKey(ForeignKey):
> __metaclass__ = SubfieldBase
>
> def __init__(self, *args, **kwargs):
> ForeignKey.__init__(self, *args, **kwargs)
>
> class TestSub(Model):
> pass
>
> class Test(Model):
> sub = MyForeignKey(TestSub)
>
> ### shell:
>
> >>> from test.models import Test, TestSub
> >>> ts = TestSub.objects.create()
> >>> t = Test.objects.create(sub=ts)
>
> Traceback (most recent call last):
>   ...
> AttributeError: 'Test' object has no attribute 'sub_id'
>
>
>
>
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Integrating Social Auth

2011-10-24 Thread Sachin Gupta
I have been trying to integrate 
social-authand it has been  a 
failure till now. I have done all the steps mentioned on 
this page, added the backends and the keys but it is not working. I am 
struggling how to get the templates working. If anyone can help me out that 
would be great.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/abQNd-8nZiMJ.
To post to this group, send email to django-users@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.