Re: Many to Many field in ModelForm - with tens of thousands of records

2018-10-29 Thread Sanjay Bhangar
My recommendation would be to use a bit of Javascript to implement an
"autocomplete" to fetch records via AJAX as the user types (with
perhaps a minimum of 3 characters or so), so you only ever fetch a
subset of records and don't overload your template.

You can find quite a few 3rd party libraries that should be able to
aid in setting up this behaviour, see:
https://djangopackages.org/grids/g/auto-complete/ - unfortunately, I
can't recommend a particular one right now - but most should have
integrations for the django admin / django forms with Many2Many or
ForeignKey fields.

Hope that helps,
Sanjay
On Mon, Oct 29, 2018 at 5:01 PM Web Architect  wrote:
>
> Would also add that the server CPU usage was hitting 100% due to the template 
> loading issue.
>
> On Monday, October 29, 2018 at 4:48:54 PM UTC+5:30, Web Architect wrote:
>>
>> Hi,
>>
>> We are using django 1.11 for our ecommerce site.
>>
>> We are facing an issue with modelform and many to many field in it as 
>> follows:
>>
>> Lets say there are two models:
>>
>> class A(models.Model):
>>c = models.CharField()
>>
>> class B(models.Model):
>>   a = models.ManyToManyField('A')
>>
>> Now if I define a modelform:
>>
>> class MF(models.ModelForm):
>>   class Meta:
>>   model = B
>>   fields = [a,]
>>
>> We are using django widget tweaks to render the fields in MF. Now if there 
>> are tens of thousands of records in A, the MF form rendering causes the page 
>> to hang as the widget will try to show the whole set of tens of thousands of 
>> records option for field a.
>>
>> Hence, would appreciate if anyone could suggest a smart solution wherein the 
>> above issue is taken care of.
>>
>> Thanks.
>>
>>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/36ebab2d-7440-40bc-b5e9-a4a2897dcd3a%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZHLEPgUKqZWfLh2yqJc6wkoAMbeY_iw5zDk%2BOJHqJejOw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: New entry tries to use an existing unique id

2018-10-26 Thread Sanjay Bhangar
Hi Michel,

So, a little explanation of why you're facing this issue:

When you create an "auto-increment" field in Postgres, Postgres creates
something called a "sequence" to keep track of the increments. If you were
to `psql` into your database and check the schema of the table, you'll see
the `id` field defined with something like:

id | integer  |   | not null |
nextval('content_id_seq'::regclass)

What this means is that to assign the `id` to an object, it will call the
"nextval" function on the "content_id_seq" sequence, to get the next number
in the sequence. In the normal flow of things, this is not a problem. Every
time you insert a new record into the table, it increments the sequence by
calling the "nextval" operation and populates the id, and the same for the
subsequent row insertion and so on.

Now, the problem arises if you imported data "directly" into the database,
i.e. INSERTed rows including the id, in which case, the database will never
call the "nextval" function internally, and the "sequence" it uses to keep
track of the incrementing ids will never have been updated. I.e. if you
manually insert 3000 rows with ids, the nextval() operation on the sequence
is never called, and hence postgres still thinks the "sequence" is at 1,
and therefore tries to assign the id of, say "2" to the next item, and then
of course fails since there is already an item that you manually inserted
with id 2.

There would be two ways to solve this:

 - 1> When importing the data, leave out the `id` field, and let postgres
populate the id field automatically using the auto-increment nextval()
function so the sequence stays in sync.
 - 2> The other option is to manually reset the sequence to be at whatever
your highest id value is.

The way to manually update the sequence:

For each table where you are facing this problem:

Run `\d` to see the table schema and get the name of the "sequence" ^^ in
my example above, the sequence name is "content_id_seq" - it will generally
follow the format of _id_seq .

Fetch the highest current id with:

SELECT id FROM  ORDER BY id DESC LIMIT 1;

Reset the sequence to the value of the highest id:

SELECT setval('content_id_seq', 4555, true);  # assuming your sequence is
called content_id_seq and the highest id was 4555 .

If doing this individually for each table in the db seems a bit tedious,
you will find various scripts and solutions to automate the process a bit
more by searching for something like "postgres reset sequence" - this is a
fairly common problem and you should find a bunch of material online.

I hope that helps!
-Sanjay


On Fri, Oct 26, 2018 at 6:50 AM Michel Lavoie 
wrote:

> Hi,
>
> I migrated my previous sqlite3 installation to postgresql, following this
> discussion:
> https://groups.google.com/forum/#!msg/django-users/VGG8GTAX4l0/tQUW20HcAwAJ
>
> I'm not facing another weird issue: Whenever I try to create a new item
> (finance.models.Debtor, see
> https://github.com/miek770/huitcent/blob/master/finance/models.py),
> django fails and tells me that primary key (1) is taken. Indeed, the next
> free id is around 3100. The time after that it tries to take id (2), then
> (3), and so on. The error looks like this:
>
> IntegrityError at /finance/2/add_transaction/
>
> duplicate key value violates unique constraint "finance_debtor_pkey"
> DETAIL:  Key (id)=(3) already exists.
>
> Request Method: POST
> Request URL: https://myserver/finance/2/add_transaction/
> Django Version: 2.1.2
> Exception Type: IntegrityError
> Exception Value:
>
> duplicate key value violates unique constraint "finance_debtor_pkey"
> DETAIL:  Key (id)=(3) already exists.
>
> Exception Location: /srv/http/huitcent/lib/python3.5/site-packages/django/
> db/backends/utils.py in _execute, line 85
> Python Executable: /srv/http/huitcent/bin/uwsgi
> Python Version: 3.5.3
> Python Path:
>
> ['.',
>  '',
>  '/srv/http/huitcent/lib/python35.zip',
>  '/srv/http/huitcent/lib/python3.5',
>  '/srv/http/huitcent/lib/python3.5/plat-arm-linux-gnueabihf',
>  '/srv/http/huitcent/lib/python3.5/lib-dynload',
>  '/usr/lib/python3.5',
>  '/usr/lib/python3.5/plat-arm-linux-gnueabihf',
>  '/srv/http/huitcent/lib/python3.5/site-packages']
>
> Server time: jeu, 25 Oct 2018 21:00:14 -0400
>
> As I mentioned before, there are indeed existing entries with these ids.
> My table definition in postgresql (version 10 looks like this:
>
> forum=# \d+ finance_debtor
> Table
> "public.finance_debtor"
>  Column |  Type   | Collation | Nullable |
> Default   | Storage | Stats target | Description
>
> +-+---+--++-+--+-
>  id | integer |   | not null |
> nextval('finance_debtor_id_seq'::regclass) | plain   |  |
>  transaction_id | integer |   | not null |
>   

Validating count + property of a Many2Many with a through table

2018-07-31 Thread Sanjay Bhangar
Hello!

This is more of a code organization question than a "something is not
working" question - it might get slightly rambling, so if this kind of
question is not your cup of tea, you have been warned :-)

So - I have a set of models like this (highly simplified):

class Item(models.Model):
  title = models.CharField(...)
  price = models.IntegerField(...)
  tags = models.ManyToManyField(Tag, through=ItemTag)

class Tag(models.Model):
  name = models.CharField(...)

class ItemTag(models.Model):
  item = models.ForeignKey(Item)
  tag = models.ForeignKey(Tag)
  is_primary = models.BooleanField()


So, I have an Item model that has some properties - it has a
ManyToMany relationship with Tag, and one or more tags can be selected
as "is_primary" tags for the model.

Now, to validate properties on the Item model, I call validation
methods inside a "clean" method on the Item model, something like:

  def clean(self):
if self.price > 1:
  raise ValidationError('Price cannot be so high!")

This is simplified, but you get the idea - this works great, errors
are propagated in the Admin, as well as raised when I import data via
a CSV file for example. I know there's a few different places one can
define validations - I personally like to have them in the model, but
I would love to hear alternate view-points if this is not the best
place to put them.

So, coming to the problem: there is now a requirement to validate that
a model cannot have more than 3 primary tags associated with it - i.e.
cannot be associated with more than 3 tags with the through table
specifying is_primary=True.

This, of course, cannot really go in the `clean` method of the Item
model. The ItemTag relationships don't exist yet, and I don't have the
data I need to be able to validate a maximum of 3 tags.

The problem is, I cannot seem to be able to do this kind of validation
in the ItemTag model either, since it depends on knowing how many
existing ItemTag relationships to Item there are - and before the
entire transaction is committed to the database, a single ItemTag
doesn't know whether the total exceeds the allowed 3.

The only place to put it that worked (and made sense) was in the
Formset definition for the inline form in the admin.

So, we landed up over-riding the formset used for the ItemTag inline
in the admin, adding our validations to the `clean` method - roughly
like:

class ItemImageInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
image_count = 0
for form in self.forms:
if form.cleaned_data.get('primary') == True:
image_count += 1
if image_count > 3:
raise ValidationError('Cannot have more than 3 primary tags')


This works. However, it seems a bit strange to have validations split
between a model method, and a subclass of a formset of an admin form.
It seems confusing in terms of maintainability - also, writing tests
for the validations in the model seemed a lot more straightforward
when validations were just in the model's `clean` method.

I can see why this is so. Am just wondering if I'm getting something
wrong in terms of patterns here / if there is a way other folks solve
this, to, ideally, be able to have all the validation that pertains to
a particular model in one place, and be able to test all model
validations in a consistent manner.

Thank you to whoever read this far :-)

-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZFZnemOSOwDRjDN--JLKdF94QEJNrbuTw2MCPoK1QxP7Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: GeoDjango: Filter by Area

2016-12-22 Thread Sanjay Bhangar
On Wed, Dec 21, 2016 at 10:08 PM, Tim Graham  wrote:

> If you don't get an answer here, you can also ask on the geodjango list:
> https://groups.google.com/forum/#!forum/geodjango.
>
>
Will do. Thanks Tim, you're the best!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZHrkuJEdHzitoz-b9epeRTG3XY4XU45g5EmDH62Th9uqQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


GeoDjango: Filter by Area

2016-12-19 Thread Sanjay Bhangar
Hey folks,

I am trying to use the 'Area' function documented here:
https://docs.djangoproject.com/en/1.10/ref/contrib/gis/functions/#area to
annotate my geo queryset results with Area of the polygon geometries in my
database.

This works great with something like:

  annotated_qset = GeoModel.objects.annotate(area=Area('geom'))

I then have a property called 'area` which I can use and it's all great.

However, I then try and filter by Area by following the documentation for
filtering by Length on the documentation page, so I try something like:

  filtered_qset =
GeoModel.objects.annotate(area=Area('geom')).filter(area__gt=1)

This gives an error like "AttributeError: 'AreaField' object has no
attribute 'get_lookup".

It makes sense that this works for the Length function since Length uses
the FloatField class, so supports lookups and filters, whereas the
AreaField does not:
https://github.com/django/django/blob/master/django/contrib/gis/db/models/sql/conversion.py#L24

I could be totally naive here and this may just not be a trivial thing for
the back-end (PostGIS in my case) to support, but just wondering if anyone
has any work-arounds to filter by area size of feature, and / or if there
are plans to support this in future versions.

Thank you all again for an amazing community and amazing piece of software
:-)

-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZHq4BtoAGwgQxNaXWG4ofYGGPwm1c4R4u6AFxCQMOUceQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Extracting results of a join

2016-10-10 Thread Sanjay Bhangar
On Mon, Oct 10, 2016 at 12:56 PM, Geoff Kuenning  wrote:

>
>
> So is there a way to get Django to issue this join and collect the
> results into an aggregate set?  I've read through the docs and
> experimented with different filter and double-underscore notations,
> without success.  It seems silly to do the work with a loop when a
> correctly written join can do it so much faster.  (And I'll note that if
> AlbumOrder had more entries, the loop would take far longer.)
>
>
Hi Geoff,

Have you looked at the docs for `select_related` and `prefetch_related`? It
sounds like they maybe what you're looking for here:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related

So your example query:

> for photo in photos.filter(albumorder__album = album.key):
photo.ordering = photo.albumorder_set.filter(album = album.key)

Would be something like `for photo in photos.filter(albumorder__album =
album.key).select_related('albumorder'): ...`

You need to tell Django which related tables to include in the initial SQL
query, and select_related and prefetch_related accomplish this, in subtly
different ways (will let you read the docs to figure that out since I
haven't quite myself ;-) )

Hope this helps! select_related has gotten me out of many DB optimization
issues in the past and now I'll never ship code without carefully examining
where all using a `select_related` would significantly speed up queries.

-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZEWsyZ4pdtURVXiRummSpOMkHHZSOte--3FrrM2VX7XxQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 1.7, KeyError: u'manager' error

2014-10-17 Thread Sanjay Bhangar
On Fri, Oct 17, 2014 at 2:53 PM, Taenyon Kim  wrote:

> Example
>
> class ModelA(models.Model):
> fielda = models.CharField(max_length=10)
>
> class ModelB(models.Model):
> modela = models.ForeignKey(ModelA)
> fieldb = models.CharField(max_length=10)
>
>
> When I query like "modela_instance.modelb_set()", then I will get
> KeyError: u'manager' as shown below:
>

AFAIK, you want something like "modela_instance.modelb_set.all()" - just
modela_instance.modelb_set() is the manager instance that you call call
methods on (like 'all', 'filter', etc.), but calling the manager directly
doesn't quite work, as you found out :)

All the best,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZEsi_7iYJP8k2s7ADjZt%2BtCXD2Mkatvrjx1_D%3Do5v%3D%3D_Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Retrieving recurring events using Django queries

2014-09-19 Thread Sanjay Bhangar
hey Stodge,

Interesting question :)

My guess is there are probably a number of approaches one can take. Of
course, processing all your entries in python "on the fly" would
probably get to be quite an intensive operation.

One possible idea maybe to create a "cache" table of sorts where you
pre-calculate and store all possible dates for a CalendarEntry.

Something like:

class EventDate(models.Model):
date = models.DateField(..)
calendarentry = models.ForeignKey(CalendarEntry)

Then, in the post_save of CalendarEntry, you write some code to
calculate all possible dates for the event and populate the EventDate
table. The problem is:
  a> If the CalendarEntry does not have an end_date, you obviously
cannot calculate all dates until the end of eternity - you would have
to come up with a reasonable "end date" beyond which queries are not
possible and only populate EventDate until that point (perhaps
updating it for the future with a cron job or some such .. )
  b> Generating the EventDates and the associated database INSERTs
could get quite intensive, especially, for say, a daily event for the
next 5 years, etc. If that gets to be a problem, you may need to do
this out of the request-response cycle, using for eg. django-celery.

Once you have that table, of course, querying would be something like
CalendarEntry.objects.filter(eventdate__date=date) , etc..

This is likely not the most elegant solution - not sure if there's a
better way to do it, or some efficient way to do the query directly in
the database without the overhead of maintaining this 'cache' table.

Would love to hear if anyone has an elegant solution to this - else
what I've outlined above should work, though it doesn't feel 100%
right, especially the part about needing some arbitrary cut-off date
to prevent an infinite generation of EventDate entries ..

Please do share what you land up coming up with.

All the best.
-Sanjay

On Fri, Sep 19, 2014 at 6:13 PM, Stodge  wrote:
> I have the following to model a calendar entry (recurring event). I need the
> ability to retrieve all events from the database between a start and end
> date. This has to include one off events and also recurring "virtual" events
> that occur because of an event in the database. Do you think this is
> possible using Django queries? Or do I need to retrieve the objects from the
> DB and then calculate the recurring events in the range in plain python
> using something like dateutil? I've been racking my brains but I can't seem
> to work out how to do it. Any suggestions appreciated.
>
> class CalendarEntry(models.Model):
>
> REPEAT_CHOICES = (
> ('NONE',_('None')),
> ('DAILY',_('Daily')),
> ('WEEKDAY',  _('Every weekday')),
> ('WEEKLY',   _('Weekly')),
> ('BIWEEKLY', _('Fortnightly')),
> ('MONTHLY',  _('Monthly')),
> ('YEARLY',   _('Yearly')),
> )
>
> # Mappings between content and an event entry.
> content_type= models.ForeignKey(ContentType, verbose_name='content
> type')
> object_id   = models.PositiveIntegerField()
> content_object  = generic.GenericForeignKey('content_type', 'object_id')
> field   = models.CharField(max_length=64)
>
> # Basic event information.
> start_date = TimestampGMT(blank=True, null=True)
> end_date = TimestampGMT(blank=True, null=True)
>
> # Recurrence information.
> all_day = models.BooleanField()
> repeat = models.CharField(max_length=15, choices=REPEAT_CHOICES,
> default='NEVER')
> end_repeat = models.DateTimeField(_("end repeat"), null=True,
> blank=True)
>
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/293df7ca-1192-49e2-8d94-d133bb1d5057%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZGzvqtbYk_8_aHiZseq%2B1eg5tTcRxm%3DvR3j8ZSURjqAEw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: deploying djnago on apache

2014-08-12 Thread Sanjay Bhangar
On Tue, Aug 12, 2014 at 2:41 PM, ngangsia akumbo  wrote:
> This is what i have for errors
>
> yems@yems /var/log/apache2 $ ls
>
> access.logerror.logother_vhosts_access.log
> access.log.1  error.log.1  other_vhosts_access.log.1
>

If you have not added a specific ErrorLog and CustomLog directive for
this vhost file (as per my previous email), apache will club all
access and error logs into the default access and error log files.

>
> static path
>
> yems@yems /var/www/bluepearlhotel $ ls
>
> blog  bluepearlhotel  event  gallery  home  images  manage.py  media  static
>
> app listed are blog, event, gallery, home, images, a
>
> and the project name is bluepearlhotel
>

You seemed to have your paths in your vhost conf as like
"/home/yems/var/ww/..." whereas your path seems to be /var/www/..
(without the /home/yems .. )

>
> i have also done the a2ensite bluepearlhotel.conf  it gave me this message
>
> yems@yems /etc/apache2/sites-available $ a2ensite bluepearlhotel.conf
>
> Site bluepearlhotel already enabled
>
> the out pu of  /etc/apache2/sites-available
>
>
> yems@yems /etc/apache2/sites-available $ ls
>
> 000-default.conf  bluepearlhotel.conf  default-ssl.conf  testsite.com
>
>
>
> config files are not being read
>

There seem to be several little silly things that could be the issue
here - its a bit hard to tell from out here - if you feel like, ping
me on chat (sanjayb on IRC/Freenode or my current email address on
google-chat) -- we can go over these things step by step and make sure
things are in order.

Cheers,
Sanjay


>
> There are no erros at the bluepearlhotel
>
>
> On Monday, August 11, 2014 4:52:11 PM UTC+1, Sanjay Bhangar wrote:
>>
>> hey Ngangsia,
>>
>>
>> On Mon, Aug 11, 2014 at 7:17 PM, ngangsia akumbo 
>> wrote:
>> > i have these configs
>> >
>> > project path
>> > yems bluepearlhotel # ls
>> > blog  bluepearlhotel  event  gallery  home  images  manage.py  media
>> > static
>> > yems bluepearlhotel #
>> >
>> >
>> > cd /etc/apcahe2/sites-available
>> >
>> >  yems sites-available # ls
>> > 000-default.conf  bluepearlhotel.conf  default-ssl.conf  testsite.com
>> > yems sites-available #
>> >
>>
>> The config you are using here is testsite.com or bluepearlhotel.conf ?
>> Recently, apache changed their default config to only look for files
>> ending in .conf inside sites-available, iirc, so if your config is in
>> testsite.com, maybe its not reading your config at all.
>>
>> >
>> > VirtualHost *:80>
>> > WSGIScriptAlias / /home/yems/bluepearlhotel.wsgi
>> >
>> > ServerName  bluepearlhotel.com
>> >
>> > Alias /static /var/www/bluepearlhotel/static/
>> >
>> > 
>> > Order allow,deny
>> > Allow from all
>> > 
>> >
>> > 
>> > 
>> >
>> > Require all granted
>> > 
>> > 
>> >
>>
>> That *looks* okay. Can you add a couple lines for log files, and then
>> check those files to see if you get anything in the logs that maybe
>> helpful? Like this:
>>
>>   ErrorLog /var/log/apache2/bluepearlhotel.com_error.log
>>   CustomLog /var/log/apache2/bluepearlhotel.com_access.log combined
>>
>> Also, your /static alias seems off? Where exactly are your project
>> files? If your project folder is /home/yems/var/www/bluepearlhotel
>> your static path should probably be something like
>> /home/yems/var/www/bluepearlhotel/static or so?
>>
>> Can you paste output of the command 'pwd' inside your project folder?
>>
>> >
>> >
>> > yems@yems ~ $ ls
>> > bluepearlhotel.wsgi
>> >
>> > import os
>> > import sys
>> > sys.path = ['home/home/var/www/bluepearlhotel'] + sys.path
>> > os.environ['DJANGO_SETTINGS_MODULE'] = 'bluepearlhotel.settings'
>> > import django.core.handlers.wsgi
>> >
>> > application = django.core.handlers.wsgi.WSGIHandler()
>> >
>> > when i browse
>> >
>> > www.bluepearlhotel.com
>> > it give me an empty page
>> >
>> > Please need help
>> >
>>
>> Again, that *seems* okay, but perhaps you have something weird going
>> on with your paths.
>>
>> I'd check the apache log files, one of two things could happen then:
>>
>> 1> You don't see any errors for bluepearlhotel.com -- in this case,
>> your apache conf is probably not bein

Re: deploying djnago on apache

2014-08-11 Thread Sanjay Bhangar
hey Ngangsia,


On Mon, Aug 11, 2014 at 7:17 PM, ngangsia akumbo  wrote:
> i have these configs
>
> project path
> yems bluepearlhotel # ls
> blog  bluepearlhotel  event  gallery  home  images  manage.py  media  static
> yems bluepearlhotel #
>
>
> cd /etc/apcahe2/sites-available
>
>  yems sites-available # ls
> 000-default.conf  bluepearlhotel.conf  default-ssl.conf  testsite.com
> yems sites-available #
>

The config you are using here is testsite.com or bluepearlhotel.conf ?
Recently, apache changed their default config to only look for files
ending in .conf inside sites-available, iirc, so if your config is in
testsite.com, maybe its not reading your config at all.

>
> VirtualHost *:80>
> WSGIScriptAlias / /home/yems/bluepearlhotel.wsgi
>
> ServerName  bluepearlhotel.com
>
> Alias /static /var/www/bluepearlhotel/static/
>
> 
> Order allow,deny
> Allow from all
> 
>
> 
> 
>
> Require all granted
> 
> 
>

That *looks* okay. Can you add a couple lines for log files, and then
check those files to see if you get anything in the logs that maybe
helpful? Like this:

  ErrorLog /var/log/apache2/bluepearlhotel.com_error.log
  CustomLog /var/log/apache2/bluepearlhotel.com_access.log combined

Also, your /static alias seems off? Where exactly are your project
files? If your project folder is /home/yems/var/www/bluepearlhotel
your static path should probably be something like
/home/yems/var/www/bluepearlhotel/static or so?

Can you paste output of the command 'pwd' inside your project folder?

>
>
> yems@yems ~ $ ls
> bluepearlhotel.wsgi
>
> import os
> import sys
> sys.path = ['home/home/var/www/bluepearlhotel'] + sys.path
> os.environ['DJANGO_SETTINGS_MODULE'] = 'bluepearlhotel.settings'
> import django.core.handlers.wsgi
>
> application = django.core.handlers.wsgi.WSGIHandler()
>
> when i browse
>
> www.bluepearlhotel.com
> it give me an empty page
>
> Please need help
>

Again, that *seems* okay, but perhaps you have something weird going
on with your paths.

I'd check the apache log files, one of two things could happen then:

1> You don't see any errors for bluepearlhotel.com -- in this case,
your apache conf is probably not being read at all. Have you done
a2enmod on the vhost file? Can you check if there is an entry /
symlink inside /etc/apache2/sites-enabled/ (post output of 'ls
/etc/apache2/sites-enabled'). Then, first need to figure out why the
conf files is not being read.

2> If the conf file is being read, you should see some errors. Those
errors should give you some more information about what's going wrong.
Paste those errors here and we can try and help you out.

Don't give up, lets figure this out :P

-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZHhdX3Oe9N%2Bp%2Bd-8BoKVhFdKFkQiHup-HQYVy50Dba6Qw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Admin site doesn't work

2014-06-12 Thread Sanjay Bhangar
Hey Glen,

Hm, whatever it is, is not apparent to me, sorry :/. The only thing I
can think of is possibly inconsistent indentation. Some comments /
questions inline --

On Thu, Jun 12, 2014 at 3:39 AM, Glen J  wrote:
> urls.py:
> from django.conf.urls import patterns, include, url
>
> # Uncomment the next two lines to enable the admin:
>  from django.contrib import admin
>  admin.autodiscover()
>
> urlpatterns = patterns('',
> # Examples:
> # url(r'^$', 'mysite.views.home', name='home'),
> # url(r'^mysite/', include('mysite.foo.urls')),
>
> # Uncomment the admin/doc line below to enable admin documentation:
> # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
>
> # Uncomment the next line to enable the admin:
>  url(r'^admin/', include(admin.site.urls)),
> )
>
>
> settings.py:
> # Django settings for mysite project.
>
> DEBUG = True
> TEMPLATE_DEBUG = DEBUG
>
> ADMINS = (
> # ('Your Name', 'your_em...@example.com'),
> )
>
> MANAGERS = ADMINS
>
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add
> 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
> 'NAME': 'mysite',  # Or path to database file if
> using sqlite3.
> # The following settings are not used with sqlite3:
> 'USER': 'glen',
> 'PASSWORD': 'P0rchl1ght!',
> 'HOST': '192.168.122.120',  # Empty for
> localhost through domain sockets or '127.0.0.1' for localhost through TCP.
> 'PORT': '5432',  # Set to empty string for
> default.
> }
> }
>

Please do not post any sort of passwords on a public mailing list -
even though I realize this is for a local database. Please take the
time to quickly sanitize your pastes and remove potentially sensitive
information.

> # Hosts/domain names that are valid for this site; required if DEBUG is
> False
> # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
> ALLOWED_HOSTS = []
>
> # Local time zone for this installation. Choices can be found here:
> # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
> # although not all choices may be available on all operating systems.
> # In a Windows environment this must be set to your system time zone.
> TIME_ZONE = 'America/Chicago'
>
> # Language code for this installation. All choices can be found here:
> # http://www.i18nguy.com/unicode/language-identifiers.html
> LANGUAGE_CODE = 'en-us'
>
> SITE_ID = 1
>
> # If you set this to False, Django will make some optimizations so as not
> # to load the internationalization machinery.
> USE_I18N = True
>
> # If you set this to False, Django will not format dates, numbers and
> # calendars according to the current locale.
> USE_L10N = True
>
> # If you set this to False, Django will not use timezone-aware datetimes.
> USE_TZ = True
>
> # Absolute filesystem path to the directory that will hold user-uploaded
> files.
> # Example: "/var/www/example.com/media/"
> MEDIA_ROOT = ''
>
> # URL that handles the media served from MEDIA_ROOT. Make sure to use a
> # trailing slash.
> # Examples: "http://example.com/media/";, "http://media.example.com/";
> MEDIA_URL = ''
>
> # Absolute path to the directory static files should be collected to.
> # Don't put anything in this directory yourself; store your static files
> # in apps' "static/" subdirectories and in STATICFILES_DIRS.
> # Example: "/var/www/example.com/static/"
> STATIC_ROOT = ''
>
> # URL prefix for static files.
> # Example: "http://example.com/static/";, "http://static.example.com/";
> STATIC_URL = '/static/'
>
> # Additional locations of static files
> STATICFILES_DIRS = (
> # Put strings here, like "/home/html/static" or "C:/www/django/static".
> # Always use forward slashes, even on Windows.
> # Don't forget to use absolute paths, not relative paths.
> )
>
> # List of finder classes that know how to find static files in
> # various locations.
> STATICFILES_FINDERS = (
> 'django.contrib.staticfiles.finders.FileSystemFinder',
> 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
> #'django.contrib.staticfiles.finders.DefaultStorageFinder',
> )
>
> # Make this unique, and don't share it with anybody.
> SECRET_KEY = 'vp4@9d))k610$v1me&e3t1271plyhu1em&*0)2)*06j@aop=u3'
>

Since you have posted this on a public mailing list, please make sure
you change it before pushing to any production environment.

> # List of callables that know how to import templates from various sources.
> TEMPLATE_LOADERS = (
> 'django.template.loaders.filesystem.Loader',
> 'django.template.loaders.app_directories.Loader',
> # 'django.template.loaders.eggs.Loader',
> )
>
> MIDDLEWARE_CLASSES = (
> 'django.middleware.common.CommonMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.con

Re: Admin site doesn't work

2014-06-11 Thread Sanjay Bhangar
On 11 Jun 2014 18:04, "Glen J"  wrote:

> Sanjay,
> Thanks for the reply.  I've tried accessing it various ways using both
> nginx and the included devserver on :8000.  I've done both 127.0.0.1/admin
> and 127.0.0.1/admin/ with the same results.  I can post the contents of
> my urls.py later today when I have access to my machine at home.  FWIW, I
> didn't think the example.com entry was the issue, but at this point I'm
> kinda grasping at straws as I've checked my urls.py and settings.py about a
> hundred times and synced with the database many times as well and don't get
> a hard error, only the django welcome page.
>
>
Hah, it's almost definitely something silly -- have you added
django.contrib.admin to your INSTALLED_APPS in settings.py?

No worries - post your urls.py and other things that maybe relevant when
you have access and we'll try and figure it out.

Cheers,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZH1gKxQ-EegDGGMENFe-vLFF8%2Bd7_Wa81vLPKoK7DQkTg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Admin site doesn't work

2014-06-11 Thread Sanjay Bhangar
hey Glen,

Sorry if this is a silly question - but are you sure you are visiting
/admin on your site?
If you are and still getting this error, can you please paste the
contents of your urls.py

On Wed, Jun 11, 2014 at 4:24 PM, Glen J  wrote:
> I've tried it both on the development server you indicate below as well as
> on a my own web server (nginx using uwsgi) and get the same results.  No
> errors are displayed, simply the welcome page for Django.  Syncdb works fine
> (using Postgresql) and shows output when I do it.  One thing I did spot in
> the database that I wasn't sure of is in my django_site table it has
> example.com.  Not sure why it is there as I never did that.
>

Django creates a default site called example.com. You are expected to
change this to your correct site URL when you deploy. This should not
be the cause of your troubles though - AFAIK, this is only used when
generating full url permalinks, like in RSS feeds, etc.

HTH,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZH9hhaS70V0wdRLKzpj4humi_gaSwnyNBhr6jDeT5UPOQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: backbonejs and django

2014-05-29 Thread Sanjay Bhangar
Hi,

On Thu, May 29, 2014 at 3:07 PM, Eddilbert Macharia  wrote:
> Hi All,
>
> i am using django-tastypie to return django models as json object.
>
> when i run the following code
>
> var org = Backbone.Model.extend({
>
>urlRoot: 'api/orgnanization/',
> });
>
>
> var orgColl=Backbone.Collection.extend({
> model: org,
>urlRoot: 'api/orgnanization/',
>initialize:function(){
>this.fetch();
>console.log(this)
>}
> });
>
> var apiView=Backbone.View.extend({
> el:'.try',
> //template:,
> initialize:function(){
> this.listenTo(this.collection,'reset',this.render)
> },
> //events:{},
> render:function(){
> console.log(this.collection)
> //this.$el.html(this)
> },
> });
>
> var cos=new orgColl()
> new apiView({collection:cos})
>
> i get the following in the chrome console
> r {length: 0, models: Array[0], _byId: Object, constructor: function, model:
> function…}
>
> _byId: Object
> _events: Object
> _listenerId: "l7"
> length: 1
> meta: Object
> models: Array[1]
> __proto__: s
>
>
> but when i look a the network the model is actually fetched from the
> database
>
> meta: {limit:20, next:null, offset:0, previous:null, total_count:3}
>
> limit: 20
> next: null
> offset: 0
> previous: null
> total_count: 3
>
> objects: [{id:1, name:eddmashinc, resource_uri:}, {id:2, name:trive,
> resource_uri:},…]
>
> 0: {id:1, name:eddmashinc, resource_uri:}
>
> id: 1
> name: "eddmashinc"
> resource_uri: ""
>
> 1: {id:2, name:trive, resource_uri:}
>
> id: 2
> name: "trive"
> resource_uri: ""
>
> 2: {id:3, name:mashainc, resource_uri:}
>
> id: 3
> name: "mashainc"
> resource_uri: ""
>
> how do i get this data to display on the backbone view or what im i doing
> wrong ??
>

It seems like the JSON you're getting back from the server puts your
items under a key called 'objects'. A Backbone Collection, by default,
if you just provide it a urlArg, will expect the server to return an
array / list of items.

It does, however, provide a parse method that you can over-ride to
parse the JSON you get from the server and return an array.

So, your Collection definition would look something like:

 var orgColl=Backbone.Collection.extend({
 model: org,
urlRoot: 'api/orgnanization/',
initialize:function(){
this.fetch();
console.log(this)
},
parse: function(response) {
return response.objects;
}
 });

See: http://backbonejs.org/#Collection-parse

All the best,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZGvWUPtqDRyKNYijexTYLmVOCJCY%3DEgP%3DL3Qycaog72%2Bw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Formsets, adding new forms and autocomplete/ajax selects

2014-05-28 Thread Sanjay Bhangar
hey Lachlan,

So this had driven me a bit crazy some years ago ..

On Wed, May 28, 2014 at 8:42 AM, Lachlan Musicman  wrote:
> Hola,
>
> I am trying to get two different "extras" to work.
>
> I have a form with an inline_formset, which I would like to be able to
> add multiple formsets of on the fly.
>
> Each of those formsets has another FK to a model with a very large
> dataset, so I would also like to implement some sort of
> autocomplete/ajax/select2/typeahead solution to prevent an unusably
> large select
>

I had two additional extras :):

i> The FK could also be an m2m that should be handled by select2.

ii> There should also be an Add + button next to the select2 to add a
new instance, which opens up a pop-up to add a new item, like it does
in the Django admin.

And then I needed this on a whole bunch of models / forms, so I needed
it abstracted / generalized in some way. Unfortunately, the solution I
came up with involves some ugly hacks, so I'm slightly embarassed by
it, haha - its also for a much older version of Django, etc. (1.3,
iirc).

However, I still think this is a really kick-ass and useful thing to
be able to do simply - I'd be happy to try and catch up with you
off-list (which we've been meaning to do anyways, ha!) and see if we
can have some fun rolling a little django app for this or so.

> Here is my basic set up.
>
> models.py
> 
> class PartNumber(models.Model):
> name = models.CharField("Description", max_length=100)
> supplier_part_number = models.CharField(max_length=30,
> unique=True, blank=True, null=True)
>
> class PurchaseOrder(models.Model):
> po_number = models.CharField('PO number', max_length=10, unique=True)
> ordered_date = models.DateField(default=today)
>
> class PurchaseOrderPart(models.Model):
> part_number = models.ForeignKey(PartNumber, related_name='purchases')
> po_number = models.ForeignKey(PurchaseOrder, related_name='partslist')
> delivery_date = models.DateField(null=True, blank=True)
> qty_ordered = models.IntegerField('Quantity
> ordered',validators=[MinValueValidator(1)])
> cost = models.DecimalField('Unit Cost',
> max_digits=10,decimal_places=2,blank=True,null=True)
>
>
> forms.py
> -
>
> class PurchaseOrderPartForm(forms.ModelForm):
> class Meta:
>   fields = ('part_numbers', 'delivery_date', 'qty_ordered', 'cost')
>   model = PurchaseOrderPart
>   widgets={
> 'part_numbers': forms.Select(attrs={'class':'form-control'}),
> 'delivery_date': CalendarWidget(attrs={'class':'input-append
> form-control'}),
> 'qty_ordered': forms.NumberInput(attrs={'class':'form-control'}),
> 'cost': forms.NumberInput(attrs={'class':'form-control'}),
> }
>
> POPartFormset = inlineformset_factory(PurchaseOrder,
> PurchaseOrderPart, form=PurchaseOrderPartForm, extra=1,
> can_delete=True)
>
>
> I have successfully implemented jquery.formset.js (
> https://github.com/elo80ka/django-dynamic-formset ) to create "add"
> and "remove" buttons - this allows for a variable number of
> PurchaseOrderParts on a PurchaseOrder.
>
>
> When I then implemented django-select2 I was mostly successful, except
> for one problem - the way that django-select2 implements field is by
> adding some js on render.
>
> Since the jquery.formset.js was creating forms on the fly, any
> formsets added via it's add button did not have the required
> django-select2 container, and hence had no widget at all.
>
> jquery.formset.js has an "added" function that allows for something
> like this, but then I would need to glue it all together and it
> doesn't seem clean enough.
>

So, I used a similar approach - jquery.formset.js and select2. What I
did was I created a little jquery plugin / wrapper around select2 to
be able to instantiate it with a simple call to like
$('#select_field_id_foo').mySelect2();. I then also created a custom
widget for the autocompletes, which would ensure their custom options
were in the html to be read by the plugin.

So, this is the custom widget class I made:
http://code.camputer.org/itf/annotate/head%3A/itf/app/forms.py#L42

This is its template:
http://code.camputer.org/itf/annotate/head%3A/itf/templates/formwidgets/select2.html

Then I can simply instantiate the widget in my form definition like so:

group = forms.ModelChoiceField(TheatreGroup.objects.all(),
widget=AutocompleteAddWidget(model_class=TheatreGroup))
See for eg: 
http://code.camputer.org/itf/annotate/head%3A/itf/itfprofiles/forms.py#L129

So far so good. Where the ugly hackery lies is the javascript - as you
mention, to work around the problem of instantiating when adding a new
formset and other problems when using the Django Admin JS for the
pop-up forms, I landed up hacking in the jquery.formset.js code
itself, which I'm not proud of. I think this can probably be
accomplished cleaner using the 'added' callback or so, as you mention
(and make your single point of entry / instantiation a custom jquery

Re: Opinion needed for a BookMarker project - Regarding CSRF token

2014-05-12 Thread Sanjay Bhangar
Hi Aseem,

On Mon, May 12, 2014 at 11:25 PM, Aseem Bansal  wrote:
> I am new to Django and am learning it baically because I wanted to create a
> BookMarker project. A project for managing bookmarks. For this I am going to
> create a UI through Django and a JavaScript for sending the URLs to the app.
> There is a problem of CSRF token in Django. I was able to do a dummy POST
> request  by sending the CSRF token hard-coded as a parameter. But I do not
> understand how the CSRF tokens are generated. Can I just hard-code them? I
> don't think that it should be possible otherwise there is no point of having
> it in the first place. Should I consider turning off the CSRF middleware as
> this is just local machine or should I keep it as a best practice and find a
> way to generate the CSRF token in my JavaScript? That would suck but I am
> out of opinions.
>

To use the csrf token and send it along with AJAX requests made in
javascript, refer
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax .

It should be fairly straightforward following steps there. Let know if
anything is unclear or does not work.

> Also when you are doing Django projects and need to deal with JS then what
> do you do? I mean is there an alternative for JS in Django?
>
> If any of these questions doesn't make any sense please tell and I will try
> to improve these. Just tell what doesn't make sense.
>

Hope the documentation makes sense, otherwise just search for "django
ajax csrf token" or so and you should find quite a lot of examples
online :)

All the best.
-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZEBpqkCwRaJKy%2BJVZCQY2ORAQNZr1fRjgaBx9UnnzZPeg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Question on a resembling function on truncatewords

2014-04-12 Thread Sanjay Bhangar
On Sat, Apr 12, 2014 at 7:50 PM, Camilo Torres  wrote:
> On Saturday, April 12, 2014 1:10:34 AM UTC-4:30, Kimitaka wrote:
>>
>> I wrote the function in my Product class in my models.py:
>> class Product(models.Model):
>> title = models.CharField(max_length=220)
>> description = models.CharField(max_length=3000, null=True, blank=True)
>> price = models.DecimalField(max_digits=1000, decimal_places=2, null=True,
>> blank=True)
>> slug = models.SlugField()
>> timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
>> updated = models.DateTimeField(auto_now_add=True, auto_now=False)
>> active = models.BooleanField(default=True)
>>
>> def __unicode__(self):
>> return self.title
>> class Meta:
>> ordering = ['title',]
>>
>> def shorten_words(self):
>> if len(self.description) > 20:
>> print self.desciption[0:20]
>> else:
>> print self.desciption
>>
>>
>> and I added a code in my products.html page:
>> {{ product.description.shorten_words() }}
>
> Hello,
>
> Should it be?:
> {{ product.shorten_words }}
>

This. And in the desciption() method, you want to do "return
self.description[0:20] and not print..." - print will just print the
output in the console at that point - you need to "return" the value
from the method.

So:

def shorten_words(self):
if len(self.description) > 20:
return self.desciption[0:20]
else:
return self.desciption

That, and {{ product.shorten_words }} in your template should do the trick.

All the best,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZFEoBh8fzusWjAdbSdGQj9hmJSHKS8YUTZVJE1obPZmnA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to call url and get json data

2013-10-21 Thread Sanjay Bhangar
Mahantesh,

On Mon, Oct 21, 2013 at 3:48 PM, Mahantesh U  wrote:
> Hi,
>
>How to call the below url in django in views file:
>
>
>
> http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=O-lzp4Hyqp8&format=json
>
>   The above api returns json data which further i need to use and fill those
> in html file.
>
>
> HttpResponse('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=O-lzp4Hyqp8&format=json')
>
>  Is this correct way to call to get json data?
>

No.

Think about what you need to do - you need to fetch this JSON in your
view, process it, and then send those variables as "context" to your
template to be able to render them.

So, first, you need to fetch the JSON data in your python view. This
can be accomplished with something like:

import urllib2
json_string = 
urllib2.urlopen('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=O-lzp4Hyqp8&format=json').read()

^ this will store the results of that webpage into a variable called
"json_string". You can also look at the "requests" library to fetch
data from URLs in python, but urllib2 should be fine as well.

Then, we need to convert the json_string into a python dict:

import json
data = json.loads(json_string)

Now you will have a python dict with all the data in a variable called "data"

Now you can process this data, add other context data that you need,
etc. and finally render the template with something like:

from django.shortcuts import render
return render(request, "template_name.html", data)

Then in your template you can output like {{ author_name }}, {{
author_url }}, etc. as needed.

Hope that makes sense.
All the best,
Sanjay


> Thanks in advance
>
>
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/10216c68-f54f-4ea9-9e9c-6d0d03227bc0%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZFrBP8cuLxupFArEt1bXT7urb%3DNqtrFVpcxGsWev46-AA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Geo support with Django Rest Framework

2013-10-21 Thread Sanjay Bhangar
Hi Rok,

Thank you so much for the reply and code snippets. I think I managed
to implement the stuff I needed using the hooks provided by
Django-Rest-Framework -- not 100% sure why I picked that over Tastypie
for this, but its treating me well, so I'll stick to it ..

Since we're sharing code :), this is what I came up with to handle
filtering by bbox and distance to a point -- this is obviously first
draft code, but it seemed to work quite well --

class VirtualCacheList(generics.ListAPIView):
serializer_class = VirtualCacheListSerializer

def get_queryset(self):
qset = VirtualCache.objects.all()
params = self.request.QUERY_PARAMS
username = params.get('username', None)
if username is not None:
qset = qset.filter(user__username=username)
bbox_string = params.get('bbox', None)
if bbox_string:
bbox = [float(b) for b in bbox_string.split(",")]
qset = qset.filter(point__within=bbox)
distance = params.get("distance", None)
lat = params.get("lat", None)
lon = params.get("lon", None)
if distance and lat and lon:
lat = float(lat)
lon = float(lon)
distance = int(distance)
point = Point(lat, lon)
qset = qset.filter(point__distance_lte=(point,
D(m=distance),)).distance(point, field_name='point')
qset = qset.order_by('distance')
return qset

I probably want to implement that as a Filter class or so - I will
look at the django-restframework-gis packages for an idea of the
cleanest way to do it, but it's super nice how easy these frame-works
have made it to get a fully functional api with docs and everything.
I'll probably bug the people over at the Django Rest Framework mailing
list if I run into issues, but so far I found ways to do everything I
needed to do - just the GeoJSON serialization seemed awkward, but I
see there's a package for that, so I seem to be sorted.

Thanks again,
Sanjay




On Mon, Oct 21, 2013 at 3:58 PM, rok  wrote:
> I'm using tastypie for the REST functionality which I have extended so that
> geolocation can be used as a filter, e.g.:
>
> class TestResource(ModelResource):
>
> class Meta:
> queryset = Event.objects.all()
> resource_name='test'
> ordering = ['date_from']
>
> def get_object_list(self, request):
> _items = super(TestResource, self).get_object_list(request).all()
> if request.method == 'GET':
> if 'lat' in request.GET and 'lng' in request.GET and 'rad' in
> request.GET:
> _lat = float(request.GET['lat'].strip())
> _lng = float(request.GET['lng'].strip())
> self._current_location = Point(_lat, _lng)
> _items=_items.filter(
>
> Q(city__coordinates__distance_lte=(self._current_location,
> float(request.GET['rad'].strip())*1000))
> )
> return _items
>
> def dehydrate(self, bundle):
> bundle.data['lat'] = bundle.obj.city.coordinates.x
> bundle.data['lng'] = bundle.obj.city.coordinates.y
> bundle.data['distance'] =
> bundle.obj.city.coordinates.distance(self._current_location) * 100
> return bundle
>
> Hope this helps, if you want I can include more code details...
> Rok
>
>
> On Sunday, October 20, 2013 4:06:26 PM UTC+2, Sanjay Bhangar wrote:
>>
>> Hi all,
>>
>> I'm developing an app using GeoDjango that requires me to create an
>> API. Ideally, I would output GeoJSON at various API end-points and
>> support a few geo-queries like "within bounding box", etc.
>>
>> I have done something similar before without Django Rest Framework and
>> just writing vanilla views, but I thought it would be nice to make use
>> of a lot of the niceties that the framework provides.
>>
>> Just wondering if something has dealt with serialization /
>> deserialization of geo models using Django Rest Framework and has any
>> pointers / code to share (or advice on why this is a bad idea :)). A
>> fair amount of internet searching did not turn up anything for me.
>>
>> Looking through the docs, it seems like there are reasonable hooks to
>> write custom Serializer, Renderer and Filter classes - just wondering
>> if someone has gone down this road before - and also, potentially, if
>> someone else may find this useful and then I could think about making
>> whatever solution I come up with more generalizable ..
>>
>> Also, if there's a b

Re: Geo support with Django Rest Framework

2013-10-21 Thread Sanjay Bhangar
Hey Tom,

On Mon, Oct 21, 2013 at 1:50 PM, Tom Christie  wrote:
> Hi Sanjay,
>
> I would take a look at these two repos:
>
> https://github.com/dmeehan/django-rest-framework-gis
> https://github.com/mjumbewu/django-rest-framework-gis
>

This is EXACTLY what I was looking for. Obviously, I need to work on
my internet searching skills :/

Turns out things were fairly simple to do and I implemented what I
needed anyways, but this is obviously a bit cleaner so I will plug in
one of these. Essentially, a GeoJSON Serializer is what I was looking
for, and these give me exactly that :)

> You might also try searching the REST framework issue list as it's likely
> either or both of these were at some point discussed there.
> Also try searching the archives for the REST framework discussion group,
> here:
>
> https://groups.google.com/forum/#!forum/django-rest-framework
>

Yea, I saw their google forum link after I sent my mail here as well.
My apologies for not hunting enough before asking here.

Thanks again, and if folks from the django rest framework team are
reading this - you guys rock, it's been a pleasure to get into.

> Hope that helps!
>

Tremendously!
Thanks,
Sanjay


>   Tom
>
> On Sunday, 20 October 2013 15:06:26 UTC+1, Sanjay Bhangar wrote:
>>
>> Hi all,
>>
>> I'm developing an app using GeoDjango that requires me to create an
>> API. Ideally, I would output GeoJSON at various API end-points and
>> support a few geo-queries like "within bounding box", etc.
>>
>> I have done something similar before without Django Rest Framework and
>> just writing vanilla views, but I thought it would be nice to make use
>> of a lot of the niceties that the framework provides.
>>
>> Just wondering if something has dealt with serialization /
>> deserialization of geo models using Django Rest Framework and has any
>> pointers / code to share (or advice on why this is a bad idea :)). A
>> fair amount of internet searching did not turn up anything for me.
>>
>> Looking through the docs, it seems like there are reasonable hooks to
>> write custom Serializer, Renderer and Filter classes - just wondering
>> if someone has gone down this road before - and also, potentially, if
>> someone else may find this useful and then I could think about making
>> whatever solution I come up with more generalizable ..
>>
>> Also, if there's a better place to discuss this, please let me know :)
>>
>> Thanks,
>> Sanjay
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/71f87a56-b0ff-4ff7-9d4c-b47f4bb525f3%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZHJ8WUhYVcitLkMM3DQa1GpoD6-%2BgG8%2BkfsFGFBq7NXzA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Geo support with Django Rest Framework

2013-10-20 Thread Sanjay Bhangar
Hi all,

I'm developing an app using GeoDjango that requires me to create an
API. Ideally, I would output GeoJSON at various API end-points and
support a few geo-queries like "within bounding box", etc.

I have done something similar before without Django Rest Framework and
just writing vanilla views, but I thought it would be nice to make use
of a lot of the niceties that the framework provides.

Just wondering if something has dealt with serialization /
deserialization of geo models using Django Rest Framework and has any
pointers / code to share (or advice on why this is a bad idea :)). A
fair amount of internet searching did not turn up anything for me.

Looking through the docs, it seems like there are reasonable hooks to
write custom Serializer, Renderer and Filter classes - just wondering
if someone has gone down this road before - and also, potentially, if
someone else may find this useful and then I could think about making
whatever solution I come up with more generalizable ..

Also, if there's a better place to discuss this, please let me know :)

Thanks,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZGWuikBcD1AqqSWwtE0a-wF0PoGt0qXrA5nRPbcDYFHyw%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Image browsing in django

2013-10-16 Thread Sanjay Bhangar
Harjot,

It is enctype='multipart/form-data' and not encoding='multipart/form-data'

Hope that helps - all the best,
Sanjay

On Wed, Oct 16, 2013 at 10:11 AM, Harjot Mann  wrote:
> On Mon, Oct 14, 2013 at 9:48 PM, Harjot Mann  wrote:
>> I have not done anything special in views..it just contains a simple
>> form saving code.
>> Should I need to do anything there?
>
>
> Please reply. I am waiting :(
>
> --
> Harjot Kaur Mann
> Blog: http://harjotmann.wordpress.com/
> Daily Dairy: http://harjotmann.wordpress.com/daily-diary/
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/CAB0GQhDC1MstEPp3LD_zgdAS0QMsoL3p-2pO3HhRvu6OPW14mQ%40mail.gmail.com.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAG3W7ZESsGnKdaC3_oSjk2JwtG-eriR_HKLbS5G29BEcVWnhuQ%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Restrict access to user-uploaded files to authorized users

2013-09-26 Thread Sanjay Bhangar
On Thu, Sep 26, 2013 at 6:54 AM, m1chael  wrote:

> I think Xsendfile is what you want
>
>
+1. I know the OP said it maybe hard to install apache modules, but I would
really try and check with the host, etc. - it should ideally not be such an
issue to install mod-xsendfile, and this is exactly the use-case that it
facilitates .. I would strongly recommend reading up on XSendfile and
seeing if implementation is feasible, because it's really the best,
non-hacky way to do this ..

Any-how, all the best :-)
-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Middleware Causing OperationalError: (2006, 'MySQL server has gone away')

2013-09-10 Thread Sanjay Bhangar
On Tue, Sep 10, 2013 at 7:50 PM, Paul Childs  wrote:

> I went as far as to reboot my machine.
> I tried the view and it worked but then my other view started exhibiting
> the same error message.
>
>
Not sure if this helps, but I saw this once recently on a colleague's
windows machine. I'm going to see if we can reproduce it and try and add
more details, but I do remember it being hard to reproduce, so we let it
go. Sorry, not very helpful, but just wanted to let you know that it seems
like you may not be the only one who's run into this. Hopefully I'll be
able to reproduce the error with the colleague and get back - if it helps,
I'm fairly certain it is windows-specific, of course, I cannot be sure
(same project with same code runs without problem on my ubuntu machine).

Please do post if you find a solution, of course :-)

thanks,
Sanjay



> On Tuesday, September 10, 2013 11:01:42 AM UTC-3, Paul Childs wrote:
>>
>> Environment: Django 1.4, MySQL 5.5.33
>>
>> In one of my views I am consistently getting  a MySQL
>> error: OperationalError: (2006, 'MySQL server has gone away')
>>
>> Traceback (most recent call last):
>>   File "C:\Python26\Lib\wsgiref\**handlers.py", line 93, in run
>> self.result = application(self.environ, self.start_response)
>>   File "C:\virtual_env\sitar_env2\**lib\site-packages\django\**
>> contrib\staticfiles\handlers.**py", line 67, in __call__
>> return self.application(environ, start_response)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\core\**handlers\wsgi.py",
>> line 241, in __call__
>> response = self.get_response(request)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\core\**handlers\base.py",
>> line 191, in get_response
>> signals.got_request_exception.**send(sender=self.__class__,
>> request=request)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\**dispatch\dispatcher.py",
>> line 172, in send
>> response = receiver(signal=self, sender=sender, **named)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\db\__**init__.py",
>> line 62, in _rollback_on_exception
>> transaction.rollback_unless_**managed(using=conn)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\db\**transaction.py",
>> line 129, in rollback_unless_managed
>> connection.rollback_unless_**managed()
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\db\**backends\__init__.py",
>> line 214, in rollback_unless_managed
>> self._rollback()
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\db\**backends\mysql\base.py",
>> line 404, in _rollback
>> BaseDatabaseWrapper._rollback(**self)
>>   File 
>> "C:\virtual_env\sitar_env2\**lib\site-packages\django\db\**backends\__init__.py",
>> line 54, in _rollback
>> return self.connection.rollback()
>> OperationalError: (2006, 'MySQL server has gone away')
>> [10/Sep/2013 10:29:11] "GET /trending/res_entry/pim/0/ HTTP/1.1" 500 59
>>
>> Looking at the stack trace it didn't look like the problem was with my
>> view.
>>
>> I traced through the code and the error occurs in one of the middleware
>> methods that is executed when I redirect to another page:
>>
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(67)**
>> res_management()
>> -> q_ress = Res.objects.filter(**maintenance_phase=maintenance_**phase)
>>    Hitting the DB OK here
>> (Pdb)
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(69)**
>> res_management()
>> -> res_list = fmas.get_ress(q_ress, mode, maintenance_phase)
>> (Pdb)
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(70)**
>> res_management()
>> -> request.session['my_res_list'] = res_list
>> (Pdb)
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(71)**
>> res_management()
>> -> return redirect('/trending/res_{0}/{**1}/1/'.format(mode,
>> (Pdb)
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(72)**
>> res_management()
>> -> maintenance_phase))
>> (Pdb)
>> --Return--
>> > c:\virtual_env\sitar_env2\**cissimp\trending\views.py(72)**
>> res_management()->
>> -> maintenance_phase))
>> (Pdb)
>> > c:\virtual_env\sitar_env2\lib\**site-packages\django\core\**
>> handlers\base.py(124)get_**response()
>> -> if response is None:
>> (Pdb) response is None
>> False
>> (Pdb) n
>> > c:\virtual_env\sitar_env2\lib\**site-packages\django\core\**
>> handlers\base.py(133)get_**response()
>> -> if hasattr(response, 'render') and callable(response.render):
>> (Pdb) l
>> 128 view_name = callback.__class__.__name__ +
>> '.__call__' # If it's a class
>> 129 raise ValueError("The view %s.%s didn't
>> return an HttpResponse object." % (callback.__module__, view_name))
>> 130
>> 131 # If the response supports deferred rendering,
>> apply template
>> 132 # response middleware and the render the response
>> 133  -> if hasattr(response, 'render') and
>> callab

Re: PDF generator in Django

2013-08-05 Thread Sanjay Bhangar
On Mon, Aug 5, 2013 at 12:27 PM, Nigel Legg  wrote:

> I'm currently looking at ReportLab following
> https://docs.djangoproject.com/en/dev/howto/outputting-pdf/ - but open to
> suggestions.
>
>
i have used wkhtmltopdf for this .. not a django / python tool per se, but
I could make my pages as normal with a template, etc. and then point
wkhtmltopdf to the URL and it generates pretty clean PDFs .. I found it
easier to generate html / css and then have another tool take care of
converting that to a PDF, and wkhtmltopdf worked quite well for that. Your
use-case may vary, but if that seems interesting and you need any help /
clarification, let me know ..

-Sanjay


> Regards,
> Nigel Legg
> 07914 740972
> http://www.trevanianlegg.co.uk
> http://twitter.com/nigellegg
> http://uk.linkedin.com/in/nigellegg
>
>
>
> On 5 August 2013 07:48, navnath gadakh  wrote:
>
>> Which is best tool to generate PDF in python django
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Big Picture?

2013-07-07 Thread Sanjay Bhangar
On Sun, Jul 7, 2013 at 7:05 AM, Amirouche Boubekki <
amirouche.boube...@gmail.com> wrote:

> Hi,
>
> I have a diagram I call big picture, you might find it useful (see
> attachment).
>
> Anything green is most of the time provided by the framework at least it
> is the case in Django.
>
> Anything gray you have to make a choice for.
>
> Anything blue is your code.
>
> Arrows are kind of inspired snakes I'm not sure of the meaning of each of
> them ;)
>
>
>
I normally dislike technical "diagrams", but this is simple and awesome :-)
-- it's a really nice "big picture" and introduction to the different
components that can be hard to visualize in one's head when just getting
started .. do you mind if I use it when introducing people to Django? (with
credit, of course:))

Thanks again!
-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: CSRF verification failed

2013-07-06 Thread Sanjay Bhangar
On Sat, Jul 6, 2013 at 9:38 AM, Kakar Arunachal Service <
kakararunachalserv...@gmail.com> wrote:

> Hello!
> I am getting CSRF verification failed error, even after i added {%
> csrf_token %} tag in the html file.
>
> Here's my html file:
>
> {% extends "base.html" %}
> {% block title %} User Registration {% endblock %}
> {% block head %} User Registration {% endblock %}
> {% block content %}
> 
> {% csrf_token %}
> {{ form.as_p }}
> 
> 
> {% endblock %}
>
> and my views.py:
>
> def register_page(request):
> if request.method == 'POST':
> form = RegisrationForm(request.POST)
> if form.is_valid():
> user = User.objects.create_user(
> username = form.cleaned_data['username'],
> password = form.cleaned_data['password1'],
> email = form.cleaned_data['email']
> )
> return HttpResponseRedirect('/')
> else:
> form = RegisrationForm()
> variables = RequestContext(request, {
> 'form': form
> })
> return render_to_response('registration/register.html',
> variables)
> else:
> return render_to_response('registration/register.html')
>
> else:
  return render_to_response("registration/register.html",
RequestContext(request, {})


> Where am i doing wrong???
>

In your outer else statement, you need to return a RequestContext instance
..

You could also use the 'render' shortcut:
from django.shortcuts import render

.

return render(request, "registration/register.html")

Basically, you need to make sure the template has the context created by
RequestContext, otherwise csrf_token will not be available as a variable on
the template.

Hope that helps,
Sanjay



>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Returning data from view to ajax call

2013-07-02 Thread Sanjay Bhangar
On Tue, Jul 2, 2013 at 4:20 PM, Larry Martell wrote:

> On Tue, Jul 2, 2013 at 5:14 PM, Sanjay Bhangar 
> wrote:
> > On Tue, Jul 2, 2013 at 4:01 PM, Larry Martell 
> > wrote:
> >>
> >> 
> >>
> >> In the browser the response has this:
> >>
> >> HTTP/1.0 200 OK
> >> Date: Tue, 02 Jul 2013 22:53:47 GMT
> >> Server: WSGIServer/0.1 Python/2.7.2
> >> Vary: Cookie
> >> Content-Type: text/plain
> >>
> >> No content. But I verified from pdb that the python code is sending
> >> something in the content when it does this:
> >>
> >> return HttpResponse(content=data, content_type="text/plain", status=200)
> >>
> > try:
> >   return HttpResponse(data, content_type="text/plain", status=200)
> >
> > (no content= ... )
>
> No difference - still no content.
>
> Can you navigate to the page just in the browser (not making an AJAX
request) ? Do you get a response then? What if you substitute data with
"some random string" ?

-Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Returning data from view to ajax call

2013-07-02 Thread Sanjay Bhangar
On Tue, Jul 2, 2013 at 4:01 PM, Larry Martell wrote:

> 
>
In the browser the response has this:
>
> HTTP/1.0 200 OK
> Date: Tue, 02 Jul 2013 22:53:47 GMT
> Server: WSGIServer/0.1 Python/2.7.2
> Vary: Cookie
> Content-Type: text/plain
>
> No content. But I verified from pdb that the python code is sending
> something in the content when it does this:
>
> return HttpResponse(content=data, content_type="text/plain", status=200)
>
> try:
  return HttpResponse(data, content_type="text/plain", status=200)

(no content= ... )

best've luck,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Returning data from view to ajax call

2013-07-02 Thread Sanjay Bhangar
On Tue, Jul 2, 2013 at 3:37 PM, Larry Martell wrote:

> On Tue, Jul 2, 2013 at 4:24 PM, Sithembewena Lloyd Dube
>  wrote:
> > What data format is your view returning? Django views return HTTP
> response
> > objects (by default, at least) - although Python lists (and other Python
> > collections?) should work when passed into a view in its context (I have
> > found Django querysets to be an exception).
> >
> > AJAX is Asynchronous Javascript, so I presume that an AJAX call would
> expect
> > something like JSON output from a callable. I guess with some pain one
> could
> > get Javascript to ingest Django querysets? I couldn't think of a sensible
> > reason to do so - and I stand to be corrected.
>
> I want to return a string. I've never done this before. I've been
> reading examples on the web and I came up with this:
>
> $.ajax({
> url: 'permalink/',
> type: 'GET',
> data: {
> report: "{% url motor.core.reports.views.view
> the_controller.app.name the_controller.get_name %}",
> params: "{{ the_report.params_string }}"
> },
> dataType: 'json',
> success: function (data) {
> setTimeout(function () {
> alert(data);
> }, 0);
> }
> });
>
>
You shouldn't need the setTimeout in your success call - just
function(data) { alert(data); } .. should be okay.

In my function I first tried returning just the string, but that was
> causing a 500 error. Then I tried this:
>
> return HttpResponse(content=data, content_type="text/plain", status=201)
>
> try status=200 ?


> I don't get the error, but the ajax success function does not seem to be
> called.
>
> An invaluable tool here is to use the Developer Tools in the browser to
inspect AJAX requests made and their responses .. in Chrome, open Developer
Tools (f12 is a handy shortcut for this) and go to the Network Tab, and
then you should see the Network Requests show up, and be able to examine
what was returned, etc..

Hope that helps,
Sanjay


> >
> >
> > On Wed, Jul 3, 2013 at 12:06 AM, Larry Martell 
> > wrote:
> >>
> >> I'm invoking a view from an ajax call and I want to return data. But
> >> the browser interpertates the return as a 500 (internal sever error)
> >> and my ajax success function does not get called. How can I return a
> >> successful status (like a 201) and also return data?
> >>
> >> --
> >> You received this message because you are subscribed to the Google
> Groups
> >> "Django users" group.
> >> To unsubscribe from this group and stop receiving emails from it, send
> an
> >> email to django-users+unsubscr...@googlegroups.com.
> >> To post to this group, send email to django-users@googlegroups.com.
> >> Visit this group at http://groups.google.com/group/django-users.
> >> For more options, visit https://groups.google.com/groups/opt_out.
> >>
> >>
> >
> >
> >
> > --
> > Regards,
> > Sithu Lloyd Dube
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To unsubscribe from this group and stop receiving emails from it, send an
> > email to django-users+unsubscr...@googlegroups.com.
> > To post to this group, send email to django-users@googlegroups.com.
> > Visit this group at http://groups.google.com/group/django-users.
> > For more options, visit https://groups.google.com/groups/opt_out.
> >
> >
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Django 1.6 doesn't install via pip

2013-07-01 Thread Sanjay Bhangar
On Sun, Jun 30, 2013 at 8:00 PM, Lachlan Musicman  wrote:

> Hola,
>
> I read the release notes, and tried to install 1.6. I encountered this
> error:
>
> $ pip install Django==1.6b1
> Downloading/unpacking Django==1.6b1
>   Could not find a version that satisfies the requirement
> Django==1.6b1 (from versions: 1.2.6, 1.3.6, 1.2.7, 1.2.3, 1.2.4,
> 1.4.4, 1.3.3, 1.2.1, 1.3.4, 1.2.2, 1.5, 1.3, 1.4.5, 1.3.1, 1.1.3,
> 1.3.5, 1.2.5, 1.1.4, 1.2, 1.3.2, 1.3.7, 1.4.3, 1.4.1, 1.5.1, 1.4.2,
> 1.4)
> No distributions matching the version for Django==1.6b1
>
>
Hey L :),

fwiw, this should work if you want to install via pip currently:
pip install -e git+https://github.com/django/django.git@1.6b1#egg=django

The docs [0] do say that pip install django==1.6b1 should work though, so
I'm guessing someone is going to push to pypi soon :-)

Cheers,
Sanjay

[0] https://www.djangoproject.com/download/


>
> I presume that the 1.6 alpha/beta hasn't been pushed to pypi yet?
>
> cheers
> L.
>
> --
> We are like a drunk blundering through a crowd of pickpockets. That we
> are not poor and naked already is a testament to either the goodness
> of humanity or the ineptitude of the criminal class.
>
> http://techcrunch.com/2013/06/08/we-asked-for-this/
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Get Form from string?

2013-07-01 Thread Sanjay Bhangar
Hey MacVictor,

So when I needed to do something similar, I landed up hard-coding a dict
with form-name -> form-class in my model definition. Honestly, there is
probably a better way to do it, but that worked fine for my use-case,
though it did feel slightly "not right". Any-how, fwiw, I did something
like:

from forms import FormA, FormB, FormC
class Foo(models.Model):
  ...
  forms = {
'SomeFormA': FormA,
'SomeFormB': FormB,
'SomeFormC': FormC
  }

And then in your view, something like:
form = model.forms[] .. etc..

I'm guessing from your email that what you need is something similar, and
perhaps someone from the list has a better idea than the above to do it ..

Hope that helps, though ..

All the best,
Sanjay


On Sun, Jun 30, 2013 at 1:59 AM, MacVictor  wrote:

> I try in view get the form by name.
> Example:
> this is my url:
>
> /some-url/MyForm/
>
> url(r'^/some-url/(?P[a-zA-Z0-9]+)/', 'my_view', name='my-wiev'),
>
>
> and my view:
>
> def my_view(request, form_name):
> form = how_get_form_name(form_name)
> response = {}
> response['my_form'] = form
> return render_to_response('request/window.html', response)
>
>
> I have create uniwersal view, get my form and send to template. Why form?
> Because my model has more Forms and I want to select which forms.
>
>
>
> W dniu piątek, 28 czerwca 2013 23:06:15 UTC+2 użytkownik yeswanth nadella
> napisał:
>
>> I am afraid, I did not understand your question. Are you trying to
>> generate a form based on your model/ models?
>>
>> On Friday, June 28, 2013 3:23:00 PM UTC-5, MacVictor wrote:
>>>
>>> and how to get only Form (not ModelForm) use string name?
>>>
>>> W dniu piątek, 28 czerwca 2013 22:09:41 UTC+2 użytkownik MacVictor
>>> napisał:

 get the model by string i use:

 from django.db.models.loading import get_model
 def get_model(self, app_label, model_name, seed_cache=True):

 how to get ModelForm by string?

 i try used:

 modelforms = forms.ModelForm.__subclasses__**()

 def get_form(form):
 try:
 for model_form in modelforms:
 try:
 if model_form.Meta.form == form:
 return model_form
 except AttributeError:
 continue
 except IndexError:
 print "Does not exist Model Forms for the object"

 but I must import the form in which I will seek appropriate by name!

>>>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: wsgi + XAMMP

2013-06-26 Thread Sanjay Bhangar
Hi Timur,

If you are using this to test / develop on your local machine, you should
not need XAMPP. Django comes with its own testing development server, so
you should not need Apache if you are using this to test / develop locally.

The way I have done this on Windows is just install the python binaries ..
are you sure your project requires 2.6 and will not work on 2.7? I would
recommend going with 2.7, but you should find 2.6 binaries as well. Install
them on your machine. Then install python-setuptools. Once you have that,
you can 'easy_install pip' on the cmd shell . Then, you can 'pip install
django==1.3' and pip install whatever other dependencies you need for your
project. If you feel like doing things the right way, read about virtualenv
and install virtualenv and install all this inside a virtualenv. You may
need to install some of the packages that you need via the binaries / exe
files available, for eg., the python-mysql connector. Just google for these
things and you should find install instructions.

Once you have your dependencies setup, you should just be able to cd into
the code folder and do 'python manage.py runserver' and have your local
development server running at http://localhost:8000 or so.

Is there a particular reason you need WSGI + Apache for your local
development setup? I reckon this maybe a bit complicated on Windows, but
again, that's possibly because I've never needed to do that :). If you're
just using it for development / testing though, I'd recommend just using
the django dev-server.

I have found python / django compatibility with windows to be quite good,
and if your project doesn't have any extreme requirements in terms of
dependencies, you should be fine pip installing most dependencies, and for
ones that don't pip install, you should find .exe installers with a quick
google.

Hope that helps,
Sanjay


On Wed, Jun 26, 2013 at 9:58 PM, Timur Kartaev wrote:

> Yes, I am trying to use django on local machine and want to use MySQL. If
> you have any other recommendation what I can install instead of XAMPP
> please write.
> среда, 26 июня 2013 г., 23:45:43 UTC+7 пользователь Charly Román написал:
>>
>> 2013/6/26 Hélio Miranda :
>> > what is your doubt yourself?
>> > Why not use the most current versions?
>> >
>> > For example django 1.5.1 python 2.7?
>> >
>>
>> And why XAMPP? Are you trying to use django on local machine?
>>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: An easy way to integrate Jcrop in Django's admin?

2013-06-26 Thread Sanjay Bhangar
On Wed, Jun 26, 2013 at 3:48 AM, thoms  wrote:

> An easy way to integrate Jcrop in Django's admin?
>
> Hello,
>
> I'm new in the Django world, and I have a question regarding image
> resizing.
>
> What I'm trying to do:
> 1) A user upload an image in the admin
> 2) He is shown the Jcrop interface to crop the image, and submit the form
> 3) The original image and the cropped one are stored in imagefields
>
> I know there are some open source projects that are doing this
> (django-cropper or django-image-cropping) but I want to do it by myself.
>
> I have a PHP background, where this kind of things where really easy to
> do. But it seems that it's a lot more difficult to achieve in Django, which
> makes me doubt about my idea to learn Django...
>
> Any advice on how to do this in a simple way?
>

I have used https://pypi.python.org/pypi/django-image-cropping/0.5 to offer
image cropping functionality in the admin and it has worked quite well for
me.

Hope that helps,
Sanjay

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Help with integration of bootstrap and Django 1.4.3

2013-04-20 Thread Sanjay Bhangar
On Sat, Apr 20, 2013 at 10:43 AM, Paras Nath Chaudhary <
opnchaudh...@gmail.com> wrote:

> How I do this is in settings.py:
> PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
> STATIC_ROOT = os.path.join(PROJECT_ROOT, '../static')
> STATIC_URL = '/static/'
> STATICFILES_DIRS = (
> # Put strings here, like "/home/html/static" or "C:/www/django/static".
> # Always use forward slashes, even on Windows.
> # Don't forget to use absolute paths, not relative paths.
> os.path.join(PROJECT_ROOT,'../static/assets'),
> )
>
>
> In template files.
>  
>
>
Shouldn't that be:
 

( /static/ ... instead of static/ ... )

If its missing the initial slash, the link would be relative to the current
page, which would be fine at http://yourdomain.com or
http://yourdomain.com/foo but would break if you were linking from
http://yourdomain.com/foo/bar ..

-Sanjay

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




Re: PostgreSQL on windows 7 (psycopg2 install problem)

2013-04-14 Thread Sanjay Bhangar
On Windows, I'd strongly recommend just installing the pre-compiled
binaries for these sort've things, unless you're experienced with compiling
software / making this sort've thing work on Windows ..

So, install something like
http://www.stickpeople.com/projects/python/win-psycopg/ and then, make sure
your virtualenv is configured to use system-site-packages. (if you are
using the latest virtualenv, you would need to maybe re-create the
virtualenv with "virtualenv --system-site-packages ." .. ) - just google
virtualenv system-site-packages if that does not fully make sense :-)

It's probably "better" to use pip and install it inside your virtualenv,
but on Windows, I could never figure that out :-), and installing the .exe
files and using --system-site-packages seems to work fine for most things
.. it should be fairly rare that you require two different versions of
something like psycopg2 for different projects, so it should not be
problematic to have it installed system-wide ..

All the best,
Sanjay




On Sun, Apr 14, 2013 at 10:17 PM, Serdar Dalgic  wrote:

> On Sun, Apr 14, 2013 at 5:45 PM, Mustafa Tulu 
> wrote:
> > Hi All,
>
> Hi;
>
> >
> > When I try to install the package into my virtualenv in pycharm, it
> tries to
> > compile the source into binaries, it fails at linking stage, giving
> errors
> > like:
> >  Creating library build\temp.win32-2.7\Release\psycopg\_psycopg.lib and
> > object build\temp.win32-2.7\Release\psycopg\_psycopg.exp
> > pqpath.obj : error LNK2019: unresolved external symbol _PQclear
> > referenced in function _pq_raise
> > connection_int.obj : error LNK2001: unresolved external symbol
> _PQclear
> > cursor_type.obj : error LNK2001: unresolved external symbol _PQclear
> > error_type.obj : error LNK2001: unresolved external symbol _PQclear
> > pqpath.obj : error LNK2019: unresolved external symbol
> _PQerrorMessage
> > referenced in function _pq_raise
> >
>
> This problem is not django-specific.
>
> Make sure you have python-dev and libpq-dev packages installed on your
> environment. After that, try "pip install psycopg2"
>
> --
> - Serdar Dalgıç 
> FLOSS Developer, Life & Nature Hacker
> twitter: https://twitter.com/serdaroncode
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

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




Re: m2m symmetry confusion

2013-04-11 Thread Sanjay Bhangar
Lachlan,

Not sure if I grokked your problem exactly, but just from personal
experience when I found my brain turned to jelly with a similar-sounding
issue before, I believe I found the answer in the "symmetrical=False"
option .. I do believe setting symmetrical=False for your 'parents' and
'children' fields maybe a good first step toward figuring this out -- I did
find that automatic creation of symmetrical relations in this case to be a
bit confusing if you aren't expecting it. And, also, just thinking about it
-- do you actually need two separate fields for parents and children? Why
not just --

children = models.ManyToManyField("self", related_name='parents',
verbose_name="Children",
symmetrical=False, null=True, blank=True)

Tbh, still not sure why your above example did not work:
>>> bob = Account(first_name="bob",last_name="sanders",gender='M')
>>> sarah = Account(first_name="sarah",last_name="sanders",gender='F')
>>> bob.siblings.add(sarah)

This is not something silly like needing to call bob.save() and
sarah.save() before adding the m2m, is it ?

Any-how, um, not sure if that helps at all or adds to the confusion, just
that I remember experiencing some brain-jelly and at that point, grokking
the 'symmetrical=False' option was my way out of it .. not sure if that's
your problem, though :-)

Cheers and all the best,
Sanjay



On Thu, Apr 11, 2013 at 12:31 PM, Lachlan Musicman wrote:

> I tried reading the code in django/db/models/fields/related.py but
> quickly realised it was beyond me groking in a half hour.
>
> BUT, for some reason I felt compelled to test through the admin
> interface and it is working. ie, I can create and remove siblings and
> partners from each other, error free (seemingly, anyway).
>
> So, confusion level ++
>
> L.
>
> --
> The new creativity is pointing, not making. Likewise, in the future,
> the best writers will be the best information managers.
>
>
> http://www.theawl.com/2013/02/an-interview-with-avant-garde-poet-kenneth-goldsmith
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

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




Re: Changing User model

2013-03-18 Thread Sanjay Bhangar
On Tue, Mar 19, 2013 at 3:11 AM, Lachlan Musicman  wrote:
> Sanjay!
>
> How are ya? I'll let you know as soon as I've properly implemented the
> whole shebang. Re "problems with admin" I just sent an email to
> pydanny of 2Scoops in this regard. I don't think it's clear enough
> anywhere, but careful reading of this:
>
> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#a-full-example
>
> Shows that when adjusting the User, via AbstractUser or
> AbstractBaseUser, the following *also* needs
> adjusting/rewriting/subclassing:
>
> models.py
> -
> The User model (the point of the exercise)
> The UserManager,  by subclassing BaseUserManager. Usually just the
> create_user and create_superuser methods.
>
> admin.py
> -
> The User Creation Form, for adding the new fields
> The User Change Form, as above
> The new User Admin needs to have the new forms explicitly listed.
>
>
> Did you do this and it didn't work?
>

Right, so, following code from that example, we landed up with this:
https://github.com/batpad/truenorth/blob/master/sat/login/admin.py .
It is pretty much a verbatim copy-paste of the code there, since
again, we did not have much customization beyond changing login to
email instead of username.

Sorry, I should have defined "didn't work" better - took a little
digging to remember the exact problems I had:

a> The password field does not give a link to the change password form.

b> Does not show m2m widgets for Permissions and Groups

These should actually be easy to fix, now that I think about it ;)

Ah, so the password field link is straightforward, just add a
help_text with an '' in it to the
ReadOnlyPasswordHashField in the UserChangeForm, doh.

Ah, and for b>, in this particular case, we're inheriting from
AbstractBaseUser and not AbstractUser, so it does not apply, but I
imagine one would just have to add 'groups' and 'user_permissions' to
the 'Permissions' dict in the fieldsets attribute of your custom
UserAdmin class.

Hm, the value of looking at code again with a clear head :)

I think I just lost myself a bit fiddling with it the last time I
looked at it, also working on adding tangential functionality that may
have thrown me off, but it seems like this should actually work just
fine :-) - apologies for the premature response there.

Cheers :)
-Sanjay


> Cheers
> L.
>
>
> On 18 March 2013 22:59, Sanjay Bhangar  wrote:
>> Hey L,
>>
>> On Mon, Mar 18, 2013 at 9:13 AM, Lachlan Musicman  wrote:
>>> Hola,
>>>
>>> For a new project, I will be creating a separate Profile class for all
>>>  information about my Users that isn't covered by User.
>>>
>>> One thing I did want though, was to change the login username to the
>>> email address.
>>>
>>> From what I've read in the code and docs, am I right in presuming that
>>> I can subclass AbstractUser and just change
>>>   USERNAME_FIELD = 'email'
>>> to get this result?
>>>
>>
>> That seemed to work, yes. The problem I had, though, was once I made
>> this change, adding users in the default admin became totally broken,
>> and I did not find a way to fix that easily. Please do let know if you
>> manage to do this in a way that doesn't break the admin functionality
>> to add users (if you don't get care about Admin to manage users, this
>> should work no problem .. ).
>>
>> Please do share what works out though - I was extremely excited about
>> the new Abstract User class, but found subclassing AbstractUser and
>> maintaining admin usability to manage users really hard to accomplish,
>> some-how. Let me know if you want me to post more details on what
>> issues I encountered and what I tried ..
>>
>> Cheers :)
>> -Sanjay
>>
>>
>>> All of the examples I've seen* suggest going all the way to
>>> AbstractBaseUser - but I'm ok with AbstractUser, I just want the
>>> single change?
>>>
>>> Cheers
>>> L.
>>>
>>>
>>> *pydanny's 2 scoops and the docs here:
>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#django.contrib.auth.models.CustomUser
>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#a-full-example
>>>  )
>>>
>>>
>>> cheers
>>> L.
>>>
>>>
>>> --
>>> The new creativity is pointing, not making. Likewise, in the future,
>>> the best writers will be the best information managers.
>>>
>>> http://www.thea

Re: Changing User model

2013-03-18 Thread Sanjay Bhangar
Hey L,

On Mon, Mar 18, 2013 at 9:13 AM, Lachlan Musicman  wrote:
> Hola,
>
> For a new project, I will be creating a separate Profile class for all
>  information about my Users that isn't covered by User.
>
> One thing I did want though, was to change the login username to the
> email address.
>
> From what I've read in the code and docs, am I right in presuming that
> I can subclass AbstractUser and just change
>   USERNAME_FIELD = 'email'
> to get this result?
>

That seemed to work, yes. The problem I had, though, was once I made
this change, adding users in the default admin became totally broken,
and I did not find a way to fix that easily. Please do let know if you
manage to do this in a way that doesn't break the admin functionality
to add users (if you don't get care about Admin to manage users, this
should work no problem .. ).

Please do share what works out though - I was extremely excited about
the new Abstract User class, but found subclassing AbstractUser and
maintaining admin usability to manage users really hard to accomplish,
some-how. Let me know if you want me to post more details on what
issues I encountered and what I tried ..

Cheers :)
-Sanjay


> All of the examples I've seen* suggest going all the way to
> AbstractBaseUser - but I'm ok with AbstractUser, I just want the
> single change?
>
> Cheers
> L.
>
>
> *pydanny's 2 scoops and the docs here:
> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#django.contrib.auth.models.CustomUser
> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#a-full-example 
> )
>
>
> cheers
> L.
>
>
> --
> The new creativity is pointing, not making. Likewise, in the future,
> the best writers will be the best information managers.
>
> http://www.theawl.com/2013/02/an-interview-with-avant-garde-poet-kenneth-goldsmith
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

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




Re: plugin for selecting files

2013-03-16 Thread Sanjay Bhangar
On Sun, Mar 17, 2013 at 12:00 AM, Larry Martell  wrote:
>
> Is there a way for me to get the path on the local computer of the
> files? In request.FILES all I see are the base names.
>

No. That would be pose serious security / privacy issues and afaik, is
definitely not possible to do. What would be your use-case for getting
the path on the user's machine?

-Sanjay

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




Re: plugin for selecting files

2013-03-15 Thread Sanjay Bhangar
Hey,

I believe there are some jquery plugins by now to handle
asynchronously uploading multiple files, and they should contain some
examples of how to handle them on the server side - this is one thing
I found on github -
https://github.com/sigurdga/django-jquery-file-upload , though I'm
certain there's more.

I've had to do something similar recently, and I sort've rolled my
own, was fairly interesting --

a> JS Library to handle "chunk uploading" of the files so you can do
async uploading and show progress bars, etc. - I used an excellent
library written by a friend -
http://hostb.org/static/js/chunkupload.js

b> Some code to allow users to drag and drop files onto the page, as
well as select multiple files and add it to an upload queue - I wrote
this for my project, but the uploadQueue should be fairly re-usable:
http://code.camputer.org/itf/annotate/head%3A/itf/static/js/upload/itfUpload.js

(Note: The above may not work across IE / older browsers, I believe
you would need some flash fallback to get that to work.)

c> Since the front-end sends chunks of the files to server, we need
one django view that's called when a new file is started, and one to
receive individual chunks of the file, and process it when the file
has completed uploading -- this is fairly tied in to my application
code, but you can see the views I used to process the chunks and the
files: 
http://code.camputer.org/itf/annotate/head%3A/itf/mediagallery/views.py#L122

Sorry, not sure how helpful those code snippets are, but hopefully it
gives you an idea of how you may go about it -- I do believe though,
that there should be some well packaged django apps that handle most
of this for you -- if you do have any questions about the code
snippets linked though, let me know, I can try and answer :)

Cheers,
Sanjay


On Fri, Mar 15, 2013 at 9:36 PM, Javier Guerra Giraldez
 wrote:
> On Fri, Mar 15, 2013 at 10:15 AM, Tom Evans  wrote:
>> I'm
>> fairly certain that  should not throw any change
>> events or make the name of the file available to JS, for reasons of
>> security.
>
> it does generate change events, even if the value is a black box.
>
>
>> Auto submitting the form would not allow the user to correct
>> mistakenly selecting the wrong file, or rather, forms usually allow
>> you to change a field and verify before submitting
>
> i agree that it's rude to submit a form before the user explicitly
> 'sends' it; but this behaviour is appearing more and more.  the idea
> is that the upload happens while the user fills other fields.  the
> uploaded file isn't "confirmed" yet, it would be replaced if the user
> chooses another one on the same 'slot' (if there are multiple 'choose
> file' fields).  if the user 'cancels' the form, the uploaded file
> should be discarded.  this doesn't mix too well with the
> multiple="true" attribute it's not an easy answer because of the
> many different user expectations.
>
>
> --
> Javier
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

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




Re: Need help with GeoDjango distance query.

2013-02-16 Thread Sanjay Bhangar
On Fri, Feb 15, 2013 at 10:00 PM, mack the finger  wrote:
> http://stackoverflow.com/questions/14889780/distance-query-within-a-certain-distance-based-on-value-in-joined-table
>
> Basically I want all objects within a certain distance, AS WELL as within
> each object's preferred distance.
>

just off the bat -- the distance query expects a decimal.Decimal
object - so you'd need to convert whatever
models.F('connection_distance') returns into a valid Decimal before
passing it to the query ..

-Sanjay

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




Re: Has the djangoproject.com site been down?

2013-02-13 Thread Sanjay Bhangar
for future reference, I find http://downforeveryoneorjustme.com/ to be
quite useful for checking this sort of thing

On Wed, Feb 13, 2013 at 5:12 PM, Babatunde Akinyanmi
 wrote:
> Its not just you, at least when I'm not trying with my phone.
>
> ..and say your from Nigeria not Africa
>
> Sent from my Windows Phone
> 
> From: tOlorun
> Sent: 2/12/2013 5:53 PM
> To: django-users@googlegroups.com
> Subject: Re: Has the djangoproject.com site been down?
>
> its just you ...
> its loading here ...
> Thanks
> tOlorun
>
> *Oluwanife@me*
>
>
> To be filled with the life of Christ Jesus and released into our
> destinies,taking
> the world for Him.
>
> | M: +2348121631706 | M: +234817907 | M: +23233487811
> | E-mail: omnioto...@gmail.com I omnioto...@live.com |
> omnioto...@yahoo.co.uk
> | Skype: omniotosho
>
>
> On Tue, Feb 12, 2013 at 5:40 PM, +Emmanuel  wrote:
>>
>> Is it just me or is djangoproject.com not loading? Been trying to access
>> it for a couple of weeks without success. I've tried different browsers to
>> no avail. Am accessing it from Africa.
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

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




Re: How to associate a formset with a field in a form

2013-02-12 Thread Sanjay Bhangar
Hey,

I, too, initially found the formsets documentation a bit confusing,
but they're quite straightforward to work with once you figure them
out..

Firstly, you probably want to use inlineformset_factory and not
formset_factory:
https://docs.djangoproject.com/en/dev/ref/forms/models/#django.forms.models.inlineformset_factory

With this, you would do something like:
ingredient_formset_factory = inlineformset_factory(Recipe, Ingredient,
form=IngredientForm)

Now you have your formset "factory" to be able to instantiate, either
an empty formset, with something like:
ingredient_formset = ingredient_formset_factory()

or with data with something like:
ingredient_formset = ingredient_formset_factory(request.POST)

then you can pass the ingredient_formset as context to your view and
render it in your html, inside your parent , probably after you
render your Recipe form, with something like {{ ingredient_formset }}
on your template .. as long as its within the  tag, the POST
data will be sent on form submit, and you can process it in your view.

Another thing you're probably going to want is the ability for your
users to Add additional forms on the page - there's a jquery plugin
for that: 
http://blog.stanisla.us/2009/10/10/jquery-plugin-django-dynamic-formset/

You should also probably read the documentation at
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
which covers these things better than my email :-)

All the best,
Sanjay


On Tue, Feb 12, 2013 at 10:28 AM, mmuk2  wrote:
> I'm trying to create a simple "recipe" form with a title and a list of
> ingredients, which allows a user to add additional ingredients to the
> recipe.
>
> I'm struggling, however, to implement this in Django. Particularly how to
> associate a formset with a field in a form. I'm sure it's a simple solution
> and one that's been done many times, but I must be missing something.
>
> I've got a model called Recipe that has a 1:n relationship with Ingredient.
> That means, a Recipe can have many Ingredients, but an Ingredient can only
> belong to 1 Recipe.
>
> models.py:
>
> class Recipe(models.Model):
>
> title = models.CharField(blank=True, null=True, max_length=100)
>
>
> class Ingredient(models.Model):
>
> title = models.CharField(blank=True, null=True, max_length=1000)
> recipe = models.ForeignKey(Recipe)
>
> The next step would be to set up model forms using the above 2 Models, which
> I've done.
>
> forms.py:
>
> class IngredientForm(forms.ModelForm):
> class Meta:
> model = Ingredient
>
> class RecipeForm(forms.ModelForm):
> class Meta:
> model = Recipe
>
> I know I now need to use formset_factory in order to display a list of
> Ingredients. This is where I'm stuck.
>
> views.py
>
> from django.forms.formsets import formset_factory
>
> # This obviously just gives me a Recipe form
> recipe_form = RecipeForm(request.POST or None)
>
> # This gives me a list of Ingredient forms in a formset, which is what I
> want, but I would like it to be associated with a Recipe
> ingredient_formset = formset_factory(IngredientForm)
>
> The above 2 lines of code will give the IngredientForm and RecipeForm as two
> separate forms that I can send to the template. However, there must be a way
> to display the recipe_form so that it displays the ingredient_formset as a
> "field" of a recipe_form. Subsequently, the user should be able to add extra
> ingredients to the recipe.
>
> I've had a read of the django documentation and haven't been able to come
> across anything there. Is there a particular section of the django docs that
> I should be focusing my attention on to get me unstuck? Or is there another
> way I should be approaching this?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

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




Re: On the fly image resize

2013-02-03 Thread Sanjay Bhangar
On Mon, Feb 4, 2013 at 6:32 AM, Spencer Summerville  wrote:
> Hello, there are a lot of solutions to resizing images in Django. I commend
> you for wanting to create your own solution, but one of the greatest things
> about Django is that there's tons of projects that people have made that
> solve your problems and usually there's enough of them that you can find one
> that implements itself in a way that lets you do what you want to do. I'm
> not a great programmer and usually these modules are taken from websites
> that in order to function, they have had to work properly in an environment
> where anything can go wrong.
>
> In my own experience, sorl-thumbnail has never let gotten in my way, it lets
> you do what you want and if you want to do something special you can easily
> write your own functionality. Don't want to use PIL? Use ImageMagick or
> write your own class. Have some sort of radical key value cache that nobody
> has ever heard of? Write your own class. Do you want to generate thumbnails
> in a batch process or in the model or in the template? sorl-thumbnail lets
> you choose what you want to do.
>

+1 for sorl. I have been using it for a while now with no significant
problems, and has made thumbnail generation a non-issue.

Sorry for the slightly off-topic statement here, but since we're
talking about Sorl :) - the one problem I've had is this:
In general, I want images to be resized in the format the user uploads
them - i.e. if a user uploads a PNG, I want the thumbnail to be a PNG,
and if the user uploads a JPEG, I want the thumbnail to be a JPEG. It
seems a bit silly, but I have not found a way to do this - I set an
option in settings.py for THUMBNAIL_FORMAT = "PNG", and then all the
thumbnails are PNG, which is non-optimal. And if I set the format to
JPEG, it will take uploaded PNGs with transparencies and convert them
to JPEGs without transparency, which is, again, unacceptable ..

I had looked around a fair bit in the docs, etc. but did not find a
way to specify something like "keep format of uploaded image" - this
was some time ago, though, so I'll check again - if anyone has dealt
with this, though, would love to know how :)

Cheers,
Sanjay



> https://github.com/sorl/sorl-thumbnail
>
>
> On Saturday, February 2, 2013 12:33:36 PM UTC-8, nYmo wrote:
>>
>> Hi all,
>> I'm new to django and also python but have already some programming
>> experience. I'm currently creating my first application in django and get
>> stucked because I'm looking for the best way to resize uploaded images.
>> I'm already so far that I can upload/delete/update my images and show them
>> in my view. Now I want to resize the images for my view and thought about
>> the best way?
>>
>> First question: Is it possible to resize the images on the fly? For
>> example I uploaded an image in 1920x1080px and now want to transform it to
>> 400x200 or something similar when the view is being loaded? Is this a
>> convenient way in django or not?
>>
>> The only other way in my opinion could be to resize the image during the
>> file is being uploaded. What I don't like about this is that I have more
>> than one copy of one image only because of different image sizes.
>>
>> Any other thoughs?
>>
>> I know that there are some nice packages out there where such problems are
>> already solved. But since I'm new to django I want to learn by myself how to
>> accomplish the basic stufff :)
>>
>> Thanks in advance
>>
>> Regards nymo
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

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




Re: Automating deployments

2013-02-03 Thread Sanjay Bhangar
On Sun, Feb 3, 2013 at 1:32 PM, Ashwin Kumar  wrote:
> thats so kind of you, i struggled a lot for 1 month to setup a server
> (ubuntu+nginx+uWSGI+mysql+pil+virtualenv+emperor).
> still i didn't succeed running emepror on system restart, i removed
> virtualenv as i got python-mysqldb error.
>

for the python-mysqldb error, here is what I generally do:
install python-mysqldb from apt-get, so 'sudo apt-get install python-mysqldb'
and then when creating the virtualenv, make sure to tell it to use
system packages where available with:
virtualenv --system-site-packages .

Then it should use mysqldb from the one installed by apt, which should
generally work better with the version, etc. on your machine than the
one installed from pip.

Hope that helps,
Sanjay


> let me know if you finish it.
>
> With Best
> -Ashwin.
> +91-9959166266
>
>
> On Sat, Feb 2, 2013 at 6:23 AM, Brian Schott  wrote:
>>
>> We are using ansible.
>> http://ansible.cc/
>>
>> Other popular choices are puppet and chef.  The real benefit. Is that
>> these tools let you version control your configurations.
>>
>> Sent from my iPhone
>>
>> On Feb 1, 2013, at 7:46 PM, Carlos Aguilar  wrote:
>>
>> Bash scripts really???
>>
>> If you are a Python developer you can use fabric to deployed and pip for
>> dependencies.
>>
>> Best Regards
>>
>> El viernes, 1 de febrero de 2013, Marc Aymerich escribió:
>>>
>>> Hi,
>>> I'm thinking about the best way to provide automatic deployment for
>>> the Django project I'm working on. Its a pretty big one and has lots
>>> of dependencies, lots of SO packages, Celeryd and other daemons, SO
>>> tweaks... and also several people will need to have installed it on
>>> their servers (they are sysadmins, not Django developers), Therefore I
>>> want to automate as much as possible the installation and updating
>>> processes, to minimize their pain and also because of having
>>> homogeneity.
>>>
>>> As I've been a sysadmin myself for many years I've already written
>>> some bash scripts that automates all the deployment. But in order to
>>> make it more 'natural' I'm planning to integrate those scripts within
>>> the Django project as management commands.
>>>
>>> To illustrate my ultimate goal this is how I imagine the workflow:
>>>
>>> sudo pip install django-my_project
>>> my_project-admin.sh clone project_name path
>>>
>>> sudo python manage.py installrequirements
>>> sudo python manage.py setuppostgres
>>> python manage.py syncdb
>>> python manage.py migrate
>>> python manage.py createsuperuser
>>>
>>> sudo python manage.py setupapache
>>> python manage.py collectstatic
>>> sudo python manage.py setupceleryd
>>> sudo python manage.py createtincserver
>>> python manage.py updatetincd
>>> sudo python manage.py setupfirmware
>>> python manage.py loaddata firmwareconfig
>>>
>>> sudo python manage.py restartservices
>>>
>>>
>>> Any thought on this? How do you automate your deployments? I heard
>>> about fabric lots of times but never used it. Will fabric be helpful
>>> in my case? Does it has any advantage for writing my own scripts? Or
>>> maybe there are already some existing tools for automating deployment
>>> of most common services like Apache, celeryd ..,?
>>>
>>> Many thanks!
>>> br
>>> --
>>> Marc
>>>
>>> --
>>> You received this message because you are subscribed to the Google Groups
>>> "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send an
>>> email to django-users+unsubscr...@googlegroups.com.
>>> To post to this group, send email to django-users@googlegroups.com.
>>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>>> For more options, visit https://groups.google.com/groups/opt_out.
>>>
>>>
>>
>>
>> --
>> Carlos Aguilar
>> Consultor Hardware y Software
>> DWD&Solutions
>> http://www.dwdandsolutions.com
>> http://www.houseofsysadmin.com
>> Cel: +50378735118
>> USA: (301) 337-8541
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving em

Re: Moving a Django website to another server

2013-01-26 Thread Sanjay Bhangar
On Sat, Jan 26, 2013 at 7:09 AM, Addy Yeow  wrote:
> I was looking for a consistent and error-free deployment as I switch
> between servers frequently despite using the same public domain. rsync
> was great but I had to manually reload server thereafter or issue a
> syncdb, etc.
>
> I have since moved to Fabric for my deployment needs. See
> http://docs.fabfile.org/en/1.5/tutorial.html.
> With Fabric, I only need to issue one command for daily deployment to
> existing or new server, e.g. fab deploy, under my Django project
> directory to deploy the project.
>

Just to second this - there are several articles on the interwebs
about using fabric, virtualenv and pip for managing your dependencies
and deployments. I have found this to be an incredibly smooth way to
manage things. The only sometimes nasty thing about moving stuff from
one server to another is installing all the dependencies you need for
your django project to run - 3rd party apps, python packages you need,
etc. One situation that can occur frequently is that if you install a
dependency on the new server, it gets a later version of the package,
and this breaks something on your code which depends on some behaviour
of an older version. To tackle this, I've found 'pip freeze' to be
great - you type 'pip freeze' in the virtualenv of your working
project code, and it lists all the python packages the project is
using with their exact versions, so you can use this to create a
requirements.txt file to 'pip install -r requirements.txt' from on the
new server while making sure it gets the very exact version of
dependencies so you can be sure it is running the same code -- in
general, I have found this to be the smoothest way to deploy projects
onto new servers.

hth,
Sanjay

-- 
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.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Generic views and url issues

2013-01-23 Thread Sanjay Bhangar
(reply inline)

On Thu, Jan 24, 2013 at 5:09 AM,   wrote:
> I've been trying to understand how to use generic views.  I've followed some
> tutorials, and read through Django docs, but I can't get the url function to
> work in my templates.
>
> I get the error
> NoReverseMatch at /testadcall/
>
> Reverse for 'detail' with arguments '(1,)' and keyword arguments '{}' not
> found.
>
>
> in my urls.py
>
> queryset = {'queryset': Adcall.objects.order_by('name')}
>
> urlpatterns = patterns('django.views.generic.list_detail',
> url(r'^$','object_list', queryset, name="adcalls"),
> url(r'(?P\d+)/detail/$', 'object_detail', queryset,
> name="detail"),
> )
>
> in my template for the list view:
>
> {% load url from future %}
> {% if object_list %}
> 
> {% for adcall in object_list %}
> {{ adcall.name
> }}
> {% endfor %}
> 
> {% endif %}
>

try:
{% url 'detail' object_id=adcall.id %}

since you have object_id defined as a keyword param in the url, you
will need to specify it as a keyword param in the {% url %} tag, I
*think* :)

let know if that works -
best've luck,
Sanjay

> I've tried no quotes, single quotes, and double quotes around the url name
> "detail", with no apparent effect.
>
> Am I wrong in thinking that this should work?
>
> I'm using Django 1.4.3, Python 2.7.3
>
> Thanks so much.
>
> --
> 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/-/M6Qrx89JeBkJ.
> 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: Project Structure - Lots of scattered custom views

2013-01-15 Thread Sanjay Bhangar
On Mon, Jan 14, 2013 at 8:16 PM, chad petzoldt  wrote:
>> It had occurred to me that Django wasn't the right tool for this job -
>> not everything is a nail :)
>
>
> I am embedding these files within a template, so they are not direct static
> serves. But the content must be inserted within the template "as-is" from
> the filesystem.
>

here is a view i have from a project (simplified):

def viewPage(request, page):
filename = page + ".html"
html_file = join(HTML_PATH, filename)
try:
txt = open(html_file).read()
except:
return HttpResponse("page not found")
context = RequestContext(request, {'html': txt})
return render_to_response("page.html", context)

And the corresponding url.py:
(r'(?P.*)', 'foo.views.viewPage'),

And then page.html is something like:



  {{ html }}


My use case was different tho, but just to highlight that its fairly
straightforward to read the contents of some file on disk and stick it
into a django template ..
In your case, each "page" is going to need its own corresponding set
of css / js, so I imagine this would be a bit more work .. but I'm
still fairly certain you can come up with a scheme that allows you to
have your html and css / js on the file-system and then use python
code to put it together into a master template / integrate with other
app logic you have ..

It does seem like a bit of a hack, but hey, moulding InDesign exports
into actual webpages is always going to be, a bit ;-)

> I suck at Javascript.
>

ok, this shouldn't affect this problem / use-case.

> Perhaps still, Django is not proper for the job, but I do know that I need
> some server-side logic, and I want to do it in Python. Any recommendations
> on another framework?
> There are aspects of Django that are growing on me, this one paradigm is
> where I am struggling, and I would not like to abandon just yet.
>

What is the paradigm, exactly ... ? Do you have an idea of how you
would have implemented the same thing using php or anything else? It
may give a better idea of your use case / what you're thinking.

> To recap one of my original statements; I do believe what I am really
> looking for is a content management system, I just don't feel ready to
> commit (maybe I need to get over that). I want a content management system
> that focuses more on the "client experience" in the browser. It needs to be
> picky about layouts, and aware of embedded media. Any suggestions for
> starters?
>

Welll .. the most important question here is: does the client /
non-tech people need to be able to edit content themselves? Or will
you / someone "techie" always be handling the editing of the html? If
people do need to edit themselves, then you generally do need to
structure things a little - an all-singing-all-dancing WYSIWYG editor
for end-users, is I'm afraid, still a bit of a pipe dream (someone
please correct me if things have changed :)) .. going down the path of
trying to build a system that's going to accommodate for radically
different designs that you have no way of pre-empting, is generally a
recipe for disaster .. I think you've got the right idea of trying to
get the system to adapt to your work-flow rather than the other way
around .. and if it is only you editing the HTML files, build
something that helps you manage that, rather than a "content
management system", although, er, anything that you use to manage
content is a content management system :)

The other option, of course, is to tell the client that they need to
stick to a consistent format, and then just put stuff into different
fields in the database and render it in a template like normal :)

hope my response didn't add to the confusion, and hope you find a
solution that works for you.
happy hacking!
-Sanjay

> NOTE: My site layouts are not "liquid" at all. They are very absolute; from
> dimensions to positioning. Its not just about getting all the content on the
> page in a certain order.
>
>
>
> --
> 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/-/hLQsR_8-pOYJ.
>
> 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: Project Structure - Lots of scattered custom views

2013-01-13 Thread Sanjay Bhangar
On Sat, Jan 12, 2013 at 12:04 AM, chad petzoldt  wrote:
> Sanjay, you were hitting things pretty close. I think that making sure slug
> names match up to real *static* locations is the key. I am hosting with
> Apache, and I thought about using some configurations to cheat a little bit,
> and get some of the static-files burden off of Django and let Apache resolve
> any requests that point to actual files on disk (with some security in
> mind).
>
> What about a view that can determine if it should be pointing at a file on
> disk, and if so, do a custom Http_Response, and read the actually binary
> contents from disk by hand. Im just curious on this one; it could be an
> alternative means of file storage and recognition. I understand this may
> have some performance implications, but this is not going to break Django,
> correct? Is this bad Django etiquette?
>

Yea, hooking up slug-name to folder-name is brittle - if you're just
reading the binary contents of files and serving them, you could do it
in a django view, but you're probably better off doing it directly
through apache - there's no reason to use Django for something its not
good as :) - I think this really depends on how much these 'static'
html pages you're serving need other components of your django app -
if they're completely separate, then they're probably better off being
served simply as static files through apache :)

What I have done in the past is read template files off disk through
some name in the URL .. so like http://foo.com/home looks into a
directory, looks for home.html, and renders the template .. if you do
need to nest these static html files of yours into a django template
that has some other logic, I think this is a perfectly fine logic to
use and has worked well for me .. if you just need to serve the binary
files off disk though, you're probably better off just using apache to
serve them ...

Hope that makes sense / helps ..
-Sanjay


> Amirouche, a different way to describe what I am trying to achieve might be
> this: I would like to bypass the admin as much as possible when it comes to
> these "Articles". But when rendered, all of these articles do need at least
> a small HTML wrapper, and probably some kind of of global template that
> helps with navigation. If I could handle navigation without the admin, i
> would be very excited, but it does seem that I will need to use the admin
> for at least this purpose. The navigation would probably help render
> hierarchical  "menus" for use as templates within the Articles. I would like
> to keep this navigation as light as possible.
>
> Thanks for the feedback.
>
> --
> 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/-/ja-o_pBFAT4J.
>
> 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: Project Structure - Lots of scattered custom views

2013-01-08 Thread Sanjay Bhangar
hey all,

This seems to be an itch I've had to scratch myself in the past - let
me see if I understand the situation vaguely correctly:

You have a site that uses Django / database features for some things,
but then you also have a lot of content that's being designed in some
design tool and needs to be manually crafted into precise (sometimes
hackish) html and uploaded, and you almost want to just work with
plain html files on a file-system so you can use the tools you're used
to - Komodo / vim, version control, etc. This content is in the form
of "article bundles" which need to have some sequencing between pages.

The 'new app for every article' definitely sounds like a clusterf
it maybe an interesting experiment, but it just *feels* wrong at so
many levels .. you do want some way to generalize this into a single
app .. but my guess is you also are unable to wrap things into common
templates and editing the html in the database / django admin is just
too messy .. even if you let individual "articles" or "article
bundles" have their own custom css that's specified some-how in the
db, and their own custom html that you some-how populate from html
files you upload. It may work, and it is perhaps the correct way to do
this. I just know the situation where you're fighting with some silly
html generated by a design tool and actually want simple html files
and css resources, and the database "structure" can feel like its
getting in the way ..

So, here is my radical (?) suggestion :) -

Have a simple model like this:
class Item(models.Model):
  title = models.CharField(..)
  slug = models.SlugField(..)
  ... any extra metadata fields you need for the "article bundles"

Then, for each item "slug" name, you create a new folder on the
file-system in some path you define in settings.py or so like
CUSTOM_HTML_PATH or anything - so, say you have a series of articles
on "Why not to do webdesign in Indesign" with a slug like
"why-not-indesign", you create a folder inside CUSTOM_HTML_PATH with
the name "why-not-indesign". Then create the various articles in that
"bundle" like 1.html, 2.html, 3.html, etc. and include all the css /
js files that specific bundle needs inside a static folder in that
directory.

Then you just need a view which takes , looks for the
appropriate folder on the file-system, and renders 1.html inside
whatever master template you may have. The view can also check for all
the .html files in the directory to handle next / previous.
You would probably need to do a bit of magic with STATICFILE_DIRS or
so to make sure each of the static file folders inside the directories
are collected by collectstatic so you can still serve the static files
through the web server and not through django.

Of course, I don't know the details of your work-flow so I maybe
missing something, but I do in general find the idea of storing some
things just on the file-system quite interesting, and the code to
manage it is generally pretty straightforward.

Of course, this may also be a terrible idea, but I'd also love to hear why .. :)

Cheers,
Sanjay





On Tue, Jan 8, 2013 at 9:52 AM, Lachlan Musicman  wrote:
>>
>> There are some cases where they send me Indesign, but when I export to HTML
>> some of the layouts break. So then I have to manually rig it until I feel
>> its close enough (but then it turns out it wasn't, so I mod again). Some
>> imagemaps made from sliced up Photoshops with some cute rollover effects
>> added on. And then some of the Articles form sequential "stories", so they
>> need linking in between to make them feel seamless.
>>
>> The major point is that I have small bundles of files that are very
>> interconnected, and keeping them close and organized makes the
>> reviewing/editing/handling process much easier. Most of my hacking has been
>> from KomodeIDE, and then VIM/SSH (and thats even when Im doing the design
>> work!). Im having a hard time breaking away from the direct editing.
>
> So it sounds like a model like this would work:
>
> def BundleFiles(models.Model):
> file = models.FileField()
> articlw = models.ManyToMany(Article)
> # or maybe article = models.ForeignKey(Article)
>
> def Article(models.Model):
>  html = models.TextField() #for the end product
> # or html = models.FileField()
> cssfile = models.FileField() #this can be abstracted out to it's own
> model if used across many articles
>  previous = models.FK(Article, blank = True, null= True)
>  next = models.FK(Article, blank = True, null= True)
>
> See how these are more like folders to hold each set of info. For the
> final product/page, you would need to write appropriate views and
> methods that extracted the important bits and put them in the
> appropriate places.
>
>
>
>>>
>>> > I think that splitting each article into it's own app sounds like a
>>> > disaster waiting to happen.
>>>
>>
>> I agree, thats why I posted here. I am already starting to see the
>> problems... I have started breaking the