retain form data when a user session expires while filling a form

2018-04-12 Thread Vijay Shanker


I have to code this scenario:

Some user comes to fill a form and while user is at it, session expires; 
User tries to submit form, as session has expired it will take him to login 
page after which he is rediredted to form page with a prefilled form with 
data he filled previously.

my propsed solution: on form submit, check if user session is expired with 
an ajax call, if yes, drop a cookie with values of filled form, user comes 
back to same form, prefill the form from cookie value.

how far I got: not much; I used ajax call to check session expiry with a 
backend call to this function:

def check_valid_session(request):
session_expiry_date = request.session.get_expiry_date()
now = datetime.now()
seconds_left = (session_expiry_date - now).total_seconds()
if seconds_left <= 0:
return JsonResponse({'session_expired': True, 'seconds_left': 
seconds_left })
else:
return JsonResponse({'session_expired':False, 'seconds_left': 
seconds_left})

in my settings I have:

SESSION_COOKIE_NAME = "sso-sessionid"
SESSION_COOKIE_HTTPONLY = False
SESSION_COOKIE_AGE = 10 
SESSION_COOKIE_DOMAIN = '.mydomain.com'
SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

but in response, I always get seconds_left as something close to 9.999. and 
session_expiry_date keeps increasing itself by 10 seconds each time i hit 
submit and call the backend code above. How to get correct session expire 
time?

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


django, multi-tenancy and urls

2014-12-05 Thread vijay shanker
 am writing a e-commerce application where different people can have stores 
with urls like this: www.store-one.saas.com, www.store-two.saas.com, and so 
on.

These domains have to be generated automatically when a user signs up for 
store.

I have read somewhere that www.saas.com/store-one can be rewritten as 
store-one.saas.com (ofcourse, they din told me how :( ).

Is it possible and how it can be done, how can i achieve it in production 
and with my local machine?

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


LiveFyre vs disqus Commenting system

2014-03-03 Thread vijay shanker
Hi 
I was pondering over using livefyre's comment on my site (to have something 
similar to disqus). I am inquisitive about how it fared for people who had 
already used it, i.e can i get total comments count, can i collect user 
information of people who use it to comment upon, what are the pros and 
cons of using it,as compared to disqus and other similar APIs.Hope to hear 
from people who had taste of both these pies.
Regards
Vijay

-- 
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/2bb17aeb-8ed2-4758-bba3-0ee7230a75bb%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Inserting image alongwith text in django's TextField

2013-12-23 Thread Vijay Shanker
Thanks Mrinmoy. using redactor instead.


On Mon, Dec 23, 2013 at 3:17 PM, Mrinmoy Das <mrinmoy.da...@gmail.com>wrote:

> Hi Vijay,
>
> Use something which allows you to do that.
>
> There are a bunch of tools available
>
> https://www.djangopackages.com/grids/g/wysiwyg/
>
>
> Mrinmoy Das
> http://goromlagche.in/
>
>
> On Mon, Dec 23, 2013 at 3:11 PM, vijay shanker <deont...@gmail.com> wrote:
>
>> Hi
>> I am trying to insert images in between of text (basically an article
>> with images interspersed in between) with django's TextField so that i can
>> add and position the image in the TextField box in admin.I tried tinymce's
>> tinymce_models.HTMLField() for body field of my Article model but it did
>> not have any option to insert image in between of article object.How can i
>> accomplish it ?
>> Regards
>> Vijay
>>
>> --
>> 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/86aee995-aaa1-4f03-8980-99c09e2e61c9%40googlegroups.com
>> .
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>
>  --
> 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/dnLNrwxz9v8/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/CAFWA-MPkGBiDUeCNK-wXde03cNaZu5X5XD9zvk12coDOCHO27A%40mail.gmail.com
> .
>
> For more options, visit https://groups.google.com/groups/opt_out.
>

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


Inserting image alongwith text in django's TextField

2013-12-23 Thread vijay shanker
Hi
I am trying to insert images in between of text (basically an article with 
images interspersed in between) with django's TextField so that i can add 
and position the image in the TextField box in admin.I tried tinymce's 
tinymce_models.HTMLField() for body field of my Article model but it did 
not have any option to insert image in between of article object.How can i 
accomplish it ?
Regards
Vijay

-- 
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/86aee995-aaa1-4f03-8980-99c09e2e61c9%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


FormView and django-formset Issue

2013-09-13 Thread vijay shanker
Hi i used formsets in generic FormView like this:

class RequestRecommendationView(FormView):
template_name = "account/stepfour.html"
form_class = formset_factory(StepFourForm)

def form_valid(self,form):
print form.is_valid()
cleaned_data = form.cleaned_data
# return redirect(reverse("some_url_name"))
form for formset_factory is like this:

class StepFourForm(forms.Form):
contact_person = forms.CharField(required=True)
email = forms.EmailField(required=True)
company = forms.CharField(required=True)
request_message = forms.CharField(required=True)
my html structure is like this:


 Request a Recommendation 

{% csrf_token %}



{% for f in form %}
{% for field in f %}

{{field.label_tag}}
{{field}}

{% for error in field.errors %}
{{ error }}
{% endfor %}

{% endfor %}
{% endfor %}



Request Now
{{ form.management_form }}


Then i used django-dynamic-formset 
(https://code.google.com/p/django-dynamic-formset/) to add/remove extra 
forms through these:


$(function() {
   $('#myForm tbody').formset();
   })

the problem is: if i leave the form empty,(every field is required), it 
manages to get to form_valid() of my class-view (though it should not), if 
i fill one of the fields (leaving others unfilled), it displays the errors 
associated message successfully. why is this happening ? what should i do 
to fix it ? is providing form_class a formset is behind all of this ?

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


Django-Ajax Issue

2013-07-14 Thread vijay shanker
Hey all
I am trying to make a simple ajax call to show items retrieved from 
database.
I am displaying bunch of fields like a text input for keyword and radio 
button for filter in a form like this:

{% csrf_token %}

 Search 



All
Paying
Uploaded
Staff Pick
 


This form is displayed by a function which inherits generic View class, 
from its get method.

class Home(View):
def get(self,request, *args, **kwargs):
return render_to_response('items/search_page.html', 
context_instance = RequestContext(request) )
def post(self, request, *args, **kwargs):
print 'in home post'

What puzzles me is that when i am trying to submit the form data via ajax 
call (on same page) with jquery when someone clicks on search button, it 
takes me to post view of Home and not on to other function i have defined.
The javascript on the html page is:

   function search(e) {
e.preventDefault();
search_for = $("#search").val()
rval = $('input:radio[name=fancy_radio]:checked').val()
$.ajax({
url:"/search/",
method : "POST",
data : { 'keyword': search_for, 'filter': rval },
success:function(result){
alert(result)
}
});
   }


why is this happening ? 

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




Re: Issue in User authentication

2013-07-06 Thread vijay shanker


On Thursday, July 4, 2013 11:30:06 PM UTC+5:30, vijay shanker wrote:
>
> *Hi*
> *I am using django 1.5 and created my own user model by AUTH_USER_MODEL= 
> 'account.User' in settings.*
>
> *my user model is like this:*
>
> from django.db import models
> from django.contrib.auth.models import AbstractBaseUser, UserManager, 
> PermissionsMixin
> # Create your models here.
> GENDER = (
> ('M', 'Male'),
> ('F', 'Female')
> )
>
> class User(AbstractBaseUser, PermissionsMixin):
> username = models.CharField(max_length=100, unique=True)
> first_name = models.CharField(max_length=100)
> last_name = models.CharField(max_length=100)
> email = models.EmailField(unique=True)
> gender = models.CharField(max_length=10, choices=GENDER)
> is_admin = models.BooleanField(default=False)
> is_staff = models.BooleanField(default=False)
> is_active = models.BooleanField(default=False)
> date_joined = models.DateTimeField(auto_now_add=True)
> 
> objects = UserManager()
> 
> USERNAME_FIELD = 'email'
> REQUIRED_FIELDS = ['username']
> 
> def __unicode__(self):
> return self.get_full_name()
> 
> 
> def get_full_name(self):
> return ' '.join([self.first_name, self.last_name]) or self.username
> 
> def get_short_name(self):
> return self.first_name or self.username.
>
> The form which i present to user for signup is:
>
> class SignupForm(forms.ModelForm):
> class Meta:
> model = User
> fields = ['username', 'first_name', 'last_name', 'email', 
> 'gender', 'password']
> exclude = ['last_login', 
> 'is_superuser','groups','user_permissions', 'is_admin', 'is_staff', 
> 'is_active']
> widgets = {
> 'password': forms.PasswordInput(),
> }
> 
> def save(self):
> user = super(SignupForm, self).save(commit=False)
> user.set_password(self.cleaned_data['password'])
> user.save(commit=True)
> return user
>
>
> *my login view function is like this:*
>
> class LoginView(View):
> def get(self, request, *args, **kwargs):
> form = LoginForm()
> return render_to_response('login.html', 
> {'form':form},context_instance = RequestContext(request) )
> 
> def post(self,request,*args, **kwargs ):
> username = self.request.POST['username']
> password = self.request.POST['password']
> user = authenticate(username=username, password=password)
> 
> if user is not None:
> if user.is_active:
> print "You provided a correct username and password!"
> login(request, user)
> return redirect(reverse('bands-list'))
> else:
> login(request, user)
> print "Your account has been disabled!"
> return redirect(reverse('bands-list'))
> else:
> form = LoginForm()
> return render_to_response('login.html', 
> {'form':form},context_instance = RequestContext(request) )
>
> *and somewhere in my template:*
>
> {% if request.user.is_authenticated %}
> hello {{ user.first_name }}  >Logout
> {% else %}
> Login
> Signup
> {% endif %}
>
> *the problem i am facing are:*
> *
> *
> *1. when the user signs up, password stored are not encrypted, ( though i 
> am overriding save() to do so above)*
>
 * there is no commit for user.save(); your whole code isn't even executed 
since save has to be a method on the form not of meta*

> *2. though i provide correct password, request.user.is_authenticated does 
> not works for me.*
> *its only user.is_authenticated in template and not 
> request.user.is_authenticated
> *
> kind suggestions are welcome.
> Regards
> Vijay Shanker
>
>
>
>

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




Issue in User authentication

2013-07-04 Thread vijay shanker
*Hi*
*I am using django 1.5 and created my own user model by AUTH_USER_MODEL= 
'account.User' in settings.*

*my user model is like this:*

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, UserManager, 
PermissionsMixin
# Create your models here.
GENDER = (
('M', 'Male'),
('F', 'Female')
)

class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=100, unique=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
gender = models.CharField(max_length=10, choices=GENDER)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

def __unicode__(self):
return self.get_full_name()


def get_full_name(self):
return ' '.join([self.first_name, self.last_name]) or self.username

def get_short_name(self):
return self.first_name or self.username.

The form which i present to user for signup is:

class SignupForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'gender', 
'password']
exclude = ['last_login', 
'is_superuser','groups','user_permissions', 'is_admin', 'is_staff', 
'is_active']
widgets = {
'password': forms.PasswordInput(),
}

def save(self):
user = super(SignupForm, self).save(commit=False)
user.set_password(self.cleaned_data['password'])
user.save(commit=True)
return user


*my login view function is like this:*

class LoginView(View):
def get(self, request, *args, **kwargs):
form = LoginForm()
return render_to_response('login.html', 
{'form':form},context_instance = RequestContext(request) )

def post(self,request,*args, **kwargs ):
username = self.request.POST['username']
password = self.request.POST['password']
user = authenticate(username=username, password=password)

if user is not None:
if user.is_active:
print "You provided a correct username and password!"
login(request, user)
return redirect(reverse('bands-list'))
else:
login(request, user)
print "Your account has been disabled!"
return redirect(reverse('bands-list'))
else:
form = LoginForm()
return render_to_response('login.html', 
{'form':form},context_instance = RequestContext(request) )

*and somewhere in my template:*

{% if request.user.is_authenticated %}
hello {{ user.first_name }} Logout
{% else %}
Login
Signup
{% endif %}

*the problem i am facing are:*
*
*
*1. when the user signs up, password stored are not encrypted, ( though i 
am overriding save() to do so above)*
*2. though i provide correct password, request.user.is_authenticated does 
not works for me.*
*
*
kind suggestions are welcome.
Regards
Vijay Shanker



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




Re: forloop breaking

2013-06-26 Thread vijay shanker
You are looking for "break"
 
On Wednesday, June 26, 2013 8:39:58 PM UTC+5:30, Harjot Mann wrote:
>
> What are the methods to break forloop?
>

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




Re: error and django forms

2013-04-21 Thread Vijay Shanker
yess that does it.
thanks


On Sun, Apr 21, 2013 at 11:57 PM, vijay shanker <deont...@gmail.com> wrote:

>
>
> On Sunday, April 21, 2013 10:58:47 PM UTC+5:30, vijay shanker wrote:
>>
>> hi
>>
>> i have a django form like this:
>>
>> class AddArtistForm(forms.Form):
>> fname = forms.CharField()
>> lname = forms.CharField()
>> profession = forms.CharField()
>> dob  = forms.DateField()
>>
>> i want to display errors as this
>>   {% for field in form %}
>> {{field}}
>> #  error associated with above field
>> {% endfor %}
>>
>> i want to know how can i get error message with associated field if i
>> want to loop over forms field.
>> thanks
>>
>
>
>> introspecting fields it doesn have errors attribute, so this cnat be it
>>
>> >>>
>> dir(addform.fields['fname'])
>>
>
>
>> ['__class__', '__deepcopy__', '__delattr__', '__dict__', '__doc__',
>> '__format__', '__getattribute__', '__hash__', '__init__', '__module__',
>> '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
>> '__sizeof__', '__slotnames__', '__str__', '__subclasshook__',
>> '__weakref__', 'bound_data', 'clean', 'creation_counter',
>> 'default_error_messages', 'default_validators', 'error_messages',
>> 'help_text', 'hidden_widget', 'initial', 'label', 'localize', 'max_length',
>> 'min_length', 'prepare_value', 'required', 'run_validators',
>> 'show_hidden_initial', 'to_python', 'validate', 'validators', 'widget',
>> 'widget_attrs'
>>  fields
>> error if its not valid
>>
>  --
> 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/RvJXXj-Yb2A/unsubscribe?hl=en
> .
> 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?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

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




Re: error and django forms

2013-04-21 Thread vijay shanker


On Sunday, April 21, 2013 10:58:47 PM UTC+5:30, vijay shanker wrote:
>
> hi
>
> i have a django form like this:
>
> class AddArtistForm(forms.Form):
> fname = forms.CharField()
> lname = forms.CharField()
> profession = forms.CharField()
> dob  = forms.DateField()
>
> i want to display errors as this
>   {% for field in form %}
> {{field}}
> #  error associated with above field
> {% endfor %}
>
> i want to know how can i get error message with associated field if i want 
> to loop over forms field. 
> thanks
>
 

> introspecting fields it doesn have errors attribute, so this cnat be it   
> 
> >>> 
> dir(addform.fields['fname'])
>
 

> ['__class__', '__deepcopy__', '__delattr__', '__dict__', '__doc__', 
> '__format__', '__getattribute__', '__hash__', '__init__', '__module__', 
> '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
> '__sizeof__', '__slotnames__', '__str__', '__subclasshook__', 
> '__weakref__', 'bound_data', 'clean', 'creation_counter', 
> 'default_error_messages', 'default_validators', 'error_messages', 
> 'help_text', 'hidden_widget', 'initial', 'label', 'localize', 'max_length', 
> 'min_length', 'prepare_value', 'required', 'run_validators', 
> 'show_hidden_initial', 'to_python', 'validate', 'validators', 'widget', 
> 'widget_attrs' 
>  fields 
> error if its not valid
>

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




error and django forms

2013-04-21 Thread vijay shanker
hi

i have a django form like this:

class AddArtistForm(forms.Form):
fname = forms.CharField()
lname = forms.CharField()
profession = forms.CharField()
dob  = forms.DateField()

i want to display errors as this
  {% for field in form %}
{{field}}
#  error associated with above field
{% endfor %}

i want to know how can i get error message with associated field if i want 
to loop over forms field. 
thanks
   




 fields error if its not valid

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




Django Shopping Cart

2013-02-27 Thread vijay shanker
hey, i want to write a shopping cart app, please provide some inputs, 
useful information, suggestions etc for doing it right .
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: A small bug for dynamic choices

2013-02-14 Thread vijay shanker

 code is getting executed when Django validates it's models. Hence, 
Cartprobably has not been validated yet and it's model class is 
None.

On Monday, February 11, 2013 4:29:44 PM UTC+5:30, vijay shanker wrote:
>
> hi 
> i wrote a function for producing tuples of all model names, which is this:
> from django.contrib.contenttypes.models import ContentType
> from django.db.models.loading import get_model
>
> def get_all_models():
> return tuple([(each.__module__+'.'+each.__name__,each.__name__) for 
> each in [each.model_class() for each in 
> ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
>  
> if each is not None] if each is not None])
> 
> when i run this in my shell it gives this output:
>
> (('shoppingcart.models.Cart', 'Cart'), ('shoppingcart.models.CartItem', 
> 'CartItem'), ('shoppingcart.models.CartRule', 'CartRule'), 
> ('products.models.CasesAccessory', 'CasesAccessory'), 
> ('productoptions.models.Coating', 'Coating'), 
> ('shoppingcart.models.ConditionSet', 'ConditionSet'), 
> ('products.models.Eyeglass', 'Eyeglass'), ('products.models.GiftVoucher', 
> 'GiftVoucher'), ('productoptions.models.Lens', 'Lens'), 
> ('productoptions.models.Prescription', 'Prescription'), 
> ('products.models.Readingglass', 'Readingglass'), 
> ('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
> 'Tint'), ('productoptions.models.Vision', 'Vision'))
>
> while at choices my first option got lost and output is:
>
> (('shoppingcart.models.CartItem', 'CartItem'), 
> ('products.models.CasesAccessory', 'CasesAccessory'), 
> ('productoptions.models.Coating', 'Coating'), ('products.models.Eyeglass', 
> 'Eyeglass'), ('products.models.GiftVoucher', 'GiftVoucher'), 
> ('productoptions.models.Lens', 'Lens'), 
> ('productoptions.models.Prescription', 'Prescription'), 
> ('products.models.Readingglass', 'Readingglass'), 
> ('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
> 'Tint'), ('productoptions.models.Vision', 'Vision'))
>
> why did this happened and whats the fix ?
>

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




Re: chained selectboxes with simpleJson call

2013-02-12 Thread vijay shanker
well override ModelForm's __init__ and if theres a kwargs , then populate 
choices depending upon the value of model_name , as well override def 
clean() to handle model attribute.

class ConditionSetAdminForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(ConditionSetAdminForm, self).__init__(*args,**kwargs)
try:
model_name = kwargs['instance'].model_name
app_label,model_class = 
model_name.split('.')[0],model_name.split('.')[1] 
model_class = get_model(app_label=app_label, 
model_name=model_class)
self.fields['model_attribute']  = 
forms.ChoiceField(required=True, label='Model Attribute', choices= 
[(each.name,each.name) for each in model_class._meta.fields])
except:
self.fields['model_attribute']  = 
forms.ChoiceField(required=True, label='Model Attribute', 
choices=get_attributes())
self.fields['model_name']   = forms.ChoiceField(required=True, 
label='Model Name', choices=get_all_models())
class Meta: 
model = ConditionSet
def clean(self):
super(ConditionSetAdminForm,self).clean()
if 'model_attribute' in self._errors:
self.cleaned_data['model_attribute'] = 
self.data['model_attribute']
del self._errors['model_attribute']
return self.cleaned_data

just like that ;)

On Tuesday, February 12, 2013 5:09:51 PM UTC+5:30, vijay shanker wrote:
>
> hey all
>
> I have a model which is as such:
> *in models.py*
>
> class ConditionSet(models.Model):
> model_name  =models.CharField(max_length=
> 50) 
> model_attribute  =models.CharField(max_length=50)
> operator =models.CharField(max_length=50, 
> choices=OPERATORS)
> val=
> models.CharField(max_length=50,null=True,blank=True)
> evaluation  =models.NullBooleanField(null=True, blank=True)
> def __str__(self):
> return self.model_attribute
>
> *in admin.py :*
>
> def get_all_models():
> return [('.'.join([each._meta.app_label,each.__name__]),each.__name__) 
> for each in [each.model_class() for each in 
> ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
>  
> if each is not None] if each is not None]
>
> def get_attributes():
> model_class = 
> ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])[0].model_class()
> return [ (each.name,each.name) for each in model_class._meta.fields ]
>
> class ConditionSetAdminForm(forms.ModelForm):
> def __init__(self,*args,**kwargs):
> super(ConditionSetAdminForm, self).__init__(*args,**kwargs)
> self.fields['model_name']   = forms.ChoiceField(required=True, 
> label='Model Name', choices=get_all_models())
> self.fields['model_attribute']  = forms.ChoiceField(required=True, 
> label='Model Attribute', choices=get_attributes())
> class Meta: 
> model = ConditionSet
>
> class ConditionSetAdmin(admin.ModelAdmin):
> form = ConditionSetAdminForm
>
> admin.site.register(ConditionSet, ConditionSetAdmin )
>
> model_attribute has an initial set of choices, populated by 
> get_attributes().
> When a user selects model_name in admin, i make a json call to get options 
> and populate model_attribute options , but when i try to save it, i get  
> "select a valid choice. xyz_attribute_name is not one of the available 
> choices."
> I understand the problem is the choices for this field are still the one 
> assigned to it in beginning, how should I fix it ?
>
>

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




chained selectboxes with simpleJson call

2013-02-12 Thread vijay shanker
hey all

I have a model which is as such:
*in models.py*

class ConditionSet(models.Model):
model_name  =models.CharField(max_length=
50) 
model_attribute  =models.CharField(max_length=50)
operator =models.CharField(max_length=50, 
choices=OPERATORS)
val=
models.CharField(max_length=50,null=True,blank=True)
evaluation  =models.NullBooleanField(null=True, blank=True)
def __str__(self):
return self.model_attribute

*in admin.py :*

def get_all_models():
return [('.'.join([each._meta.app_label,each.__name__]),each.__name__) 
for each in [each.model_class() for each in 
ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
 
if each is not None] if each is not None]

def get_attributes():
model_class = 
ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])[0].model_class()
return [ (each.name,each.name) for each in model_class._meta.fields ]

class ConditionSetAdminForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(ConditionSetAdminForm, self).__init__(*args,**kwargs)
self.fields['model_name']   = forms.ChoiceField(required=True, 
label='Model Name', choices=get_all_models())
self.fields['model_attribute']  = forms.ChoiceField(required=True, 
label='Model Attribute', choices=get_attributes())
class Meta: 
model = ConditionSet

class ConditionSetAdmin(admin.ModelAdmin):
form = ConditionSetAdminForm

admin.site.register(ConditionSet, ConditionSetAdmin )

model_attribute has an initial set of choices, populated by 
get_attributes().
When a user selects model_name in admin, i make a json call to get options 
and populate model_attribute options , but when i try to save it, i get  
"select a valid choice. xyz_attribute_name is not one of the available 
choices."
I understand the problem is the choices for this field are still the one 
assigned to it in beginning, how should I fix it ?

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




Chained Select Boxes using SimpleJson Call

2013-02-12 Thread vijay shanker
hey all

I have a model which is as such:

*in models.py*

class ConditionSet(models.Model):
model_name  =models.CharField(max_length=50) 
model_attribute  =models.CharField(max_length=50)
operator =models.CharField(max_length=50, 
choices=OPERATORS)
val=
models.CharField(max_length=50,null=True,blank=True)
evaluation  =models.NullBooleanField(null=True, blank=True)
def __str__(self):
return self.model_attribute

*in admin.py :*
def get_all_models():
return [('.'.join([each._meta.app_label,each.__name__]),each.__name__) 
for each in [each.model_class() for each in 
ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
 
if each is not None] if each is not None]

def get_attributes():
model_class = 
ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])[0].model_class()
return [ (each.name,each.name) for each in model_class._meta.fields ]

class ConditionSetAdminForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(ConditionSetAdminForm, self).__init__(*args,**kwargs)
self.fields['model_name']   = forms.ChoiceField(required=True, 
label='Model Name', choices=get_all_models())
self.fields['model_attribute']  = forms.ChoiceField(required=True, 
label='Model Attribute', choices=get_attributes())
class Meta: 
model = ConditionSet

class ConditionSetAdmin(admin.ModelAdmin):
form = ConditionSetAdminForm

admin.site.register(ConditionSet, ConditionSetAdmin )

When model_attribute has an initial set of choices, populated by 
get_attributes().
When a user selects model_name in admin, i make a json call to get options 
and populate them, but i get  "select a valid choice. xyz_attribute_name is 
not one of the available choices."
I understand the problem is the choices for this field are still the one 
assigned to it in beginning, how should I fix it ?








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




Re: Modelform and Ajax (Select a valid choice..... Error)

2013-02-12 Thread vijay shanker
hey siddhartha i have similar problem, i created dynamic option with ajax 
calls and getting the same error
"select a valid choice. xyz is not available choices , how did you solved 
it?"

On Tuesday, December 11, 2012 5:09:48 PM UTC+5:30, siddharth56660 wrote:
>
> Hi, 
>
> I am facing problem in handling modelform and ajax together. 
> The situation is:- 
> I am using modelform to get display the form as ul in the template. 
> I have 3 ChoiceFields (country, state,city). On select of a country 
> from the dropdown, the valid states dropdown gets populated and on 
> select of a state the respective city dropdown gets populated. 
> For achieving the above functionality I am calling an ajax function 
> which returns me the available data of the other dropdown in Json Form 
> {stat_id, stat_name} 
> I am able to populate the data in next dropdown i.e state and city, 
> but when i click submit form it shows "Select a valid choice. 8 is not 
> one of the available choices" 
> 8 happens to be the stat_id in this case. 
> I have gone through google but dint find anything useful. Help is 
> really appreciated. 
>

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




Re: Any good books for learning django?

2013-02-11 Thread vijay shanker
thanks, i bought it :)

On Monday, February 11, 2013 7:37:28 PM UTC+5:30, frocco wrote:
>
> That's good to know, hopefully the person asked for a free copy will head 
> over to there.
>
> On Monday, February 11, 2013 8:52:52 AM UTC-5, W. wrote:
>>
>> Do not pirate. 
>> However. If you checked their webpage https://django.2scoops.org/ , you 
>> would see. 
>>
>> Can't Afford the Book? 
>>>
>>> If you're struggling with finances and can't afford it, let us know and 
>>> we'd be happy to send you a free copy. Drop us a note at <their@email> and 
>>> we'll get it to you within 72 hours.
>>>
>> Best regards, 
>>
>> W. 
>>
>> Dne pátek, 8. února 2013 11:13:11 UTC+1 vijay shanker napsal(a):
>>>
>>> do u have the pdf ?
>>> will u share it at some place (or please mail it to me deon...@gmail.com
>>> )
>>>
>>> On Thursday, February 7, 2013 11:40:01 PM UTC+5:30, Mayukh Mukherjee 
>>> wrote:
>>>>
>>>> I'd recommend two scoops of django.
>>>> It's a little more intermediate level but it's a gem.
>>>>
>>>> Sent from my iPhone
>>>>
>>>> On Feb 7, 2013, at 12:49, frocco <far...@gmail.com> wrote:
>>>>
>>>> Hello,
>>>> Most of what I find are dated, 2008,2009.
>>>> Are these still good for learning django 1.4?
>>>>
>>>> Which books do you recommend?
>>>>
>>>> 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...@googlegroups.com.
>>>> To post to this group, send email to django...@googlegroups.com.
>>>> Visit this group at <http://groups.google.com/group/django-users?hl=en>
>>>> http://groups.google.com/group/django-users?hl=en.
>>>> For more options, visit <https://groups.google.com/groups/opt_out>
>>>> https://groups.google.com/groups/opt_out.
>>>>  
>>>>  
>>>>
>>>>

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




Re: Any good books for learning django?

2013-02-11 Thread vijay shanker
yes u right .. my bad

On Friday, February 8, 2013 6:28:20 PM UTC+5:30, Tom Evans wrote:
>
> On Fri, Feb 8, 2013 at 10:13 AM, vijay shanker 
> <deon...@gmail.com> 
> wrote: 
> > do u have the pdf ? 
> > will u share it at some place (or please mail it to me 
> > deon...@gmail.com) 
>
>
> Please don't use this list to arrange or ask others to pirate books. 
> The author of any django book almost certainly is a subscriber, you 
> are stealing his/her work from under their nose. 
>
> Please don't pirate technical books anyway. If everyone pirated 
> technical books, there would be no incentive to write new technical 
> books, and everyone loses out. 
>
> 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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




ContentType's model_class is NoneType

2013-02-11 Thread vijay shanker
Hi
I have few models in a app called shoppingcart.
I can find contenttypes associated with this model with this: 
>>>ct = ContentType.objects.filter(app_label='shoppingcart') 
>>>ct
[, , , 
]

but when i try ct[0].model_class() it returns the model class on shell but 
gives me a NoneType when i try to get all models as a tuple so that i can 
populate them as choices of field with this iterator MODELCHOICES  = [each 
for each in GetAllModels]
I have the required tables in database. (had once deleted all contenttypes 
for this app and synced db to recreate the table)
 
class GetAllModels(object):
def __init__(self,counter=0):
self.counter = counter
def __iter__(self):
return self
def next(self):
ct = 
list(ContentType.objects.filter(app_label__in=['shoppingcart','products','productoptions']))
if self.counter < len(ct):
mclass = ct[self.counter].model_class()
self.counter = self.counter +1
return ('.'.join([mclass.__module__,mclass.__name__]), 
mclass.__name__)
else:
raise StopIteration

Please enlighten me !

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




Re: A small bug for dynamic choices

2013-02-11 Thread vijay shanker
I found out that ('shoppingcart.models.Cart', 'Cart') is lost coz it 
doesnot finds any model_class (i.e model_class is None and is thus filtered 
out ) when i am running the code but it does finds the model_class from 
python shell.
something which is not very obvious is happening.  

On Monday, February 11, 2013 4:29:44 PM UTC+5:30, vijay shanker wrote:
>
> hi 
> i wrote a function for producing tuples of all model names, which is this:
> from django.contrib.contenttypes.models import ContentType
> from django.db.models.loading import get_model
>
> def get_all_models():
> return tuple([(each.__module__+'.'+each.__name__,each.__name__) for 
> each in [each.model_class() for each in 
> ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
>  
> if each is not None] if each is not None])
> 
> when i run this in my shell it gives this output:
>
> (('shoppingcart.models.Cart', 'Cart'), ('shoppingcart.models.CartItem', 
> 'CartItem'), ('shoppingcart.models.CartRule', 'CartRule'), 
> ('products.models.CasesAccessory', 'CasesAccessory'), 
> ('productoptions.models.Coating', 'Coating'), 
> ('shoppingcart.models.ConditionSet', 'ConditionSet'), 
> ('products.models.Eyeglass', 'Eyeglass'), ('products.models.GiftVoucher', 
> 'GiftVoucher'), ('productoptions.models.Lens', 'Lens'), 
> ('productoptions.models.Prescription', 'Prescription'), 
> ('products.models.Readingglass', 'Readingglass'), 
> ('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
> 'Tint'), ('productoptions.models.Vision', 'Vision'))
>
> while at choices my first option got lost and output is:
>
> (('shoppingcart.models.CartItem', 'CartItem'), 
> ('products.models.CasesAccessory', 'CasesAccessory'), 
> ('productoptions.models.Coating', 'Coating'), ('products.models.Eyeglass', 
> 'Eyeglass'), ('products.models.GiftVoucher', 'GiftVoucher'), 
> ('productoptions.models.Lens', 'Lens'), 
> ('productoptions.models.Prescription', 'Prescription'), 
> ('products.models.Readingglass', 'Readingglass'), 
> ('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
> 'Tint'), ('productoptions.models.Vision', 'Vision'))
>
> why did this happened and whats the fix ?
>

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




A small bug for dynamic choices

2013-02-11 Thread vijay shanker
hi 
i wrote a function for producing tuples of all model names, which is this:
from django.contrib.contenttypes.models import ContentType
from django.db.models.loading import get_model

def get_all_models():
return tuple([(each.__module__+'.'+each.__name__,each.__name__) for 
each in [each.model_class() for each in 
ContentType.objects.filter(app_label__in=['products','productoptions','shoppingcart'])
 
if each is not None] if each is not None])

when i run this in my shell it gives this output:

(('shoppingcart.models.Cart', 'Cart'), ('shoppingcart.models.CartItem', 
'CartItem'), ('shoppingcart.models.CartRule', 'CartRule'), 
('products.models.CasesAccessory', 'CasesAccessory'), 
('productoptions.models.Coating', 'Coating'), 
('shoppingcart.models.ConditionSet', 'ConditionSet'), 
('products.models.Eyeglass', 'Eyeglass'), ('products.models.GiftVoucher', 
'GiftVoucher'), ('productoptions.models.Lens', 'Lens'), 
('productoptions.models.Prescription', 'Prescription'), 
('products.models.Readingglass', 'Readingglass'), 
('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
'Tint'), ('productoptions.models.Vision', 'Vision'))

while at choices my first option got lost and output is:

(('shoppingcart.models.CartItem', 'CartItem'), 
('products.models.CasesAccessory', 'CasesAccessory'), 
('productoptions.models.Coating', 'Coating'), ('products.models.Eyeglass', 
'Eyeglass'), ('products.models.GiftVoucher', 'GiftVoucher'), 
('productoptions.models.Lens', 'Lens'), 
('productoptions.models.Prescription', 'Prescription'), 
('products.models.Readingglass', 'Readingglass'), 
('products.models.Sunglass', 'Sunglass'), ('productoptions.models.Tint', 
'Tint'), ('productoptions.models.Vision', 'Vision'))

why did this happened and whats the fix ?

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




change select choices in django admin on select of another field

2013-02-11 Thread vijay shanker
Hi
I have a model called Place, which is like this:

class Place(models.Model):
 state = models.CharField(max_lengh=50, choices=STATE_CHOICES)
 city   = models.Charfield(max_length=50)

I want to populate select choices for repective city for state in admin, 
when the user selects the state. How should i do it ? 
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: delete obsolete content type entries...

2013-02-10 Thread vijay shanker
we can delete all obsolete ContentType entries manually.
>>>for each in ContentType.objects.filter(app_label=appname): each.delete()
 thanks

On Friday, May 4, 2007 8:42:51 PM UTC+5:30, Jens Diemer wrote:
>
>
> I have delete some app models. So, in the internal django tables 
> "django_content_type" and "auth_permission" are some old content types 
> entries.
>
> So i received errors like: "ContentType matching query does not exist." 
> (When i create a new user group).
>
> Is there a way to update the django tables automatically?
>
> -- 
> Mfg.
>
> Jens Diemer
>
>
> 
> A django powered CMS: http://www.pylucid.org
>
>

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




Re: post_save signal getting called twice !

2013-02-08 Thread vijay shanker
yes that was it. thanks a ton. ;)

On Friday, February 8, 2013 5:21:19 PM UTC+5:30, Martin J. Laubach wrote:
>
> further, i tried putting a sender argument in receiver, but the sender , i 
>> found (by set_trace) is Cart_cartitems, how can i import this > 'shoppingcart.models.Cart_cartitems'> when its only a intermediary model 
>> that django's creating.
>
>
>   I think you want Cart.cartitems.through
>
>   mjl
>
>

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




Re: Is there any way to apply a constraint on ForeignKey/OneToOneField being attached to any model based on some condition ?

2013-02-08 Thread vijay shanker
fortunately my case was really simple, i had to count number of m2m objects 
attached to my model and storing it as field, and  had to make the decision 
of having a ForeignKey/OneToOne relation based on number of m2m objects 
attached.I was already using m2m_changed signal ( on post_add ), so i 
handled the case there itself
thanks tran.
:)

On Thursday, February 7, 2013 2:33:46 PM UTC+5:30, Huu Da Tran wrote:
>
> You could overwrite the save() method... or if you are populating from a 
> form, overwrite the clean() method.
>
> On Thursday, February 7, 2013 3:23:54 AM UTC-5, vijay shanker wrote:
>>
>> Hi
>> I have these two models Cart and CartItem,
>>
>> class Cart(models.Model):
>> cart_id = models.CharField(max_length=
>> 50, null=False)
>> customer= models.ForeignKey(Customer,null=True,blank=True)
>> cartitems   = models.ManyToManyField(CartItem,null=True)
>> applied_rule= 
>> models.OneToOneField(CartRule,null=True,blank=True)
>> 
>>
>> class CartItem(models.Model):
>> content_type= models.ForeignKey(ContentType)
>> object_id   = models.PositiveIntegerField()
>> content_object  = 
>> generic.GenericForeignKey('content_type','object_id')
>> quantity= models.PositiveIntegerField(default=0)
>> is_abandoned= models.BooleanField(default=False)
>> def __str__(self):
>> return self.cart_id
>>
>> the rules to be applied only when there are more than two items in 
>> shoppingcart, i.e i am looking for a way to attach a rule to cart only if 
>> there are more than two items in cart (cartitems m2m field should have more 
>> than two objects in it).
>> How should i go about it ?
>>
>

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




Re: Set db connections manually for each request.

2013-02-08 Thread vijay shanker
write a custom manager and use it whenever you want to do use other 
database:

https://docs.djangoproject.com/en/1.3/topics/db/multi-db/#using-get-query-set-with-multiple-databases


On Thursday, February 7, 2013 7:08:40 PM UTC+5:30, girishms wrote:
>
> Hi All,
> Is it possible to set db connection manually for each request?
>
> Here is the senerio:
> There are two dbs (lets say:db-1 and db-2) in my application.
> I need to use db-1 for some views and db-2 for others.
> I know that django creates separate connection for each request, is it 
> possible to specify
> which db to be used during connection.?
>
>
> There is a way to do this for each query by using - "using":
>ex: modelname.objects.using('db-name')
> But as there are lot of queries in views, its very hard to do for each 
> query.
>
>
> -- 
> Girish M S 
>

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




Re: Any good books for learning django?

2013-02-08 Thread vijay shanker
do u have the pdf ?
will u share it at some place (or please mail it to me deont...@gmail.com)

On Thursday, February 7, 2013 11:40:01 PM UTC+5:30, Mayukh Mukherjee wrote:
>
> I'd recommend two scoops of django.
> It's a little more intermediate level but it's a gem.
>
> Sent from my iPhone
>
> On Feb 7, 2013, at 12:49, frocco  wrote:
>
> Hello,
> Most of what I find are dated, 2008,2009.
> Are these still good for learning django 1.4?
>
> Which books do you recommend?
>
> 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...@googlegroups.com .
> To post to this group, send email to django...@googlegroups.com
> .
> Visit this group at 
> http://groups.google.com/group/django-users?hl=en.
> For more options, visit 
> https://groups.google.com/groups/opt_out.
>  
>  
>
>

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




Re: post_save signal getting called twice !

2013-02-08 Thread vijay shanker

further, i tried putting a sender argument in receiver, but the sender , i 
found (by set_trace) is Cart_cartitems, how can i import this  when its only a intermediary model 
that django's creating.
On Friday, February 8, 2013 11:26:47 AM UTC+5:30, vijay shanker wrote:
>
> Thanks Evans.That was helpful. :)
>
> On Thursday, February 7, 2013 7:54:36 PM UTC+5:30, Tom Evans wrote:
>>
>> On Thu, Feb 7, 2013 at 1:54 PM, vijay shanker <deon...@gmail.com> wrote: 
>> > Hi 
>> > I am using django version 1.4.3 
>> > I am using two signals in my models.py 
>> > one is m2m_changed, so i can have a counter field (numcounter) of 
>> number of 
>> > m2m fields attached, and another is post_save so i can decide whether 
>> to 
>> > have a OneToOneField (cartrule, is to be applied only if there are more 
>> than 
>> > 2 fields) or not. 
>> > my models.py is: 
>> > 
>> > class CartItem(models.Model): 
>> > content_type= models.ForeignKey(ContentType) 
>> > object_id   = models.PositiveIntegerField() 
>> > content_object  = generic.GenericForeignKey(' 
>> > content_type','object_id') 
>> > quantity= models.PositiveIntegerField(default=0) 
>> > is_abandoned= models.BooleanField(default=False) 
>> > created_at  = models.DateTimeField(auto_now_add=True) 
>> > update_at   = models.DateTimeField(auto_now=True) 
>> > def __str__(self): 
>> > return self.content_object.name 
>> > 
>> > class CartRule(models.Model): 
>> > ##some field 
>> > pass 
>> > 
>> > class Cart(models.Model): 
>> > cart_id = models.CharField(max_length=50, null=False) 
>> > customer= 
>> models.ForeignKey(Customer,null=True,blank=True) 
>> > cartitems   = models.ManyToManyField(CartItem,null=True) 
>> > created_at  = models.DateTimeField(auto_now_add=True) 
>> > update_at   = models.DateTimeField(auto_now=True) 
>> > cartrule   = 
>> > models.OneToOneField(crapclass,null=True,blank=True) 
>> > num_cartitem= models.IntegerField() 
>> > def __str__(self): 
>> > return self.cart_id 
>> > 
>> > @receiver(post_save, sender=Cart) 
>> > def apply_condition(sender,instance,created,raw,using,*args,**kwargs): 
>> > # i want to decide here if num_cartitem is greater than 2 its ok to 
>> have 
>> > a cartrule 
>> > pass 
>> > 
>> > @receiver(m2m_changed) 
>> > def save_cartitem_counter(sender, instance, signal,*args, **kwargs): 
>> > if kwargs['action'] == 'post_add': 
>> > instance.num_cartitem = instance.cartitems.all().count() 
>> > instance.save() 
>> > 
>> > the issue is apply_condition gets called twice, with similar value of 
>> args, 
>> > first with older value of m2m (cartitem) field in Cart, the other time 
>> with 
>> > the values i intended to save 
>> > I looked into older post but still could not figure out the whys.How 
>> should 
>> > i go about this ? 
>> > 
>>
>> When you save a Cart instance, the post_save signal is triggered. 
>> If the M2M relationship is changed as well, then the m2m_changed 
>> signal is triggered. Your handler for this then re-saves the Cart 
>> instance after denormalising data, which triggers the post save signal 
>> for a second time. 
>> You should probably connect the M2M receiver to a specific sender too, 
>> currently it will fire whenever any M2M on any model is changed. 
>>
>> Keeping denormalized data like that is a pain, could you do without 
>> it, and re-calculate it where necessary? 
>>
>> Alternatively, you could use a named intermediary M2M relationship: 
>>
>>
>> https://docs.djangoproject.com/en/1.4/topics/db/models/#intermediary-manytomany
>>  
>>
>> and connect signals on post_create and post_delete to the intermediary 
>> model, updating the Cart as necessary. 
>>
>> This is a little more logical, since you wish to denormalise the data 
>> whenever an item is added to or removed from a cart, ie whenever a row 
>> is added or deleted to the intermediate table. Naming the relationship 
>> allows you to connect the signals to the right place. 
>>
>> 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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: post_save signal getting called twice !

2013-02-07 Thread vijay shanker
Thanks Evans.That was helpful. :)

On Thursday, February 7, 2013 7:54:36 PM UTC+5:30, Tom Evans wrote:
>
> On Thu, Feb 7, 2013 at 1:54 PM, vijay shanker 
> <deon...@gmail.com> 
> wrote: 
> > Hi 
> > I am using django version 1.4.3 
> > I am using two signals in my models.py 
> > one is m2m_changed, so i can have a counter field (numcounter) of number 
> of 
> > m2m fields attached, and another is post_save so i can decide whether to 
> > have a OneToOneField (cartrule, is to be applied only if there are more 
> than 
> > 2 fields) or not. 
> > my models.py is: 
> > 
> > class CartItem(models.Model): 
> > content_type= models.ForeignKey(ContentType) 
> > object_id   = models.PositiveIntegerField() 
> > content_object  = generic.GenericForeignKey(' 
> > content_type','object_id') 
> > quantity= models.PositiveIntegerField(default=0) 
> > is_abandoned= models.BooleanField(default=False) 
> > created_at  = models.DateTimeField(auto_now_add=True) 
> > update_at   = models.DateTimeField(auto_now=True) 
> > def __str__(self): 
> > return self.content_object.name 
> > 
> > class CartRule(models.Model): 
> > ##some field 
> > pass 
> > 
> > class Cart(models.Model): 
> > cart_id = models.CharField(max_length=50, null=False) 
> > customer= 
> models.ForeignKey(Customer,null=True,blank=True) 
> > cartitems   = models.ManyToManyField(CartItem,null=True) 
> > created_at  = models.DateTimeField(auto_now_add=True) 
> > update_at   = models.DateTimeField(auto_now=True) 
> > cartrule   = 
> > models.OneToOneField(crapclass,null=True,blank=True) 
> > num_cartitem= models.IntegerField() 
> > def __str__(self): 
> > return self.cart_id 
> > 
> > @receiver(post_save, sender=Cart) 
> > def apply_condition(sender,instance,created,raw,using,*args,**kwargs): 
> > # i want to decide here if num_cartitem is greater than 2 its ok to 
> have 
> > a cartrule 
> > pass 
> > 
> > @receiver(m2m_changed) 
> > def save_cartitem_counter(sender, instance, signal,*args, **kwargs): 
> > if kwargs['action'] == 'post_add': 
> > instance.num_cartitem = instance.cartitems.all().count() 
> > instance.save() 
> > 
> > the issue is apply_condition gets called twice, with similar value of 
> args, 
> > first with older value of m2m (cartitem) field in Cart, the other time 
> with 
> > the values i intended to save 
> > I looked into older post but still could not figure out the whys.How 
> should 
> > i go about this ? 
> > 
>
> When you save a Cart instance, the post_save signal is triggered. 
> If the M2M relationship is changed as well, then the m2m_changed 
> signal is triggered. Your handler for this then re-saves the Cart 
> instance after denormalising data, which triggers the post save signal 
> for a second time. 
> You should probably connect the M2M receiver to a specific sender too, 
> currently it will fire whenever any M2M on any model is changed. 
>
> Keeping denormalized data like that is a pain, could you do without 
> it, and re-calculate it where necessary? 
>
> Alternatively, you could use a named intermediary M2M relationship: 
>
>
> https://docs.djangoproject.com/en/1.4/topics/db/models/#intermediary-manytomany
>  
>
> and connect signals on post_create and post_delete to the intermediary 
> model, updating the Cart as necessary. 
>
> This is a little more logical, since you wish to denormalise the data 
> whenever an item is added to or removed from a cart, ie whenever a row 
> is added or deleted to the intermediate table. Naming the relationship 
> allows you to connect the signals to the right place. 
>
> 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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




post_save signal getting called twice !

2013-02-07 Thread vijay shanker
Hi
I am using django version 1.4.3
I am using two signals in my models.py
one is m2m_changed, so i can have a counter field (numcounter) of number of 
m2m fields attached, and another is post_save so i can decide whether to 
have a OneToOneField (cartrule, is to be applied only if there are more 
than 2 fields) or not.
my models.py is:

class CartItem(models.Model):
content_type= models.ForeignKey(ContentType)
object_id   = models.PositiveIntegerField()
content_object  = generic.GenericForeignKey('
content_type','object_id')
quantity= models.PositiveIntegerField(default=0)
is_abandoned= models.BooleanField(default=False)
created_at  = models.DateTimeField(auto_now_add=True)
update_at   = models.DateTimeField(auto_now=True)
def __str__(self):
return self.content_object.name

class CartRule(models.Model):
##some field
pass

class Cart(models.Model):
cart_id = models.CharField(max_length=50, null=False)
customer= models.ForeignKey(Customer,null=True,blank=True)
cartitems   = models.ManyToManyField(CartItem,null=True)
created_at  = models.DateTimeField(auto_now_add=True)
update_at   = models.DateTimeField(auto_now=True)
cartrule   = 
models.OneToOneField(crapclass,null=True,blank=True)
num_cartitem= models.IntegerField()
def __str__(self):
return self.cart_id
 
@receiver(post_save, sender=Cart)
def apply_condition(sender,instance,created,raw,using,*args,**kwargs):
# i want to decide here if num_cartitem is greater than 2 its ok to 
have a cartrule
pass

@receiver(m2m_changed)
def save_cartitem_counter(sender, instance, signal,*args, **kwargs):
if kwargs['action'] == 'post_add':
instance.num_cartitem = instance.cartitems.all().count()
instance.save()

the issue is apply_condition gets called twice, with similar value of args, 
first with older value of m2m (cartitem) field in Cart, the other time with 
the values i intended to save
I looked into older post but still could not figure out the whys.How should 
i go about this ?

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




post_save signal handler gets called twice !

2013-02-07 Thread vijay shanker
Hi
I am using django version 1.4.3
I am using two signals in my models.py
one is m2m_changed, so i can have a counter field (numcounter) of number of 
m2m fields attached, and another is post_save so i can decide whether to 
have a OneToOneField (cartrule, is to be applied only if there are more 
than 2 fields) or not.
my models.py is:

class CartItem(models.Model):
content_type= models.ForeignKey(ContentType)
object_id   = models.PositiveIntegerField()
content_object  = generic.GenericForeignKey('content_type','object_id')
quantity= models.PositiveIntegerField(default=0)
is_abandoned= models.BooleanField(default=False)
created_at  = models.DateTimeField(auto_now_add=True)
update_at   = models.DateTimeField(auto_now=True)
def __str__(self):
return self.content_object.name

class CartRule(models.Model):
##some field
pass

class Cart(models.Model):
cart_id = models.CharField(max_length=50, null=False)
customer= models.ForeignKey(Customer,null=True,blank=True)
cartitems   = models.ManyToManyField(CartItem,null=True)
created_at  = models.DateTimeField(auto_now_add=True)
update_at   = models.DateTimeField(auto_now=True)
cartrule   = 
models.OneToOneField(crapclass,null=True,blank=True)
num_cartitem= models.IntegerField()
def __str__(self):
return self.cart_id
 
@receiver(post_save, sender=Cart)
def apply_condition(sender,instance,created,raw,using,*args,**kwargs):
# i want to decide here if num_cartitem is greater than 2 its ok to 
have a cartrule
pass

@receiver(m2m_changed)
def save_cartitem_counter(sender, instance, signal,*args, **kwargs):
if kwargs['action'] == 'post_add':
instance.num_cartitem = instance.cartitems.all().count()
instance.save()

the issue is apply_condition gets called twice, with similar value of args, 
first with older value of m2m (cartitem) field in Cart.
I looked into older post but still could not figure out the whys. 

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




Re: m2m_changed signal can not distinguish between existing and newly added instances

2013-02-07 Thread vijay shanker
well .. odd .. replying my own post .. 
kwargs['action'] 

A string indicating the type of update that is done on the relation. This 
can be one of the following:
"pre_add"Sent *before* one or more objects are added to the relation.
"post_add"Sent *after* one or more objects are added to the relation.
"pre_remove"Sent *before* one or more objects are removed from the relation.
"post_remove"Sent *after* one or more objects are removed from the relation.
"pre_clear"Sent *before* the relation is cleared."post_clear"Sent *after*the 
relation is cleared. 


m2m_changed calls the handle_something function with different 
kwargs['action'] value which can help you differentiate between them.

On Friday, June 8, 2012 7:24:34 PM UTC+5:30, vijay shanker wrote:
>
> hi 
> i have this model  Client_Order 
> i want to do some manipulation each time a new pakg is added to this 
> field. 
> i used m2m_changed signal, but it cant distinguish between existing 
> instances attached and the newly added ones. 
> both post_add and pre_add show the same number of instances .. i.e if 
> a.b were attached and i added c instance to it .. both post_add and 
> pre_add give the same pk_set in kwargs 
>
> ACTV_STATUS = ( 
> ('Active','Active'), 
> ('Inactive','Inactive'), 
> ) 
>
> class Client_Order(models.Model): 
> order_name  = models.CharField(max_length=300) 
> order_desc  = models.TextField(verbose_name="Order 
> Description") 
> order_client= models.ForeignKey(Client_sda) 
> order_active_status = models.CharField(choices = ACTV_STATUS, 
> max_length=300) 
> order_pakages   = models.ManyToManyField(Pakage, 
> help_text="Please attach a maximum of 5 packages only. ") 
> discount= models.IntegerField(default=0) 
> total_amount= models.IntegerField() 
> order_booking_date  = models.DateField() 
> order_expiry_date   = models.DateField() 
>
> @receiver(m2m_changed) 
> def handle_something(sender, instance, signal,*args, **kwargs): 
> print kwargs 
> print 'pk_set->',kwargs['pk_set'] 
>
> how do i distinguish between newly added instances from previously 
> added ones ? 
>

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




Is there any way to apply a constraint on ForeignKey/OneToOneField being attached to any model based on some condition ?

2013-02-07 Thread vijay shanker
Hi
I have these two models Cart and CartItem,

class Cart(models.Model):
cart_id = models.CharField(max_length=
50, null=False)
customer= models.ForeignKey(Customer,null=True,blank=True)
cartitems   = models.ManyToManyField(CartItem,null=True)
applied_rule= 
models.OneToOneField(CartRule,null=True,blank=True)


class CartItem(models.Model):
content_type= models.ForeignKey(ContentType)
object_id   = models.PositiveIntegerField()
content_object  = generic.GenericForeignKey('content_type','object_id')
quantity= models.PositiveIntegerField(default=0)
is_abandoned= models.BooleanField(default=False)
def __str__(self):
return self.cart_id

the rules to be applied only when there are more than two items in 
shoppingcart, i.e i am looking for a way to attach a rule to cart only if 
there are more than two items in cart (cartitems m2m field should have more 
than two objects in it).
How should i go about it ?

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




Is there any way to stop foreignkey being attached to a django model depending upon some constraint ?

2013-02-07 Thread vijay shanker
Hi
I have these two models Cart and CartItem,

class Cart(models.Model):
cart_id = models.CharField(max_length=50, null=False)
customer= models.ForeignKey(Customer,null=True,blank=True)
cartitems   = models.ManyToManyField(CartItem,null=True)
applied_rule= 
models.OneToOneField(CartRule,null=True,blank=True)


class CartItem(models.Model):
content_type= models.ForeignKey(ContentType)
object_id   = models.PositiveIntegerField()
content_object  = generic.GenericForeignKey('content_type','object_id')
quantity= models.PositiveIntegerField(default=0)
is_abandoned= models.BooleanField(default=False)
def __str__(self):
return self.cart_id

the rules to be applied only when there are more than two items in 
shoppingcart, i.e i am looking for a way to attach a rule to cart only if 
there are more than two items in cart (cartitems m2m field should have more 
than two objects in it).
How should i go about it ?

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




Django ForeignKey versus ManyToManyField

2013-02-05 Thread vijay shanker
Hi
I have two models, a Customer model and a WishListItem model (which stores 
products). I have option of either having a ManyToManyField in Customer to 
WishListItem, or I can have a customer ForeignKey to customer for each 
WishListItem.
Which one will be more efficient ? 
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Reverse for 'app_list' with arguments '()' and keyword arguments '{'app_label': ''}' not found.

2012-09-08 Thread vijay shanker
hi
i have this model called charity
___
from django.db import models
from settings import DEFAULT_CHARITY_NAME as deafult_charity_name


class GetDefaultInstance(models.Manager):
def get_default_instance(self):
return 
super(Charity,self).get_query_set().filter(charity_name=default_charity_name)
   

class Charity(models.Model):
class Meta:
verbose_name_plural = 'Charities'
app_label = 'charities'
charity_name= models.CharField(max_length=50)
in_percentage   = models.IntegerField(help_text='default value is 0,\
  leave blank if you will enter 
fixed amount.', default=0, blank=True,null=True)
fixed_amount= models.IntegerField(help_text='default value is 0,\
  leave blank if you entered amount 
in percentage.',default=0, blank=True, null=True  )

objects = models.Manager()
default_instance = GetDefaultInstance()

def __unicode__(self):
return '%s'%self.charity_name

___-

in urls:
(r'^admin/charity_report/(?P[-\w]+)/$', 
'charities.admin_views.report'),
__

and another model called ItemDetails which have forignkey relation with 
above model, with  default instance of charity attached to each Itemdetail 
object .
I wanted to add admin button alongside history button so user can see 
amount charged as charity and stuff like percentage deduction,amount 
deducted etc.

i managed to show the button but when clicked at it gives this trace:
http://pastebin.com/03wscYLX

the settings is at: 
http://pastebin.com/7FYY189D

the other regular info are in:
http://pastebin.com/QmAdEeP9

its been 2-3 days trying to run it on apache server.. it works ok on local 
machine.

i override form_change template and provide the button, write urls for 
admin 

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

{% extends "admin/change_form.html" %}
{% load mini_shop_tags %}
{% load i18n %}
{% block object-tools %}
{% if change %}{% if not is_popup %}
  
{% trans "History" %}
{% if opts.module_name == "item" %}
Charity Report
{% endif %}
{% if has_absolute_url %}

{% trans "View on site" %}

{% endif%}
  
{% endif %}{% endif %}
{% endblock %}from charities.models import Charity, GetDefaultInstance
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required
from generoucity.mini_shop.extensions.deals.models import ItemDetails 
from generoucity.mini_shop.models import Item

class CharityReport(object):
def __init__(self,request,itemdetails_id):
self.request = request
self.itemdetails_id = itemdetails_id

def render_report(self):
data = {}
item = Item.objects.get(pk=self.itemdetails_id)
itemdetail_obj  = ItemDetails.objects.get(item=item)
charity_obj = itemdetail_obj.charity
if not type(charity_obj) is type('NoneType'):
data['charity_name'] = charity_obj.charity_name
else:
data['charity_name'] = 'No charity is associated with this deal.'
data['price'] = item.price
if charity_obj.in_percentage:
data['charity_category'] = 'Fixed Percentage: %s '%(charity_obj.in_percentage)
data['charity_amount'] = (float(charity_obj.in_percentage)/100)*item.price
else:
data['charity_category'] = 'By Fixed Amount: %d'%(charity_obj.fixed_amount)
data['charity_amount'] = charity_obj.fixed_amount
data['item'] = item.name
return render_to_response("admin/mini_shop/extensions/deals/charity_report.html",locals(),RequestContext(self.request,{}))

def report(request,itemdetails_id):
charity_report_object = CharityReport(request, itemdetails_id)
return charity_report_object.render_report()



report = staff_member_required(report)

from models import Charity
import datetime
from django.conf import settings

def charity_admin(request):
charities = Charity.objects.all()
return {"charities": charities,}
from django.db import models
from settings import DEFAULT_CHARITY_NAME as deafult_charity_name


class GetDefaultInstance(models.Manager):
def get_default_instance(self):
return super(Charity,self).get_query_set().filter(charity_name=default_charity_name)
   

class Charity(models.Model):

Reverse for 'app_list' with arguments '()' and keyword arguments '{'app_label': ''}' not found.

2012-09-08 Thread vijay shanker
hi
i tried overriding change_form to add a extra button along side history 
button in django admin section.. on local machine it works fine but on 
server it gives me this error.
I have no clear idea what went wrong and how to fix it .


Environment:


Request Method: GET
Request URL: http://108.166.89.168/admin/charity_report/166/

Django Version: 1.4.1
Python Version: 2.7.1
Installed Applications:
('sorl.thumbnail',
 'south',
 'generoucity.newsletter',
 'django.contrib.comments',
 'django.contrib.messages',
 'django.contrib.flatpages',
 'django.contrib.humanize',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.staticfiles',
 'generoucity.mini_shop',
 'generoucity.mini_shop.extensions.deals',
 'generoucity.treemenus',
 'generoucity.social_auth',
 'generoucity.registration',
 'mptt',
 'captcha',
 'charities')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.middleware.doc.XViewMiddleware',
 'generoucity.mini_shop.extensions.deals.middleware.LocationCookieMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" 
in get_response
  111. response = callback(request, *callback_args, 
**callback_kwargs)
File 
"/usr/local/lib/python2.7/dist-packages/django/contrib/admin/views/decorators.py"
 
in _checklogin
  16. return view_func(request, *args, **kwargs)
File "/usr/gen1/generoucity_2011.com/generoucity/charities/admin_views.py" 
in report
  34. return charity_report_object.render_report()
File "/usr/gen1/generoucity_2011.com/generoucity/charities/admin_views.py" 
in render_report
  30. return 
render_to_response("admin/mini_shop/extensions/deals/charity_report.html",locals(),RequestContext(self.request,{}))
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" 
in render_to_response
  20. return HttpResponse(loader.render_to_string(*args, **kwargs), 
**httpresponse_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in 
render_to_string
  176. return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  140. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
_render
  134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  823. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render_node
  837. return node.render(context)
File 
"/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in 
render
  123. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
_render
  134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  823. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render_node
  837. return node.render(context)
File 
"/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in 
render
  123. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
_render
  134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  823. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render_node
  837. return node.render(context)
File 
"/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py" in 
render
  123. return compiled_parent._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
_render
  134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  823. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render_node
  837. return node.render(context)
File 
"/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in 
render
  281. return nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render
  823. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in 
render_node
  837. 

advantages and disadvantages of Raw sql queries in django

2012-06-29 Thread vijay shanker
hi
i want to know pros and cons associated with running raw sql queries
over django's ORM .
googled it out but couldn find many useful links.

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



how to exclude some field from BaseInlineFormSet

2012-06-12 Thread vijay shanker
hi
i am trying to do this:
class PakageInfoForm(BaseInlineFormSet):
class Meta:
model = PakageInfo
exclude = ['client_sda',]
this doesn works ..
how to exclude any field from BaseInlineFormSet ..

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



m2m_changed signal can not distinguish between existing and newly added instances

2012-06-08 Thread vijay shanker
hi
i have this model  Client_Order
i want to do some manipulation each time a new pakg is added to this
field.
i used m2m_changed signal, but it cant distinguish between existing
instances attached and the newly added ones.
both post_add and pre_add show the same number of instances .. i.e if
a.b were attached and i added c instance to it .. both post_add and
pre_add give the same pk_set in kwargs

ACTV_STATUS = (
('Active','Active'),
('Inactive','Inactive'),
)

class Client_Order(models.Model):
order_name  = models.CharField(max_length=300)
order_desc  = models.TextField(verbose_name="Order
Description")
order_client= models.ForeignKey(Client_sda)
order_active_status = models.CharField(choices = ACTV_STATUS,
max_length=300)
order_pakages   = models.ManyToManyField(Pakage,
help_text="Please attach a maximum of 5 packages only. ")
discount= models.IntegerField(default=0)
total_amount= models.IntegerField()
order_booking_date  = models.DateField()
order_expiry_date   = models.DateField()

@receiver(m2m_changed)
def handle_something(sender, instance, signal,*args, **kwargs):
print kwargs
print 'pk_set->',kwargs['pk_set']

how do i distinguish between newly added instances from previously
added ones ?

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



Re: limit number of related instance for m2m field in django-admin

2012-06-08 Thread vijay shanker
override def clean() of form and raise forms.ValidationError( 'Your
Error Message here' )

On Jun 7, 6:45 pm, Kurtis Mullins <kurtis.mull...@gmail.com> wrote:
> You could customize the Admin Book Creation Form's save() method to check
> for X number of books an author already has.
>
> Note: I have very limited experience customizing the Admin application and
> have only used this method through a normal Form.
>
>
>
>
>
>
>
> On Thu, Jun 7, 2012 at 7:56 AM, vijay shanker <vshanker...@gmail.com> wrote:
> > hi
> > is there any way to limit the number of instances that can be attached
> > to a m2m field.
> > e.g
> > author = models.manytomany(Book)
>
> > i want to limit the max number of book objects that can be attached to
> > author.
> > How to go about this.
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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



how to have a foreign key to a field of same model which in turn is foreign key to another model ..

2012-06-07 Thread vijay shanker
hi
how can i have this:
client_groups = models.ForeignKey(User, to_field="groups")

it din worked

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



limit number of related instance for m2m field in django-admin

2012-06-07 Thread vijay shanker
hi
is there any way to limit the number of instances that can be attached
to a m2m field.
e.g
author = models.manytomany(Book)

i want to limit the max number of book objects that can be attached to
author.
How to go about this.

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



App inside another app or nesting in django apps

2012-05-31 Thread vijay shanker
can we write one app inside some another django-app .
please suggest any reference or articles

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



sqlall fails silently

2012-05-31 Thread vijay shanker
hi
i defined three models and put them in /appname/models/ a.py, b.py,
c.py. and a __init__.py in which i import all classes defined inside
a.py/b.py/c.py.

when i try to do a ./manage.py sqll appname at prompt , it simply
passes of without any output.
 what could be possibly done to debug it .. i had put the appname in
installed_apps, other app respond to sqlall printing related mysql
queries .
thanks


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



two versions of django onsame machine .. django and django-norel

2012-05-16 Thread vijay shanker
i have installed django 1.4 previously and want to install django-
norel now.. should i unisntall django 1.4 first .. is it necessary

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



is doing text manipulations in django-template fater than doing same in views

2012-03-29 Thread vijay shanker
i have to do basic text manipulations at times .. which is a better
way.. to do so in template or return a result only after doing so from
views ??

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



is doing text manipulations in django's template faster than doing same in views

2012-03-29 Thread vijay shanker
which one is faster or considered better in terms of performance ?

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



passing '&' in url

2012-02-28 Thread vijay shanker
i need to pass " & " as query e.g q=larsen & turbo
urlencode does not works as finally its as good as without it for
above eg.
please suggest.

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