Re: Struggling with formsets

2015-02-19 Thread Werner Brand
Thanks for the reponse!  My template looks like this:


{{ formset.management_form }}

{{ formset }}

{% csrf_token %}

 

Here is the print request.POST:

form-1-salaryform-MAX_NUM_FORMSform-0-surnameform-0-nameform-TOTAL_FORMSform-MIN_NUM_FORMSform-0-idform-1-nameform-INITIAL_FORMScsrfmiddlewaretokenform-0-salaryform-1-idform-1-surname

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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/74e6d086-5ec7-41f2-be04-edcf4f6d8aaa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


extracting data from three tables

2015-02-19 Thread sum abiut
Hi,
I have three models that i want to extract data from them. The models are
join using foreign key. i am not sure how to do that in django. Can someone
please point me to the right path.

Cheers

-- 
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/CAPCf-y7vVA995WHrStKebFOBLQXx9gnu%2B-c0TwaK70uFNA-ZqA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Proble understanding DetailView url doesn't match the slug

2015-02-19 Thread 严超
What is the specific error Django printed out ? We can narrow down the
cause by checking the errors maybe.

*Best Regards!*


*Chao Yan--About me : http://about.me/chao_yan
*

*My twitter: @yanchao727 *
*My Weibo: http://weibo.com/herewearenow *
*--*

2015-02-20 9:58 GMT+08:00 inoyon artlover KLANGRAUSCH <
inoyonartlo...@googlemail.com>:

> Many thanks! Now I got it! :)
>
> Am Samstag, 14. Februar 2015 05:28:40 UTC+1 schrieb inoyon artlover
> KLANGRAUSCH:
>>
>> Hi there, there is something I obviously don't understand. According to
>> django reference,
>> the DetailView has to be provided a slug or pk. I do it in the url but
>> django constantly doesn't
>> recognize the slug in the url.  'current url doesn't match etc.' what is
>> wrong here? I do everything
>> like it is explaind and it doesn't work.. very frustrating sometimes...
>>
>>
>> My models.py:
>>
>> class List01(models.Model):
>> name = models.CharField(max_length=100, default='name')
>> surename = models.CharField(max_length=100, default='surename')
>> slug = models.SlugField()
>>
>>
>> views.py
>>
>> class List(DetailView):
>> template_name = 'index.html'
>> model =List01
>>
>> urls.py
>>
>> urlpatterns = patterns('',
>> url(r'^admin/', include(admin.site.urls)),
>> url(r'^(?P)$',List.as_view()),
>> )
>>
>  --
> 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/671c9f52-a48d-4529-a126-31542515dbf2%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/CALAMvO8vNMUxM-Cbeg2P8hzhwqqVMw_Na8HxGGhLCtbvhcU8cg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Proble understanding DetailView url doesn't match the slug

2015-02-19 Thread inoyon artlover KLANGRAUSCH
Many thanks! Now I got it! :)

Am Samstag, 14. Februar 2015 05:28:40 UTC+1 schrieb inoyon artlover 
KLANGRAUSCH:
>
> Hi there, there is something I obviously don't understand. According to 
> django reference,
> the DetailView has to be provided a slug or pk. I do it in the url but 
> django constantly doesn't
> recognize the slug in the url.  'current url doesn't match etc.' what is 
> wrong here? I do everything
> like it is explaind and it doesn't work.. very frustrating sometimes...
>
>
> My models.py:
>
> class List01(models.Model):
> name = models.CharField(max_length=100, default='name')
> surename = models.CharField(max_length=100, default='surename')
> slug = models.SlugField()
>
>
> views.py
>
> class List(DetailView):
> template_name = 'index.html'
> model =List01
>
> urls.py
>
> urlpatterns = patterns('',
> url(r'^admin/', include(admin.site.urls)),
> url(r'^(?P)$',List.as_view()),
> )
>

-- 
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/671c9f52-a48d-4529-a126-31542515dbf2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: allow certain users to access certain views

2015-02-19 Thread sum abiut
Hi James,

Thanks heaps for direction.

Cheers

On Thu, Feb 19, 2015 at 6:18 PM, James Schneider 
wrote:

> You should be able to handle this pretty easily with Django's built-in
> permission system.
>
> Just create a group, add the users to it, and assign the requisite
> permissions to the group. Our add the needed permissions individually to
> each user.
>
>
> https://docs.djangoproject.com/en/1.7/topics/auth/default/#permissions-and-authorization
>
> Then all you'll need to do is wrap your views with the correct permission
> checks, or do the checks within the templates if you need to, like {% if
> 'foo.view' in perms %} assuming that you have the default context
> processors in place, or have included the contrib.auth processor.
>
> You shouldn't need to do any permission checks for pages that are
> available to everyone.
>
> Alternatively, you can tweak the user.is_staff attribute to True for those
> that need extra access, and use that as your permission check if you don't
> need anything fancy.
>
> -James
> On Feb 18, 2015 9:49 PM, "sum abiut"  wrote:
>
>> Hi,
>> I have an app that i am trying to allow only certain users to access
>> specific views. For example all users can view the home page but for a
>> certain link. i only want to allow the HR manager to access it.
>>
>> Could you please point me to right direction.
>>
>> Cheers
>>
>>
>>  --
>> 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/CAPCf-y5VBRtsb2oFN5ZEPL2_57y%2BAhKqV-OnEqne2YAcACNxsw%40mail.gmail.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/CA%2Be%2BciWj2mb4a0Yx1sep8X8MSdcLfNK_L8SJ04E29gkH10gjyA%40mail.gmail.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/CAPCf-y74Xuf%2BvGK_82nn%3DUvkBbRgrgexniDqYSYeXum5m9T%2B7w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: html response to be loaded in a div

2015-02-19 Thread Vijay Khemlani
There's no "range" in django templates, you just use

{% for elem in sols %}

Regarding making the request using POST, are you sure you're not having a
proble with CSRF?

https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/

It has a section for AJAX requests



On Thu, Feb 19, 2015 at 7:44 PM, João Marques 
wrote:

> Thank You guys for all the aswers. Your were crucial debugging this error.
>
> By the way, on the GET request matter, I'm using a GET because I can't
> actually get POST to work I'll explain: As I execute the POST request, the
> url is loaded and everything runs fine except that the code on the view
> doesn't return nothing. Thats is the reason I have everything set uo with
> GET. Does anybody know if I have to enable something on my Django
> properties to get this to work?
>
> Cheers
>
> --
> 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/76c1ef99-5082-4b26-a954-f8dde0b7262d%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/CALn3ei1pS8vo3dHKtoQv%3DpjiYN2DZPpxZFXmAPqxTmPBcu9pkQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: JSON Response

2015-02-19 Thread Vijay Khemlani
What is the actual content of the respose you are getting back from the
server?

On Thu, Feb 19, 2015 at 7:06 PM, elcaiaimar  wrote:

> I mean in a correct form. My code doesn't work. It seems like the JS code
> doesn't receive the jsonresponse.
> I get a page with {"status":"True","product_id":p.id} But this should be
> read for the JS code, and if it's True show an alert saying Remove it!
>
> Is there anything wrong in my code?
>
> El jueves, 19 de febrero de 2015, 21:49:59 (UTC+1), Vijay Khemlani
> escribió:
>>
>> What do you mean with "in a good way"? Does your code work?
>>
>> On Thu, Feb 19, 2015 at 4:14 PM, elcaiaimar  wrote:
>>
>>> Hello,
>>>
>>> I was wondering how I can send a response JSON in a good way, because I
>>> have the next code:
>>>
>>> if "product_id" in request.POST:
>>> try:
>>> id_producto = request.POST['product_id']
>>> p = Pozo.objects.get(pk=id_producto)
>>> mensaje = {"status":"True","product_id":p.id}
>>> p.delete() # Elinamos objeto de la base de datos
>>> return JsonResponse(mensaje)
>>> except:
>>> mensaje = {"status":"False"}
>>> return JsonResponse(mensaje)
>>>
>>> And my JS function doesn't work with this code:
>>>
>>>var options = {
>>> success:function(response)
>>> {
>>> if(response.status=="True"){
>>> alert("Eliminado!");
>>> var idProd = response.product_id;
>>> var elementos= $(nombre_tabla+' >tbody >tr').length;
>>> if(elementos==1){
>>> location.reload();
>>> }else{
>>> $('#tr'+idProd).remove();
>>> $(nombre_ventana_modal).modal('hide');
>>> }
>>> }else{
>>> alert("Hubo un error al eliminar!");
>>> $(nombre_ventana_modal).modal('hide');
>>> };
>>> }
>>> };
>>> $(nombre_formulario_modal).ajaxForm(options);
>>> });
>>>
>>> And I don't know what I can do. Does anyone have any idea?
>>>
>>> --
>>> 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...@googlegroups.com.
>>> To post to this group, send email to django...@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/2cfc6283-ee2f-4280-b086-2dc1595855c8%
>>> 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/e57dc93c-07a1-4d86-9155-0f0a76bde9fe%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/CALn3ei0YBUMM9Ww1XXnebePeSqBvg6CE7dDnePECH-_jpdps7A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Sqlite3 to Postgres Migration?

2015-02-19 Thread Mike Dewhirst

On 20/02/2015 3:07 AM, Tom Lockhart wrote:

On Feb 18, 2015, at 11:04 PM, talex  wrote:


I have a functioning Django application that is based on sqlite3,
but I want to change to using Postgres.


I’ll point out for the benefit of others who might be getting started: 
Postgres is a full featured database and supports the full range of Django 
features and add-ons including GeoDjango. Starting development with a 
production-quality database already in place is not much more work and will 
save grief later on.

Usually I’d end with “hth†, but this is no help at all for talex…

- Tom



I agree with Tom.

You are looking for a pair of dump/load scripts. Check this post ...

http://stackoverflow.com/questions/4581727/convert-sqlite-sql-dump-file-to-postgresql

I haven't studied that SO post but at first glance it seems the sqlite 
dump file might be directly usable by postgres. If so, you need to 
create the new database in Postgres and load it from the sqlite dump file.


You need to look at the Postgres docs for psql which will load the 
sqlite3 data dump.


Here is an example I use regularly ...

psql --port=5432 --file=/home/mike/dumps/pg/ssds/pq3.dump --dbname=ssds 
--username=miked


hth

Mike

--
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/54E6740B.6070902%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Re: Question about form security.

2015-02-19 Thread Carl Meyer
On 02/19/2015 04:03 PM, Chen Xu wrote:
> what if I have two addresses, id is 1 and 2, and I want to update 2, how
> I should distinguish 2 from 1, I mean, if I have addressid in the form,
> and someone modify it from 2 to 1, and that will update 1, right? How to
> prevent this?

Your server-side code must handle all security-related validation, and
must assume that no data sent from the client can be trusted. So in this
case you describe, your server-side code must have some way to know
which address(es) the currently logged-in user has the authority to edit.

Usually in this type of case I would make the address ID being edited a
part of the URL, not a form parameter (because it's used to query the
instance being edited by the ModelForm), and I would perform the access
check at the very top of the view function, often returning a 404 if the
user should not have access to that address.

If for some reason the address ID must be in the form rather than a URL
parameter, you could pass `request.user` to the form and have the form
validation check that that user is permitted to edit the given address ID.

Carl

-- 
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/54E66EC8.70808%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Question about form security.

2015-02-19 Thread Chen Xu
what if I have two addresses, id is 1 and 2, and I want to update 2, how I
should distinguish 2 from 1, I mean, if I have addressid in the form, and
someone modify it from 2 to 1, and that will update 1, right? How to
prevent this?

On Thu, Feb 19, 2015 at 6:01 PM, Mario Gudelj 
wrote:

> Because the user must be logged in to update their username you can get
> the current user from the request. You don't need to have their id inside
> the form.
> On 20/02/2015 9:49 am, "Chen Xu"  wrote:
>
>> Hi
>> I am implementing a feature while building a website using Django,
>> basically, I want user to be able to update their usernames. All of a
>> sudden, this question comes to me, if I have the userid (ex: 1) somewhere
>> in the form as a data attribute, if someone use firebug or something to
>> change the data-userid to 2, and submit the form, this will result in that
>> user 2 gets updated, right?
>>
>> What is the correct way to prevent this?
>>
>> Thanks
>>
>>
>> --
>> ⚡ Chen Xu ⚡
>>
>> --
>> 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/CACac-qZ-dOZqFCzS0U7LHWE6Q7HR9bapVfFbYqjawtVhWG5-MQ%40mail.gmail.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/CAHqTbjkXji3ggpUCPaD8qaiTBEptourA5Qrssmf3iEU22Lxkkg%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
⚡ Chen Xu ⚡

-- 
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/CACac-qbVG4ZugwgckkiBFmvRb4qe7PtBcgUpVxnDDb6THQFuxw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Question about form security.

2015-02-19 Thread Mario Gudelj
Because the user must be logged in to update their username you can get the
current user from the request. You don't need to have their id inside the
form.
On 20/02/2015 9:49 am, "Chen Xu"  wrote:

> Hi
> I am implementing a feature while building a website using Django,
> basically, I want user to be able to update their usernames. All of a
> sudden, this question comes to me, if I have the userid (ex: 1) somewhere
> in the form as a data attribute, if someone use firebug or something to
> change the data-userid to 2, and submit the form, this will result in that
> user 2 gets updated, right?
>
> What is the correct way to prevent this?
>
> Thanks
>
>
> --
> ⚡ Chen Xu ⚡
>
> --
> 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/CACac-qZ-dOZqFCzS0U7LHWE6Q7HR9bapVfFbYqjawtVhWG5-MQ%40mail.gmail.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/CAHqTbjkXji3ggpUCPaD8qaiTBEptourA5Qrssmf3iEU22Lxkkg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Question about form security.

2015-02-19 Thread Chen Xu
Hi
I am implementing a feature while building a website using Django,
basically, I want user to be able to update their usernames. All of a
sudden, this question comes to me, if I have the userid (ex: 1) somewhere
in the form as a data attribute, if someone use firebug or something to
change the data-userid to 2, and submit the form, this will result in that
user 2 gets updated, right?

What is the correct way to prevent this?

Thanks


-- 
⚡ Chen Xu ⚡

-- 
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/CACac-qZ-dOZqFCzS0U7LHWE6Q7HR9bapVfFbYqjawtVhWG5-MQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: html response to be loaded in a div

2015-02-19 Thread João Marques
Thank You guys for all the aswers. Your were crucial debugging this error. 

By the way, on the GET request matter, I'm using a GET because I can't 
actually get POST to work I'll explain: As I execute the POST request, the 
url is loaded and everything runs fine except that the code on the view 
doesn't return nothing. Thats is the reason I have everything set uo with 
GET. Does anybody know if I have to enable something on my Django 
properties to get this to work?

Cheers

-- 
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/76c1ef99-5082-4b26-a954-f8dde0b7262d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: html response to be loaded in a div

2015-02-19 Thread João Marques
Thank you all for being so fast aswering! I've looking through your answers 
and I've improved my code altough, I'm stuck with another error right now, 
wich is:



Environment:


Request Method: GET
Request URL: 
http://localhost:8000/saveToDbAndReturn/?sols=%5B%5B%5B%2211C%22,%2211E%22,%229E%22,%2212C%22%5D,%5B%225B%22,%2212A%22,%2210C%22,%2212D%22%5D,%5B%225E%22,%2210F%22,%2211C%22%5D,%5B%2210D%22,%228B%22,%2210A%22%5D,%5B%225C%22,%2210E%22,%2210H%22%5D,%5B%229A%22,%226D%22,%2212G%22%5D,%5B%227A%22,%2212F%22,%2212E%22%5D,%5B%228C%22,%2211B%22%5D,%5B%229C%22,%2210G%22%5D,%5B%226A%22,%2211F%22%5D,%5B%229B%22,%226B%22,%2211G%22%5D,%5B%228E%22,%2210B%22%5D,%5B%225A%22,%2212B%22,%227B%22%5D,%5B%227C%22,%2211A%22%5D,%5B%225D%22,%228D%22%5D,%5B%226E%22,%229D%22%5D,%5B%226C%22,%2211D%22%5D,%5B%227E%22%5D,%5B%227D%22%5D,%5B%228A%22%5D,2700%5D,%5B%5B%227A%22,%2212E%22,%2212F%22,%2212C%22%5D,%5B%225D%22,%229B%22,%2210E%22%5D,%5B%227A%22,%2212D%22,%2210A%22%5D,%5B%2210C%22,%225E%22,%2212A%22%5D,%5B%228C%22,%2210D%22%5D,%5B%229E%22,%2212B%22,%2211C%22,%2211G%22%5D,%5B%225A%22,%227B%22,%2212G%22%5D,%5B%2210F%22,%226E%22,%2211A%22%5D,%5B%229C%22,%226C%22%5D,%5B%2210B%22,%228E%22,%225C%22,%2210H%22%5D,%5B%226D%22,%2210G%22%5D,%5B%2211D%22,%227D%22%5D,%5B%228A%22,%2211E%22%5D,%5B%227E%22,%2211B%22%5D,%5B%229A%22,%226B%22%5D,%5B%2211F%22,%226A%22%5D,%5B%225B%22,%228D%22%5D,%5B%227C%22%5D,%5B%229D%22%5D,%5B%228B%22%5D,2700%5D%5D

Django Version: 1.7.4
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'teste1',
 'django_pdb')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django_pdb.middleware.PdbMiddleware')


Template error:
In template E:\Mega\MEOCloud\Django\psi\templates\saveToDbAndReturn.html, 
error at line 3
   Could not parse the remainder: '(sols)' from 'range(sols)'
   1 : 


   2 : 


   3 :  {% for elem in range(sols) %} 


   4 : 


   5 : 


   6 :   


   7 : 


   8 : {{elem}}


   9 : 


   10 :   


   11 : 


   12 : 


   13 :   


Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in 
get_response
  111. response = wrapped_callback(request, 
*callback_args, **callback_kwargs)
File "E:\Mega\MEOCloud\Django\psi\teste1\views.py" in saveToDbAndReturn
  47. return render_to_response('saveToDbAndReturn.html', {'sols': 
sols})
File "C:\Python34\lib\site-packages\django\shortcuts.py" in 
render_to_response
  25. return HttpResponse(loader.render_to_string(*args, **kwargs), 
**httpresponse_kwargs)
File "C:\Python34\lib\site-packages\django\template\loader.py" in 
render_to_string
  170. t = get_template(template_name, dirs)
File "C:\Python34\lib\site-packages\django\template\loader.py" in 
get_template
  144. template, origin = find_template(template_name, dirs)
File "C:\Python34\lib\site-packages\django\template\loader.py" in 
find_template
  132. source, display_name = loader(name, dirs)
File "C:\Python34\lib\site-packages\django\template\loader.py" in __call__
  44. return self.load_template(template_name, template_dirs)
File "C:\Python34\lib\site-packages\django\template\loader.py" in 
load_template
  50. template = get_template_from_string(source, origin, 
template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in 
get_template_from_string
  156. return Template(source, origin, name)
File "C:\Python34\lib\site-packages\django\template\base.py" in __init__
  132. self.nodelist = compile_string(template_string, origin)
File "C:\Python34\lib\site-packages\django\template\base.py" in 
compile_string
  162. return parser.parse()
File "C:\Python34\lib\site-packages\django\template\base.py" in parse
  290. compiled_result = compile_func(self, token)
File "C:\Python34\lib\site-packages\django\template\defaulttags.py" in 
do_for
  832. sequence = parser.compile_filter(bits[in_index + 1])
File "C:\Python34\lib\site-packages\django\template\base.py" in 
compile_filter
  372. return FilterExpression(token, self)
File "C:\Python34\lib\site-packages\django\template\base.py" in __init__
  588.   "from '%s'" % (token[upto:], 
token))

Exception Type: TemplateSyntaxError at /saveToDbAndReturn/
Exception Value: Could not parse the remainder: '(sols)' from 'range(sols)'

-- 
You received this message because you are subscribed to the Google Groups 

Re: JSON Response

2015-02-19 Thread elcaiaimar
I mean in a correct form. My code doesn't work. It seems like the JS code 
doesn't receive the jsonresponse.
I get a page with {"status":"True","product_id":p.id} But this should be 
read for the JS code, and if it's True show an alert saying Remove it!

Is there anything wrong in my code? 

El jueves, 19 de febrero de 2015, 21:49:59 (UTC+1), Vijay Khemlani escribió:
>
> What do you mean with "in a good way"? Does your code work?
>
> On Thu, Feb 19, 2015 at 4:14 PM, elcaiaimar  > wrote:
>
>> Hello,
>>
>> I was wondering how I can send a response JSON in a good way, because I 
>> have the next code:
>>
>> if "product_id" in request.POST:
>> try:
>> id_producto = request.POST['product_id']
>> p = Pozo.objects.get(pk=id_producto)
>> mensaje = {"status":"True","product_id":p.id}
>> p.delete() # Elinamos objeto de la base de datos
>> return JsonResponse(mensaje)
>> except:
>> mensaje = {"status":"False"}
>> return JsonResponse(mensaje)
>>
>> And my JS function doesn't work with this code:
>>
>>var options = {
>> success:function(response)
>> {
>> if(response.status=="True"){
>> alert("Eliminado!");
>> var idProd = response.product_id;
>> var elementos= $(nombre_tabla+' >tbody >tr').length;
>> if(elementos==1){
>> location.reload();
>> }else{
>> $('#tr'+idProd).remove();
>> $(nombre_ventana_modal).modal('hide');
>> }
>> }else{
>> alert("Hubo un error al eliminar!");
>> $(nombre_ventana_modal).modal('hide');
>> };
>> }
>> };
>> $(nombre_formulario_modal).ajaxForm(options);
>> });
>>
>> And I don't know what I can do. Does anyone have any idea?
>>
>> -- 
>> 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...@googlegroups.com .
>> To post to this group, send email to django...@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/2cfc6283-ee2f-4280-b086-2dc1595855c8%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/e57dc93c-07a1-4d86-9155-0f0a76bde9fe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


matplotlib pyplot stop working

2015-02-19 Thread dk
I am using matplotlib.pyplot to generate a plot image, put it in a temp 
folder, 
and then use that to populate a webpage.

the problem is:
1) always display the same image,  I all ready deleted the image before 
creating the new one, 
I also set pyplot .close()  to close all my figures.

2) some times everything freeze and stop working.

my suspicions is since django is constantly running keeps the figure in the 
memory some how.   have any one got issues like this?
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4c7af20d-2be4-45b1-9132-be14f2ea7deb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: JSON Response

2015-02-19 Thread Vijay Khemlani
What do you mean with "in a good way"? Does your code work?

On Thu, Feb 19, 2015 at 4:14 PM, elcaiaimar  wrote:

> Hello,
>
> I was wondering how I can send a response JSON in a good way, because I
> have the next code:
>
> if "product_id" in request.POST:
> try:
> id_producto = request.POST['product_id']
> p = Pozo.objects.get(pk=id_producto)
> mensaje = {"status":"True","product_id":p.id}
> p.delete() # Elinamos objeto de la base de datos
> return JsonResponse(mensaje)
> except:
> mensaje = {"status":"False"}
> return JsonResponse(mensaje)
>
> And my JS function doesn't work with this code:
>
>var options = {
> success:function(response)
> {
> if(response.status=="True"){
> alert("Eliminado!");
> var idProd = response.product_id;
> var elementos= $(nombre_tabla+' >tbody >tr').length;
> if(elementos==1){
> location.reload();
> }else{
> $('#tr'+idProd).remove();
> $(nombre_ventana_modal).modal('hide');
> }
> }else{
> alert("Hubo un error al eliminar!");
> $(nombre_ventana_modal).modal('hide');
> };
> }
> };
> $(nombre_formulario_modal).ajaxForm(options);
> });
>
> And I don't know what I can do. Does anyone have any idea?
>
> --
> 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/2cfc6283-ee2f-4280-b086-2dc1595855c8%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/CALn3ei0zfAQg1QUap-_OcVKZchRg3ML7tee-3UzLUzBA0tVfwg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Seems like a geodjango bug with multiple databases

2015-02-19 Thread George Silva
I'm using with success two postgis enabled databases on a single
application, without quirks.

I have a read-only database, and a read/write database. No problems, so far.

On Thu, Feb 19, 2015 at 5:11 PM, Collin Anderson 
wrote:

> Hi,
>
> Interesting. What version of django is this?
>
> Here's something to try:
> Room.objects.using('another').select_related('hotel').get(pk=10)
>
> It could very well be an issue with GeoManager / GeoQuerySet.
>
> You also could ask on the geodjango list to see if anyone else has run
> into that.
>
> http://groups.google.com/group/geodjango
>
> Collin
>
>
> On Wednesday, February 18, 2015 at 9:45:15 AM UTC-5, Luan Nguyen wrote:
>>
>> I'm using geodjango and multiple databases, and experiencing a quite
>> weird situation, I guess it's a kind of bug but not absolutely sure since
>> I'm pretty new to Django.
>>
>> Here is how to reproduce the problem:
>> - Set up another database besides default:
>> DATABASES = {
>> 'default': {
>> 'ENGINE' : 'django.contrib.gis.db.backends.postgis'
>> ,
>> 'NAME' : 'issue1',
>> 'USER' : 'user',
>> 'PASSWORD' : 'password',
>> 'HOST' : '127.0.0.1',
>> 'OPTIONS' : {
>> 'autocommit' : True,
>> }
>> },
>> 'another': {
>> 'ENGINE' : 'django.contrib.gis.db.backends.postgis'
>> ,
>> 'NAME' : 'issue2',
>> 'USER' : 'user',
>> 'PASSWORD' : 'password',
>> 'HOST' : '127.0.0.1',
>> 'OPTIONS' : {
>> 'autocommit' : True,
>> }
>> },
>> }
>>
>> And two models:
>> from django.db import models as default_models
>> from django.contrib.gis.db import models
>> # Create your models here.
>> class Hotel(models.Model):
>> hotel_name = models.CharField(max_length=255)
>> objects = models.GeoManager()
>>
>> class Room(models.Model):
>> room_num = models.IntegerField()
>> hotel = models.ForeignKey(Hotel, null=True, blank=True)
>>
>> Add data into issue2 database (leave issue1 blank), then go into shell:
>> >>>h = Hotel.objects.using('another').all()[0]
>> >>> h.id
>> 9
>> >>>h.room_set.all()[0].id #=> room id 10 links to hotel id 9
>> 10
>> >>>r = Room.objects.using('another').get(pk=10)
>> >>>r.hotel
>> Traceback (most recent call last):
>> File "", line 1, in 
>> File "/Applications/MAMP/htdocs/Rainmaker/vir341/lib/python3.
>> 4/site-packages/django/db/models/fields/related.py
>> ",
>> line 572, in __get__
>> rel_obj = qs.get()
>> File "/Applications/MAMP/htdocs/Rainmaker/vir341/lib/python3.
>> 4/site-packages/django/db/models/query.py
>> ",
>> line 357, in get
>> self.model._meta.object_name)
>> multi.models.DoesNotExist: Hotel matching query does not exist.
>>
>> The thing is, if I create a hotel record on database issue1 with id of 9
>> then the last command works, so I guess it tried to look up in default
>> database. This doesn't have any problems if I use default manager for
>> Hotel, so I guess it's a bug?
>>
>  --
> 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/64d0f22e-ce10-4626-beef-5f99c63de787%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
George R. C. Silva
SIGMA Consultoria

http://www.consultoriasigma.com.br/

-- 
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/CAGyPVTuc5ecd-1xBvTT-_GKSbAAmGAgY_w0qSE6QptAfkoweYw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


JSON Response

2015-02-19 Thread elcaiaimar
Hello,

I was wondering how I can send a response JSON in a good way, because I 
have the next code:

if "product_id" in request.POST:
try:
id_producto = request.POST['product_id']
p = Pozo.objects.get(pk=id_producto)
mensaje = {"status":"True","product_id":p.id}
p.delete() # Elinamos objeto de la base de datos
return JsonResponse(mensaje)
except:
mensaje = {"status":"False"}
return JsonResponse(mensaje)

And my JS function doesn't work with this code:

   var options = {
success:function(response)
{
if(response.status=="True"){
alert("Eliminado!");
var idProd = response.product_id;
var elementos= $(nombre_tabla+' >tbody >tr').length;
if(elementos==1){
location.reload();
}else{
$('#tr'+idProd).remove();
$(nombre_ventana_modal).modal('hide');
}
}else{
alert("Hubo un error al eliminar!");
$(nombre_ventana_modal).modal('hide');
};
}
};
$(nombre_formulario_modal).ajaxForm(options);
});

And I don't know what I can do. Does anyone have any idea?

-- 
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/2cfc6283-ee2f-4280-b086-2dc1595855c8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Seems like a geodjango bug with multiple databases

2015-02-19 Thread Collin Anderson
Hi,

Interesting. What version of django is this?

Here's something to try:
Room.objects.using('another').select_related('hotel').get(pk=10)

It could very well be an issue with GeoManager / GeoQuerySet.

You also could ask on the geodjango list to see if anyone else has run into 
that.

http://groups.google.com/group/geodjango

Collin

On Wednesday, February 18, 2015 at 9:45:15 AM UTC-5, Luan Nguyen wrote:
>
> I'm using geodjango and multiple databases, and experiencing a quite weird 
> situation, I guess it's a kind of bug but not absolutely sure since I'm 
> pretty new to Django.
>
> Here is how to reproduce the problem:
> - Set up another database besides default:
> DATABASES = {
> 'default': {
> 'ENGINE' : 'django.contrib.gis.db.backends.postgis' 
> ,
> 'NAME' : 'issue1',
> 'USER' : 'user',
> 'PASSWORD' : 'password',
> 'HOST' : '127.0.0.1',
> 'OPTIONS' : {
> 'autocommit' : True,
> }
> },
> 'another': {
> 'ENGINE' : 'django.contrib.gis.db.backends.postgis' 
> ,
> 'NAME' : 'issue2',
> 'USER' : 'user',
> 'PASSWORD' : 'password',
> 'HOST' : '127.0.0.1',
> 'OPTIONS' : {
> 'autocommit' : True,
> }
> },
> }
>
> And two models:
> from django.db import models as default_models
> from django.contrib.gis.db import models
> # Create your models here.
> class Hotel(models.Model):
> hotel_name = models.CharField(max_length=255)
> objects = models.GeoManager()
>
> class Room(models.Model):
> room_num = models.IntegerField()
> hotel = models.ForeignKey(Hotel, null=True, blank=True)
>
> Add data into issue2 database (leave issue1 blank), then go into shell:
> >>>h = Hotel.objects.using('another').all()[0]
> >>> h.id
> 9
> >>>h.room_set.all()[0].id #=> room id 10 links to hotel id 9
> 10
> >>>r = Room.objects.using('another').get(pk=10)
> >>>r.hotel
> Traceback (most recent call last):
> File "", line 1, in 
> File "/
> Applications/MAMP/htdocs/Rainmaker/vir341/lib/python3.4/site-packages/django/db/models/fields/related.py
>  
> ",
>  
> line 572, in __get__
> rel_obj = qs.get()
> File "/
> Applications/MAMP/htdocs/Rainmaker/vir341/lib/python3.4/site-packages/django/db/models/query.py
>  
> ",
>  
> line 357, in get
> self.model._meta.object_name)
> multi.models.DoesNotExist: Hotel matching query does not exist.
>
> The thing is, if I create a hotel record on database issue1 with id of 9 
> then the last command works, so I guess it tried to look up in default 
> database. This doesn't have any problems if I use default manager for 
> Hotel, so I guess it's a bug?
>

-- 
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/64d0f22e-ce10-4626-beef-5f99c63de787%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Trouble changing from sqlite3 to postgres

2015-02-19 Thread Collin Anderson
Hi,

It seems strange that it would be trying to convert a "date" column to an 
integer.

Since you're creating a new database from scratch, you could try deleting 
your migrations and generating them from scratch to see if that helps.

Otherwise, what does your "app_1.0003_auto_20141126_2333" file have for 
operations?

Collin

On Tuesday, February 17, 2015 at 9:22:30 PM UTC-5, tony@gmail.com wrote:
>
> The error occurs during migration.
> The following shows the complete traceback.
> Thanks.
> 
> % python manage migrate
> WFK: BASE_DIR= /home/bill/django/wfkprojs/proj1
> WFK: STATIC_PATH= /home/bill/django/wfkprojs/proj1/app_1/static/
> WFK: MEDIA_ROOT= /home/bill/django/wfkprojs/proj1/app_1/media_root/
> WFK: MEDIA_URL= /media_root/
> Operations to perform:
>   Apply all migrations: contenttypes, app_1, sessions, auth, admin
> Running migrations:
>   Applying app_1.0003_auto_20141126_2333...Traceback (most recent call 
> last):
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/utils.py", line 
> 65, in execute
> return self.cursor.execute(sql, params)
> psycopg2.ProgrammingError: column "date" cannot be cast automatically to 
> type integer
> HINT:  Specify a USING expression to perform the conversion.
>
>
> The above exception was the direct cause of the following exception:
>
> Traceback (most recent call last):
>   File "manage.py", line 10, in 
> execute_from_command_line(sys.argv)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/core/management/__init__.py", 
> line 385, in execute_from_command_line
> utility.execute()
>   File 
> "/usr/local/lib/python3.3/site-packages/django/core/management/__init__.py", 
> line 377, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/core/management/base.py", 
> line 288, in run_from_argv
> self.execute(*args, **options.__dict__)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/core/management/base.py", 
> line 338, in execute
> output = self.handle(*args, **options)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/core/management/commands/migrate.py",
>  
> line 160, in handle
> executor.migrate(targets, plan, fake=options.get("fake", False))
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/migrations/executor.py", 
> line 63, in migrate
> self.apply_migration(migration, fake=fake)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/migrations/executor.py", 
> line 97, in apply_migration
> migration.apply(project_state, schema_editor)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/migrations/migration.py", 
> line 107, in apply
> operation.database_forwards(self.app_label, schema_editor, 
> project_state, new_state)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/migrations/operations/fields.py",
>  
> line 139, in database_forwards
> schema_editor.alter_field(from_model, from_field, to_field)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/schema.py", line 
> 473, in alter_field
> self._alter_field(model, old_field, new_field, old_type, new_type, 
> old_db_params, new_db_params, strict)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/schema.py", line 
> 626, in _alter_field
> params,
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/schema.py", line 
> 99, in execute
> cursor.execute(sql, params)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/utils.py", line 
> 81, in execute
> return super(CursorDebugWrapper, self).execute(sql, params)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/utils.py", line 
> 65, in execute
> return self.cursor.execute(sql, params)
>   File "/usr/local/lib/python3.3/site-packages/django/db/utils.py", line 
> 94, in __exit__
> six.reraise(dj_exc_type, dj_exc_value, traceback)
>   File "/usr/local/lib/python3.3/site-packages/django/utils/six.py", line 
> 549, in reraise
> raise value.with_traceback(tb)
>   File 
> "/usr/local/lib/python3.3/site-packages/django/db/backends/utils.py", line 
> 65, in execute
> return self.cursor.execute(sql, params)
> django.db.utils.ProgrammingError: column "date" cannot be cast 
> automatically to type integer
> HINT:  Specify a USING expression to perform the conversion.
>
>
> On Tuesday, February 17, 2015 at 4:39:27 PM UTC-8, Joel Burton wrote:
>>
>> The error is probably in code you wrote that uses the date field. Can you 
>> post the full traceback? That will let us see where the caller was that 
>> created the problem.
>>
>> On Tuesday, February 17, 2015 at 3:13:30 PM UTC-5, tony@gmail.com 
>> wrote:
>>>
>>> I have written a simple Django app (my first) that works with sqlite3 
>>> database.
>>> I want to change to postgres, but when I run the Django 1.7 migration 
>>> utility  with the comman

Re: Form Wizard: how to send instance_dict based on the request

2015-02-19 Thread Collin Anderson
Hi,

You could instead just override get_form_instance(step). That way you'll 
have access to self.request.

Collin

On Tuesday, February 17, 2015 at 8:26:30 PM UTC-5, Karim Gorjux wrote:
>
> Hello mates!
>
> I have some problems to understand how to set the view for 
> the NamedUrlSessionWizardView creating a instance_dict based on the user in 
> the request.
>
> in my urls.py
>
> url(r'wizard/new/(?P.+)/$',
> ServiceCUWizard.as_view(
>FORMS,   # the list of ['form_name', form_object]
>url_name='service:new_wizard_step',
>done_step_name='finished',
> ), name='new_wizard_step'),
>
> It works, I got all the forms as expected.
>
> The forms are modelforms and I would like to bound the instance if is 
> possible, but I can populate it only using the request. I think I could do 
> that subclassing def __init__, but the instance_dict is a class attribute, 
> how I can populate it?
>
> Thnak you
>
>
>
> -- 
> Karim N. Gorjux
>  

-- 
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/c7e931b5-1671-4570-be34-6894fc97c43c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Can migrated apps depend on unmigrated apps?

2015-02-19 Thread Collin Anderson
Hi Carsten,

I in my experience, it _sometimes_ works to have migrated apps depend on 
unmigrated apps.

If you haven't yet, you could try generating migrations for the unmigrated 
app, and reference them using MIGRATION_MODULES.

Collin

On Tuesday, February 17, 2015 at 5:00:26 PM UTC-5, Carsten Fuchs wrote:
>
> Hi Michael, 
>
> Am 17.02.2015 um 22:44 schrieb Michael Pöhn: 
> > This is all covered in Djangos documentation... 
> > https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies 
>
> Well, no... please see below. 
>
> > Let me paste the relevant parts for you: 
> > 
> > »Be aware, however, that unmigrated apps cannot depend on migrated apps, 
> [...]« 
>
> This explains that unmigrated apps cannot depend on migrated apps. 
>
> My question is about the opposite case: Can migrated apps depend on 
> unmigrated apps? I've explained the apparent problem in greater detail 
> in my original post. 
>
> Best regards, 
> Carsten 
>
>

-- 
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/6ea03841-50de-413d-9f7c-5769b497b550%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 1.7.4, PostgreSQL: Migrate FK to M2M?

2015-02-19 Thread Andrew Pinkham
On Feb 19, 2015, at 11:54 AM, Tom Evans  wrote:
> Django accepts the keyword argument "null" on all fields, but it is
> meaningless for an M2M.

That is an excellent point. That's what I get for writing this up based on 
memory late at night.

Sorry for the error.

Andrew

-- 
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/BD03473D-D6FB-416F-9A64-8C19E948F805%40andrewsforge.com.
For more options, visit https://groups.google.com/d/optout.


Re: Handling FormSet client side with javascript

2015-02-19 Thread Collin Anderson
Hi,

Sorry for the late reply. Does simply using {{ formset.media }} work?

Collin

On Friday, February 13, 2015 at 11:02:31 AM UTC-5, aRkadeFR wrote:
>
> Hello everyone, 
>
> I'm using FormSet in order to add multiple object at once on 
> a view. To have a more user friendly approach, I created a 
> 'my.formset.js' file and I need to include a 'jquery.formset.js' lib 
> to add/remove row of the formset (client side) and edit the 
> formset management information. 
>
> My idea to resolve this problem was to include these two 
> javascript media file everytime I'm using a formset. 
>
> A bit like every media js file for widgets :) 
>
> So my first attempt was something like that: 
> ``` 
> class BaseFormSet(BaseInlineFormSet): 
>  class Media: 
>  js = ("my.formset.js", "jquery.formset.js", ) 
> ``` 
>
> but this doesnt render these js files with formset.media.render_js(). 
>
> My second attempt was: 
> ``` 
> formset.media.add_js( ["my.formset.js", "jquery.formset.js", ]) 
> ``` 
>
> My last attempt: 
> ``` 
> form = formset.forms[0] 
> formset.forms[0].fields[form.fields.keys()[0]].media.add_js(["my.formset.js", 
>
> "jquery.formset.js", ]) 
> ``` 
>
> Still not working cause the .media._js is regenerating the media js 
> files. 
>
> The only solution so far I have, provided by @tbaxter, is to 
> include all my js files in all my application, and initialize/use 
> the formset/widgets javascript only on certain condition. 
>
> I don't like the idea of including my js application wide. It's 
> gonna overload all my pages for nothing (my js files are 
> completely standalone) when there is no FormSet. 
>
> Can I have your tought on this probleme, and what solution 
> you have in mind? 
>
> Thank you, 
>

-- 
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/eb5af3a3-d09f-4562-b290-fec7f763e74e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: JsonResponse and Ajax function.

2015-02-19 Thread Collin Anderson
Hi,

Sorry for the late reply. Do you need to use JSON.parse(response).status?

Collin

On Tuesday, February 10, 2015 at 8:33:58 AM UTC-5, elcaiaimar wrote:
>
> Hello!
>
> I've written a code to delete db registers and I want to call an ajax 
> function when the delete is done.
> At the moment, when I click my delete button I only receive a message: 
> {"status":"True","product_id":p.id} or {"status":"False"} 
> and this should be sent to the ajax function and I shoud have an alert 
> saying to me: product has been removed.
> I don't know why, probably there is something wrong in the relation of my 
> JsonResponse and ajax function.
>
> I put my code below. Does anybody know how can I fix this?
> Thank you very much!
>
> *template*:
>
>  
>   {% csrf_token %}
>   
>aria-hidden="true">Cerrar button>
>   Eliminar
>  
>
> *views.py:*
>
> if request.method=="POST":
> if "product_id" in request.POST:
> try:
> id_producto = request.POST['product_id']
> p = Pozo.objects.get(pk=id_producto)
> mensaje = {"status":"True","product_id":p.id}
> p.delete() # Elinamos objeto de la base de datos
> return JsonResponse(mensaje)
> except:
> mensaje = {"status":"False"}
> return JsonResponse(mensaje)
>
>
>
> *Ajax.js:*// Autor: @jqcaper
> // Configuraciones Generales
> var nombre_tabla = "#tabla_productos"; // id
> var nombre_boton_eliminar = ".delete"; // Clase
> var nombre_formulario_modal = "#frmEliminar"; //id
> var nombre_ventana_modal = "#myModal"; // id
> // Fin de configuraciones
> $(document).on('ready',function(){
> $(nombre_boton_eliminar).on('click',function(e){
> e.preventDefault();
> var Pid = $(this).attr('id');
> var name = $(this).data('name');
> $('#modal_idProducto').val(Pid);
> $('#modal_name').text(name);
> });
> var options = {
> success:function(response)
> {
> if(response.status=="True"){
> alert("Eliminado!");
> var idProd = response.product_id;
> var elementos= $(nombre_tabla+' >tbody >tr').length;
> if(elementos==1){
> location.reload();
> }else{
> $('#tr'+idProd).remove();
> $(nombre_ventana_modal).modal('hide');
> }
> }else{
> alert("Hubo un error al eliminar!");
> $(nombre_ventana_modal).modal('hide');
> };
> }
> };
> $(nombre_formulario_modal).ajaxForm(options);
> });
>

-- 
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/a798d66d-b9eb-4698-98fe-8944362b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django: get profiles having auth.Group as foreign key

2015-02-19 Thread Collin Anderson
Hi,

Sorry for the late reply. Do you just want something like this?

{% for dashboard in group.dashboard_set.all %}
 {{ dashboard.d_name }}
 etc
{% endfor %}

Collin

On Tuesday, February 10, 2015 at 12:41:15 AM UTC-5, itsj...@gmail.com wrote:
>
> I have an model which uses auth.models Group as foreign key called 
> Dashboard:-
>
> 
>
> 
>
> class Dashboard(models.Model):
> d_name = models.CharField(max_length=200)
> d_description = models.CharField(max_length=200)
> d_url = models.CharField(max_length=200)
> d_status = models.CharField(max_length=200)
> owner = models.ForeignKey(Group)
> 
> def __str__(self):return self.d_name
>
> 
>
> my views.py is:-
>
> 
>
> 
>
> def custom_login(request):
> if request.user.is_authenticated():
> return HttpResponseRedirect('dashboards')
> return login(request, 'login.html', authentication_form=LoginForm)
>
> def custom_logout(request):
> return logout(request, next_page='/')
>
> def user(request):
> context = {'user': user, 'groups': request.user.groups.all()}
> return render_to_response('registration/dashboards.html', context, 
> context_instance=RequestContext(request))
>
> 
>
> and here using this dashboards.html i want to display the dashboards by 
> using the Group_name which i will get as a result of **group.name** :-
>
> 
>
> 
>
> {% extends "base.html" %}
> {% block content %}
> {% if user.is_authenticated %}
> Welcome, {{ request.user.get_username }}. 
> {% else %}
> Welcome, new user. Please log in.
> {% endif %}
>
> 
> {% for group in groups %}
> 
> {{ group.name }} -
> 
> {{ dashboards.d_name }}{% if not forloop.last %},{% endif 
> %}
> 
> 
> {% endfor %}
> 
>
>
>
> {% endblock %}
>
> 
>
> here i have mentioned all the supporting information for my problem, 
> please let me know if there are any solution.
>

-- 
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/03466a23-b48a-45e8-8a1f-eeda1c23701b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Custom model field and custom widget

2015-02-19 Thread Collin Anderson
Hi,

Sorry for the late reply. Check out editable=False if you haven't.

Collin

On Friday, January 30, 2015 at 9:03:41 AM UTC-5, Thomas Weholt wrote:
>
> Hi,
>
> I need to create a custom django model field, a varchar(10) field which 
> has a calculated value set on save on the model using it and then never 
> changed. This should happen automatically. This field should appear as 
> hidden or read-only in forms and it would be nice to handle the render 
> output if the field is accessed in templates. The calculated value 
> generated on save must access the database and look into a seperate table 
> to calculate its value, ie. I need to control the generation of the value 
> it gets.
>
> Any ideas or hints?
>

-- 
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/2195b874-bab4-4d0c-b13e-a9a144d1348b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 1.7.4, PostgreSQL: Migrate FK to M2M?

2015-02-19 Thread Tom Evans
On Thu, Feb 19, 2015 at 4:56 AM, Andrew Pinkham  wrote:
> Hi Micky,
> When I had to migrate FK->M2M, I found that hand-hacking a migration file was 
> the way to go. I wrote a multiple operation migration class that did the 
> following:
>
> 1. create a M2M, nullable field, and set all defaults to null

An M2M link between two models is created by inserting a row in to a
join table that contains a foreign key to the first model and a
foreign key to the second model. If they are not linked, there is no
row in the table with those keys.

How will either of those keys ever be null?

Django accepts the keyword argument "null" on all fields, but it is
meaningless for an M2M.

Cheers

Tom

-- 
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/CAFHbX1KCevqKtBmmws95c11r0DY%2BRUtWhEKFw3BXWbBZZp-yqQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: how to handle race conditions?

2015-02-19 Thread Carl Meyer
Hi Abraham,

On 02/19/2015 03:41 AM, Abraham Varricatt wrote:
> I've heard of the term 'atomic operations' , but didn't realize it had
> support in django. Thank you for the detailed explanation!

You're welcome.

> It's an interesting idea - to mark the field in the database as a
> positive integer, but since it doesn't apply to all DBs, I think I'll
> keep it aside for now. 

This is a bit of a tangent, but when you get to the point of worrying
about things like race conditions and transactional behavior, your life
will be easier if you simply choose a database for your project and
don't worry about making everything cross-database portable.

And, frankly, if you're concerned about data integrity, your life will
be easier if the database server you choose is PostgreSQL.

Your ability to use Django effectively is much greater if you know your
specific database well, and aren't afraid to use database-specific
features and write some raw SQL now and then. Limiting yourself to
cross-database-portable ORM features is a significant handicap, one
which I think only separately-distributed reusable apps should take on.

In your particular case, without a database-level check constraint on
the quantity field, it becomes much trickier to ensure that quantity
can't go negative.

> @Waitman,
> 
> Don't think I've ever come across the term 'backorder', but its an
> interesting concept. And very appreciated, from the business angle. I
> need to think more on this.

Yes - I should have said more clearly that my answer was intended as a
primer on basic atomicity and locking concepts, not a treatise on
shopping cart user experience. It's quite likely that for a production
shopping cart you'd want significantly more sophisticated behavior than
I covered.

Carl

-- 
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/54E61D6D.2030006%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: Struggling with formsets

2015-02-19 Thread aRkadeFR

Hello,

Can we have the template?

Did you rendered the hidden fields id of your forms ?

Dump (by printing) the request.POST informations to see
if you received any "id" :)



On 02/19/2015 04:25 PM, Werner Brand wrote:
I cannot seem to figure this, although I suspects it is really 
elementary:


I have two models:

class Employee(models.Model):

id_number = models.CharField(max_length=13)

surname = models.CharField(max_length=100)

name =  models.CharField(max_length=100)


class Payslip(models.Model):

surname = models.CharField(max_length=100)
name =  models.CharField(max_length=100)

salary = models.DecimalField(max_digits=20, decimal_places=2)


In my forms:

class PayslipForm(ModelForm):

class Meta:

model = Payslip

fields = ['surname', 'name', 'salary']


PayslipFormSet = modelformset_factory(Payslip, extra=0)


In views.py:

def Payslip(request):

employee = Employee.objects.all()

formset = PayslipFormSet(queryset=employee)

context = {'formset': formset}

return render(request, 'file.html', context)


def PayslipSubmit(request):

f = PayslipFormSet(request.POST)

if f.is_valid():

f.save()

return HttpResponse('Submitted')

else:

return HttpResponse(f.errors)


The problem is that when I submit I get the following each form in 
formset:


  * id
  o Select a valid choice. That choice is not one of the available
choices.

I hope someone can help!

--
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/8c766350-f426-475c-aac5-15f42952ce00%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/54E61AC4.8040504%40arkade.info.
For more options, visit https://groups.google.com/d/optout.


Re: Doubt

2015-02-19 Thread Andrew Pinkham
On Feb 19, 2015, at 7:48 AM, sriraag paawan  wrote:
> Hello guys i am Paawan and i am new to Python Django.. i was getting an error 
> like "activate.bat is not recognised" when installing virtualenv. I am unable 
> to work with environment variable WORKON and version of Django... 

We need way more information to help you.

What system, version of Python? How are you installing virtualenv? What command 
creates the error? What is the full output of the error?

Frnakly, I would recommend Googling for the output of your error and using 
StackOverflow for help first. There are a lot of good answers there. I'm sure 
people on this mailing list will help, but this is really a better place to ask 
about Django rather than installation problems with virtualenv.

I also heartily recommend virtualenv_wrapper.

Andrew

-- 
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/12E67085-4307-48DF-AB24-325E3CE81DA6%40andrewsforge.com.
For more options, visit https://groups.google.com/d/optout.


Re: Modify Installed_Apps settings

2015-02-19 Thread Andrew Pinkham
I am learning all sorts of things about Django's testing system (instead of 
actually getting work done).

The database schema is actually created via a call create_test_db() called on 
line 366 of setup_databases() in DiscoverRunner in django/test/runner.py. It's 
within this function, found in django/db/backends/base/creation.py, that 
migrate is called on available apps in Installed_Apps (via call_command!).

I was under the impression that code provided by TransactionTestCase was where 
the test database was (re-)created and destroyed throughout the lifetime of the 
test suite. As it turns out, while the code in TransactionTestCase loads and 
flushes data, it never touches the schema of the database (afaik).

This makes sense, as it seriously speeds up testing, as database creation is 
expensive.

Turns out, by simply overriding setUp and tearDown to use call_command with 
migrate, I can create the schema I desire.

# override/tests.py
from django.db import connections   

from django.test import TestCase, override_settings, modify_settings   
from django.core.management import call_command 

@override_settings(
ROOT_URLCONF='override.urls')
@modify_settings(
INSTALLED_APPS={'prepend': {'override'}})
class OverrideTests(TestCase):

def setUp(self):
super().setUp()
for db in connections:
call_command(
'migrate',
'override',
verbosity=0,
interactive=False,
database=db,
test_flush=True)

def tearDown(self):
for db in connections:
call_command(
'migrate',
'override',
'zero',
verbosity=0,
interactive=False,
database=db,
test_flush=True)
super().tearDown()

This is, of course, quite slow, as each of my tests results in a database 
schema change.

I'm thus trying to get this working with setUpClass and tearDownClass.

@classmethod
def setUpClass(cls):
super().setUpClass()
for db in connections:
call_command(
'migrate',
'override',
verbosity=0,
interactive=False,
database=db,
test_flush=True)

@classmethod
def tearDownClass(cls):
for db in connections:
call_command(
'migrate',
'override',
'zero',
verbosity=0,
interactive=False,
database=db,
test_flush=True)
super().tearDownClass()

My understanding of TransactionTestCase (and the interaction with the 
decorators) makes me think this is possible, but at the moment, I'm getting the 
following error:

django.core.management.base.CommandError: App 'override' does not have 
migrations (you cannot selectively sync unmigrated apps)

I am also uncertain if this is a good idea, as I'm not clear as to whether 
TestCase will flush the data in the unexpected table (ie: will tests methods 
still be isolated?).

Any help or ideas welcome.

Andrew

-- 
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/44D85C35-A483-47AB-891B-5631EB76D91E%40andrewsforge.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to install django in redhat where i have python 2.6 and 2.7 and i need to install django in python 2.7

2015-02-19 Thread Tom Evans
On Thu, Feb 19, 2015 at 1:27 PM, SHINTO PETER  wrote:
> How to install django in redhat where i have python 2.6 and 2.7 and i need
> to install django in python 2.7
>

You use scl:

http://developerblog.redhat.com/2013/02/14/setting-up-django-and-python-2-7-on-red-hat-enterprise-6-the-easy-way/

Cheers

Tom

-- 
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/CAFHbX1JnTKtcZDEoKMvfhhQ0JrJPjN9Z5JNMVrVjMVQyDvt%2Bow%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ImageField isn't working

2015-02-19 Thread Valéria Pacheco
Thank you very much!
it worked!
Both solutions combined.
I'm still trying to understand what happened but thank you!! :)

2015-02-19 16:18 GMT+00:00 Tom Lockhart :

> On Feb 19, 2015, at 8:03 AM, Valéria Pacheco 
> wrote:
>
> Hello! I'm a newbie in Django and Python, I'm trying to use the ImageField
> property.
> The problem is represented in the attachment images.
> The uploading of the image works fine, but when trying to access it, the
> link seems to be broken.
> I already checked for answers online but neither seems to work.
>
>
> The URL you are trying seems to be
> /admin/backOffice/product/12/media/images/teste_processo.jpg/ which is not
> likely to work.
>
> In my development server settings.py I’ve got the following:
>
> MEDIA_URL = "/media/"
> MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))
>
> and I’ve made a media/ directory inside my project area. Then you can find
> the image with a URL something like:
>
> /media/images/teste_processo.jpg
>
> (which may already be the case for you; look for the uploaded file and use
> a URL prefixed with “/media” then the path to the file).
>
> hth
>
> - Tom
>
>
>
>
> --
> 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/8cf5041c-2ad7-40ec-9243-d4e1a928013e%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
> 
>
>
>
>  --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/Px6Iqhl-ge8/unsubscribe.
> To unsubscribe from this group and all its topics, 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/F7228E20-08EF-4841-BFF2-AD5FA064CF82%40gmail.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Cumprimentos,
Valéria Pacheco

*contacto móvel *: 913473039



*:)*

-- 
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/CAMbyHecNqF7Ra3yFGjscnbFPZmVtmqWbLNNjjruCDUOzTVsb4A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Doubt

2015-02-19 Thread sriraag paawan
Hello guys i am Paawan and i am new to Python Django.. i was getting an 
error like "activate.bat is not recognised" when installing virtualenv. I 
am unable to work with environment variable WORKON and version of Django... 

So please help me guys 

Thank u 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/9eec1332-6e89-4ad7-82a4-0ad8593f587e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Struggling with formsets

2015-02-19 Thread Werner Brand
I cannot seem to figure this, although I suspects it is really elementary:

I have two models:

class Employee(models.Model):

id_number = models.CharField(max_length=13)

surname = models.CharField(max_length=100)

name =  models.CharField(max_length=100)


class Payslip(models.Model):

surname = models.CharField(max_length=100)
name =  models.CharField(max_length=100)

salary = models.DecimalField(max_digits=20, decimal_places=2)


In my forms:

class PayslipForm(ModelForm):

class Meta:

model = Payslip

fields = ['surname', 'name', 'salary']


PayslipFormSet = modelformset_factory(Payslip, extra=0)


In views.py:

def Payslip(request):

employee = Employee.objects.all()

formset = PayslipFormSet(queryset=employee)

context = {'formset': formset}

return render(request, 'file.html', context)


def PayslipSubmit(request):

f = PayslipFormSet(request.POST)

if f.is_valid():

f.save()

return HttpResponse('Submitted')

else:

return HttpResponse(f.errors) 


The problem is that when I submit I get the following each form in formset:

   - id
  - Select a valid choice. That choice is not one of the available 
  choices.
   
I hope someone can help!
 

 

 

 

 

 

 

 

 

 

 

 

 

 

-- 
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/8c766350-f426-475c-aac5-15f42952ce00%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to install django in redhat where i have python 2.6 and 2.7 and i need to install django in python 2.7

2015-02-19 Thread Matthias Runge
On 19/02/15 14:27, SHINTO PETER wrote:
> How to install django in redhat where i have python 2.6 and 2.7 and i
> need to install django in python 2.7 
> 
Do you have the possibility to upgrade to RHEL 7? That has python2.7 on
board.
Btw. there is a Django-1.6 package for RHEL7 on EPEL package repository.

Matthias

-- 
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/54E5EB64.3040600%40matthias-runge.de.
For more options, visit https://groups.google.com/d/optout.


Re: ImageField isn't working

2015-02-19 Thread Tom Lockhart
On Feb 19, 2015, at 8:03 AM, Valéria Pacheco  wrote:

> Hello! I'm a newbie in Django and Python, I'm trying to use the ImageField 
> property.
> The problem is represented in the attachment images.
> The uploading of the image works fine, but when trying to access it, the link 
> seems to be broken. 
> I already checked for answers online but neither seems to work.

The URL you are trying seems to be 
/admin/backOffice/product/12/media/images/teste_processo.jpg/ which is not 
likely to work.

In my development server settings.py I’ve got the following:

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/"))

and I’ve made a media/ directory inside my project area. Then you can find the 
image with a URL something like:

/media/images/teste_processo.jpg

(which may already be the case for you; look for the uploaded file and use a 
URL prefixed with “/media” then the path to the file).

hth

- Tom


> 
> 
> -- 
> 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/8cf5041c-2ad7-40ec-9243-d4e1a928013e%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/F7228E20-08EF-4841-BFF2-AD5FA064CF82%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ImageField isn't working

2015-02-19 Thread Jorge Andrés Vergara Ebratt
Hello Valéria,

That's Django's default, it doesn't handle media files by itself, if you
are in development you can add this line to urls.py

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Don't forget you need to import static and settings:

from django.conf import settings
from django.conf.urls.static import static

That should work... For development only, in production use something like
Nginx or Apache



On Thu Feb 19 2015 at 11:03:32 AM Valéria Pacheco <
valeriacspach...@gmail.com> wrote:

> Hello! I'm a newbie in Django and Python, I'm trying to use the ImageField
> property.
> The problem is represented in the attachment images.
> The uploading of the image works fine, but when trying to access it, the
> link seems to be broken.
> I already checked for answers online but neither seems to work.
>
>  --
> 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/8cf5041c-2ad7-40ec-9243-d4e1a928013e%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/CAAeX05ErbyhORMmF87xZhRySkN7QHb3gzYT1u7x%3D9mDx27AS3w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ImageField isn't working

2015-02-19 Thread Lucas Klassmann
Hi Valéria,

Try verify if that support for statics files is correctly configured.

Check this: https://docs.djangoproject.com/en/1.7/howto/static-files/

Before read the documentation, check which version of your django is
installed.

Cheers.

On Thu, Feb 19, 2015 at 2:03 PM, Valéria Pacheco  wrote:

> Hello! I'm a newbie in Django and Python, I'm trying to use the ImageField
> property.
> The problem is represented in the attachment images.
> The uploading of the image works fine, but when trying to access it, the
> link seems to be broken.
> I already checked for answers online but neither seems to work.
>
>  --
> 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/8cf5041c-2ad7-40ec-9243-d4e1a928013e%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Lucas Klassmann
Desenvolvedor de Software

Email: lucasklassm...@gmail.com
Web site: http://www.lucasklassmann.com

-- 
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/CAOz50pJCcFxB-eA31hvzsGHiXcUSfof9OUwVV_USo8WTicb0Ew%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Sqlite3 to Postgres Migration?

2015-02-19 Thread Tom Lockhart
On Feb 18, 2015, at 11:04 PM, talex  wrote:

> I have a functioning Django application that is based on sqlite3, 
> but I want to change to using Postgres.

I’ll point out for the benefit of others who might be getting started: Postgres 
is a full featured database and supports the full range of Django features and 
add-ons including GeoDjango. Starting development with a production-quality 
database already in place is not much more work and will save grief later on.

Usually I’d end with “hth”, but this is no help at all for talex…

- Tom

-- 
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/9963605E-7243-4827-AD56-10544AB28634%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Sqlite3 to Postgres Migration?

2015-02-19 Thread Andrew Pinkham
On Feb 19, 2015, at 1:04 AM, talex  wrote:
> Am I correct that use of "python makemigrations" followed by
> "python migrate", should copy the existing data into Postgres
> and leave me with a working application?

I'm afraid not.

Migration allows for predictable and reversible alterations to the database 
structure. It's an excellent tool for modifying the schema (tables, columns) of 
a database. It is possible to use migrations for data (rows), but you typically 
need to modify the migration to achieve your goal.

Migrations are not intended for moving data from one database to another. You 
might be able to use Django to help achieve your goal, but it's not magic. To 
start with, you will need both both databases to be connected to your Django 
site - if you disconnect your SQLite database, then all the data in it is 
unavailable to you. Django won't know how to get to it anymore.

You might find my article about migrations interesting:
http://afrg.co/updj17/a2

> Instead what is happening is that "python migrate" gives
> the following error and hint:
> 
>  django.db.utils.ProgrammingError: column "date" cannot be cast automatically 
> to type integer
>  HINT:  Specify a USING expression to perform the conversion.
> 
> How can I apply this hint to make this work?

I'm unfamiliar with this error, but I suspect your problem lies in the 
migration files. What files exist in `/app_name/migrations/` ? Those are the 
files that `./manage.py migrate` execute with.

Andrew

-- 
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/5DE5783C-4AA5-4884-B369-DFA1F305A81D%40andrewsforge.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to install django in redhat where i have python 2.6 and 2.7 and i need to install django in python 2.7

2015-02-19 Thread Tom Lockhart
On Feb 19, 2015, at 5:27 AM, SHINTO PETER  wrote:

> How to install django in redhat where i have python 2.6 and 2.7 and i need to 
> install django in python 2.7  

Use virtualenv to select and install python 2.7 from your existing installation 
into a separate place. There is a redhat package for virtualenv. Then use pip 
(which will be installed in that separate place) to install all of the other 
python packages.

You can use an existing postgres installation but I’d recommend configuring a 
new data area for it.

hth

Tom

> 
> -- 
> 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/8feed982-d4e5-41a4-a1f5-463589711961%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/2078B72A-2153-4BD8-A3DE-1D80EAF189C1%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to install django in redhat where i have python 2.6 and 2.7 and i need to install django in python 2.7

2015-02-19 Thread Vijay Khemlani
you can compile python locally

On Thu, Feb 19, 2015 at 10:27 AM, SHINTO PETER  wrote:

> How to install django in redhat where i have python 2.6 and 2.7 and i need
> to install django in python 2.7
>
> --
> 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/8feed982-d4e5-41a4-a1f5-463589711961%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/CALn3ei1paH45ZfbmCRRAGNOZHWdp7wGWWon0o-Qqg0uiMP2QPw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


How to host django application in redhat using virtual environment?

2015-02-19 Thread SHINTO PETER
How to host django application in redhat using virtual environment?

-- 
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/9116a3f5-4397-48b2-85eb-53d5145f302f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to install django in redhat where i have python 2.6 and 2.7 and i need to install django in python 2.7

2015-02-19 Thread SHINTO PETER
How to install django in redhat where i have python 2.6 and 2.7 and i need 
to install django in python 2.7  

-- 
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/8feed982-d4e5-41a4-a1f5-463589711961%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: how to handle race conditions?

2015-02-19 Thread Abraham Varricatt
@Carl,

I've heard of the term 'atomic operations' , but didn't realize it had 
support in django. Thank you for the detailed explanation!

It's an interesting idea - to mark the field in the database as a positive 
integer, but since it doesn't apply to all DBs, I think I'll keep it aside 
for now. 

@Waitman,

Don't think I've ever come across the term 'backorder', but its an 
interesting concept. And very appreciated, from the business angle. I need 
to think more on this.

Thanks for the help,
Abraham V.






On Thursday, February 19, 2015 at 12:03:57 AM UTC+5:30, Carl Meyer wrote:
>
> Hi Abraham, 
>
> On 02/17/2015 10:01 PM, Abraham Varricatt wrote: 
> > I'm trying to make an app where folks can order X quantity of an item. 
> > The condition is that the order should only be made if inventory exists. 
> > Assume that we have stock of Y items. This means that only if Y >= X 
> > should we allow the sale to go through. And once we accept an order, the 
> > inventory should be updated so that Y = Y - X. 
>
> In general, the construct you need is called a "transaction", which 
> ensures that a series of database operations will either all be 
> committed together, or rolled back if they can't be successfully 
> completed. The Django API for that is "django.db.transaction.atomic". 
>
> > The way I've currently implemented this is with a pair of getter/setter 
> > methods. I have a model 'ShopItem' which has two fields called 
> > 'quantity' and 'name' (this is unique). I've made a utility class 
> > (outside model source file) where I've made the following 2 functions; 
> > 
> > def get_quantity(name): 
> >   stuff_left = 0 
> >   try: 
> > item = ShopItem.objects.get(name=name) 
> > stuff_left = item.quantity 
> >   except ShopItem.DoesNotExist: 
> > pass # return zero 
> >   return stuff_left 
> > 
> > def set_quantity(name, stuff_left): 
> >   item = ShopItem.objects.get(name=name) 
> >   item.quantity = stuff_left 
> >   item.save() 
> > 
> > 
> > Elsewhere in my project, if I need to display the remaining quantity of 
> > an item in a view, I'll pass the result from get_quantity(). At sale 
> > time here is how I update things; 
> > 
> > def customer_buy(name, number): 
> >   temp = get_quantity(name) 
> >   if (temp >= number): 
> > temp = temp - number 
> > set_quantity(name, temp) 
> > // do other things 
> >   else: 
> > // sale failed, do something else 
> > 
> > I tested this on my system and things appear to work. But I'm concerned 
> > about race conditions. What if two different customers came in to buy 
> > the same item? As in; if I only have 7 items in stock, but one customer 
> > came to buy 6nos and another 5nos. There is a chance (as per my 
> > understanding) that both orders will be accepted - even worse, my 
> > inventory will not accurately reflect the updated situation. 
> > 
> > Any ideas on how this issue can be resolved? I've come across this 
> > - 
> https://docs.djangoproject.com/en/1.6/ref/models/instances/#updating-attributes-based-on-existing-fields
>  
> > , but not sure how to apply it to the current scenario. 
>
> If we're only considering the changes to your ShopItem model, you don't 
> even need an explicit transaction to avoid race conditions, because (as 
> the docs you linked show) the operation can be completed in a single 
> database query, which is inherently atomic. This is how it would look to 
> do it in a single query: 
>
> from django.db.models import F 
>
> def customer_buy(name, number): 
> ShopItem.objects.filter( 
> name=name).update(quantity=F('quantity')-number) 
>
> You want this to fail if someone tries to purchase a larger quantity 
> than are available. The best way to do this is via a database-level 
> "check constraint" on the column, such that the database itself will 
> never permit a negative quantity. If you make 'quantity' a 
> PositiveIntegerField (the name is wrong, it actually allows zero too) on 
> your model, and your database is PostgreSQL (or Oracle), Django will add 
> this constraint for you automatically. Then if someone tries to purchase 
> more than are available, you'll get an IntegrityError, which you'd want 
> to catch and handle in some way: 
>
> from django.db import IntegrityError 
> from django.db.models import F 
>
> class InsufficientInventory(Exception): 
> pass 
>
> def customer_buy(name, number): 
> try: 
> ShopItem.objects.filter( 
> name=name).update(quantity=F('quantity')-number) 
> except IntegrityError: 
> # signal to the calling code that the purchase failed - the 
> # calling code should catch this exception and notify the 
> # user that the purchase failed due to lack of inventory, 
> # and tell them the updated available quantity 
> raise InsufficientInventory() 
>
> You also want this function to handle the case where the giv

Re: how to handle race conditions?

2015-02-19 Thread aRkadeFR


On 02/19/2015 01:04 AM, Mario Gudelj wrote:

Great reply. You're a champion, Carl!



Couldn't say more. Very thorough answer and interesting :)

On 19 February 2015 at 05:31, Carl Meyer > wrote:


Hi Abraham,

On 02/17/2015 10:01 PM, Abraham Varricatt wrote:
> I'm trying to make an app where folks can order X quantity of an
item.
> The condition is that the order should only be made if inventory
exists.
> Assume that we have stock of Y items. This means that only if Y >= X
> should we allow the sale to go through. And once we accept an
order, the
> inventory should be updated so that Y = Y - X.

In general, the construct you need is called a "transaction", which
ensures that a series of database operations will either all be
committed together, or rolled back if they can't be successfully
completed. The Django API for that is "django.db.transaction.atomic".

> The way I've currently implemented this is with a pair of
getter/setter
> methods. I have a model 'ShopItem' which has two fields called
> 'quantity' and 'name' (this is unique). I've made a utility class
> (outside model source file) where I've made the following 2
functions;
>
> def get_quantity(name):
>   stuff_left = 0
>   try:
> item = ShopItem.objects.get(name=name)
> stuff_left = item.quantity
>   except ShopItem.DoesNotExist:
> pass # return zero
>   return stuff_left
>
> def set_quantity(name, stuff_left):
>   item = ShopItem.objects.get(name=name)
>   item.quantity = stuff_left
>   item.save()
>
>
> Elsewhere in my project, if I need to display the remaining
quantity of
> an item in a view, I'll pass the result from get_quantity(). At sale
> time here is how I update things;
>
> def customer_buy(name, number):
>   temp = get_quantity(name)
>   if (temp >= number):
> temp = temp - number
> set_quantity(name, temp)
> // do other things
>   else:
> // sale failed, do something else
>
> I tested this on my system and things appear to work. But I'm
concerned
> about race conditions. What if two different customers came in
to buy
> the same item? As in; if I only have 7 items in stock, but one
customer
> came to buy 6nos and another 5nos. There is a chance (as per my
> understanding) that both orders will be accepted - even worse, my
> inventory will not accurately reflect the updated situation.
>
> Any ideas on how this issue can be resolved? I've come across this
> -

https://docs.djangoproject.com/en/1.6/ref/models/instances/#updating-attributes-based-on-existing-fields
> , but not sure how to apply it to the current scenario.

If we're only considering the changes to your ShopItem model, you
don't
even need an explicit transaction to avoid race conditions,
because (as
the docs you linked show) the operation can be completed in a single
database query, which is inherently atomic. This is how it would
look to
do it in a single query:

from django.db.models import F

def customer_buy(name, number):
ShopItem.objects.filter(
name=name).update(quantity=F('quantity')-number)

You want this to fail if someone tries to purchase a larger quantity
than are available. The best way to do this is via a database-level
"check constraint" on the column, such that the database itself will
never permit a negative quantity. If you make 'quantity' a
PositiveIntegerField (the name is wrong, it actually allows zero
too) on
your model, and your database is PostgreSQL (or Oracle), Django
will add
this constraint for you automatically. Then if someone tries to
purchase
more than are available, you'll get an IntegrityError, which you'd
want
to catch and handle in some way:

from django.db import IntegrityError
from django.db.models import F

class InsufficientInventory(Exception):
pass

def customer_buy(name, number):
try:
ShopItem.objects.filter(
name=name).update(quantity=F('quantity')-number)
except IntegrityError:
# signal to the calling code that the purchase failed
- the
# calling code should catch this exception and notify the
# user that the purchase failed due to lack of inventory,
# and tell them the updated available quantity
raise InsufficientInventory()

You also want this function to handle the case where the given product
name doesn't exist. To help with this case, the `update` method
returns
the number of rows updated:

from django.db import IntegrityError
from django.db.models import F

class InsufficientInventor