Can't make an object with a foreign key

2013-03-19 Thread Cody Scott
Can't make an object with a foreign key. When I submit it says 

Cannot assign "u'Category object'": "Course.category" must be a "Category" 
> instance.
>
 
Here is my admin form 

admin.py
 

> admin.site.register(Category, list_display = ('name',))
> CATEGORIES = [(category, category.name) for category in Category.objects.
> all()]
>
 

> class CourseAdminForm(forms.ModelForm):
> class Meta:
> model = Course
> category = forms.ChoiceField(choices=CATEGORIES)
>
 

> class CourseAdmin(admin.ModelAdmin):
>  form = CourseAdminForm
>
 

> admin.site.register(Course, CourseAdmin)


 

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




Can't create an object with a foreign key

2013-03-19 Thread Cody Scott
I get the error when I try to make an object.

Cannot assign "u'Category object'": "Course.category" must be a "Category" 
> instance.


here is my admin form

admin.py

admin.site.register(Category, list_display = ('name',))

CATEGORIES = [(category, category.name) for category in Category.objects.all()]
class CourseAdminForm(forms.ModelForm):
class Meta:
model = Course
category = forms.ChoiceField(choices=CATEGORIES)
class CourseAdmin(admin.ModelAdmin):
form = CourseAdminForm
 

admin.site.register(Course, CourseAdmin) 

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




How to create a form list for a Model Form dynamically?

2013-04-01 Thread Cody Scott
I am trying to make a simple quiz app.

I am trying to go to the URL /quiz/ and using the quiz_id which 
has a list of questions associated with the quiz id and create a list of 
forms to use in the model form.

In the urls.py file I know you can pass a list of forms to be used, but I 
need to create the list of forms at runtime.

I have tried passing the return value of a function as parameter but can't 
figure out the syntax.

(r'^(?P\d+)', QuizWizard.as_view(get_form_list)),
the function get_form_list has no length

(r'^(?P\d+)', QuizWizard.as_view(get_form_list(quiz_id))),
Quiz_id is unknown.


So I create a view and I create the form list inside the view and then call 
QuizWizard.as_view


#views.pyclass QuizWizard(SessionWizardView):
def __init__(self, **kwargs):
self.form_list = kwargs.pop('form_list')
return super(QuizWizard, self).__init__(**kwargs)

def done(self, **kwargs):
return render_to_response('done.html', {
'form_data':[form.cleaned_data for form in self.form_list],
})
def get_form_list(request, quiz_id):
quiz = Quiz.objects.get(id=quiz_id)

question_forms = []

for question in quiz.questions.all():
choices = []
for choice in question.choices.all():
choices.append(choice)
f = QuestionForm(instance=question)
question_forms.append(f)

#quiz_wizard = QuizWizard()
return QuizWizard.as_view(form_list=question_forms)(request)


But I am getting the error 

issubclass() arg 1 must be a class



My issue is syntax either way I can't figure out how to call the 
QuizWizard.as_view(). Here are related files:


#forms.py

class QuestionForm(forms.ModelForm):
class Meta:
model = Question


#urls.py

urlpatterns = patterns ('',
url(r'^(?P\d+)', 'quiz.views.get_form_list'),)


#models.py

class Choice(models.Model):
choice = models.CharField(max_length=64)
def __unicode__(self):
return self.choice

#create a multiple choice quiz to start
class Question(models.Model):
question = models.CharField(max_length=64)
answer = models.CharField(max_length=64)
choices = models.ManyToManyField(Choice)
module = models.CharField(max_length=64)

def __unicode__(self):
return self.question

class Quiz(models.Model):
name = models.CharField(max_length=64)
questions = models.ManyToManyField(Question)

def __unicode__(self):
return self.name


Full Traceback: http://bpaste.net/show/0YNrLYJSdjdJ7Hea5q1c/

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




Re: How to create a form list for a Model Form dynamically?

2013-04-03 Thread Cody Scott
The function I was calling there was in the urls.py file and it only took 
one parameter. I tried it again and with passing request and it still says 
quiz_id is unknown...

On Monday, April 1, 2013 10:17:13 AM UTC-4, Cody Scott wrote:
>
> I am trying to make a simple quiz app.
>
> I am trying to go to the URL /quiz/ and using the quiz_id which 
> has a list of questions associated with the quiz id and create a list of 
> forms to use in the model form.
>
> In the urls.py file I know you can pass a list of forms to be used, but I 
> need to create the list of forms at runtime.
>
> I have tried passing the return value of a function as parameter but can't 
> figure out the syntax.
>
> (r'^(?P\d+)', QuizWizard.as_view(get_form_list)),
> the function get_form_list has no length
>
> (r'^(?P\d+)', QuizWizard.as_view(get_form_list(quiz_id))),
> Quiz_id is unknown.
>
>
> So I create a view and I create the form list inside the view and then call 
> QuizWizard.as_view
>
>
> #views.pyclass QuizWizard(SessionWizardView):
> def __init__(self, **kwargs):
> self.form_list = kwargs.pop('form_list')
> return super(QuizWizard, self).__init__(**kwargs)
>
> def done(self, **kwargs):
> return render_to_response('done.html', {
> 'form_data':[form.cleaned_data for form in self.form_list],
> })
> def get_form_list(request, quiz_id):
> quiz = Quiz.objects.get(id=quiz_id)
>
> question_forms = []
>
> for question in quiz.questions.all():
> choices = []
> for choice in question.choices.all():
> choices.append(choice)
> f = QuestionForm(instance=question)
> question_forms.append(f)
> 
> #quiz_wizard = QuizWizard()
> return QuizWizard.as_view(form_list=question_forms)(request)
>
>
> But I am getting the error 
>
> issubclass() arg 1 must be a class
>
>
>
> My issue is syntax either way I can't figure out how to call the 
> QuizWizard.as_view(). Here are related files:
>
>
> #forms.py
>
> class QuestionForm(forms.ModelForm):
> class Meta:
> model = Question
>
>
> #urls.py
>
> urlpatterns = patterns ('',
> url(r'^(?P\d+)', 'quiz.views.get_form_list'),)
>
>
> #models.py
>
> class Choice(models.Model):
> choice = models.CharField(max_length=64)
> def __unicode__(self):
> return self.choice
>   
> #create a multiple choice quiz to start
> class Question(models.Model):
> question = models.CharField(max_length=64)
> answer = models.CharField(max_length=64)
> choices = models.ManyToManyField(Choice)
> module = models.CharField(max_length=64)
>
> def __unicode__(self):
> return self.question
>
> class Quiz(models.Model):
> name = models.CharField(max_length=64)
> questions = models.ManyToManyField(Question)
>
> def __unicode__(self):
> return self.name
>
>
> Full Traceback: http://bpaste.net/show/0YNrLYJSdjdJ7Hea5q1c/
>
>

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




Re: How to create a form list for a Model Form dynamically?

2013-04-03 Thread Cody Scott
I needed to pass an instance dictionary, but now I am having a problem with 
my models?
http://stackoverflow.com/questions/15684557/setting-choices-and-forms-at-runtime-for-a-form-wizard

On Wednesday, April 3, 2013 11:06:57 AM UTC-4, Nick D wrote:
>
> I see; I didn't understand the flow at first.
>  
> Is this line wrong "quiz = Quiz.objects.get(id=quiz_id)"?
>  
> I don't think Django names the pk "id" by default. Maybe it should be:
>  
> quiz = Quiz.objects.get(pk=quiz_id)
>
> On Monday, April 1, 2013 7:17:13 AM UTC-7, Cody Scott wrote:
>
>> I am trying to make a simple quiz app.
>>
>> I am trying to go to the URL /quiz/ and using the quiz_id which 
>> has a list of questions associated with the quiz id and create a list of 
>> forms to use in the model form.
>>
>> In the urls.py file I know you can pass a list of forms to be used, but I 
>> need to create the list of forms at runtime.
>>
>> I have tried passing the return value of a function as parameter but 
>> can't figure out the syntax.
>>
>> (r'^(?P\d+)', QuizWizard.as_view(get_form_list)),
>> the function get_form_list has no length
>>
>> (r'^(?P\d+)', QuizWizard.as_view(get_form_list(quiz_id))),
>> Quiz_id is unknown.
>>
>>
>> So I create a view and I create the form list inside the view and then call 
>> QuizWizard.as_view
>>
>>
>> #views.pyclass QuizWizard(SessionWizardView):
>> def __init__(self, **kwargs):
>> self.form_list = kwargs.pop('form_list')
>> return super(QuizWizard, self).__init__(**kwargs)
>>
>> def done(self, **kwargs):
>> return render_to_response('done.html', {
>> 'form_data':[form.cleaned_data for form in self.form_list],
>> })
>> def get_form_list(request, quiz_id):
>> quiz = Quiz.objects.get(id=quiz_id)
>>
>> question_forms = []
>>
>> for question in quiz.questions.all():
>> choices = []
>> for choice in question.choices.all():
>> choices.append(choice)
>> f = QuestionForm(instance=question)
>> question_forms.append(f)
>> 
>> #quiz_wizard = QuizWizard()
>> return QuizWizard.as_view(form_list=question_forms)(request)
>>
>>
>> But I am getting the error 
>>
>> issubclass() arg 1 must be a class
>>
>>
>>
>> My issue is syntax either way I can't figure out how to call the 
>> QuizWizard.as_view(). Here are related files:
>>
>>
>> #forms.py
>>
>> class QuestionForm(forms.ModelForm):
>> class Meta:
>> model = Question
>>
>>
>> #urls.py
>>
>> urlpatterns = patterns ('',
>> url(r'^(?P\d+)', 'quiz.views.get_form_list'),)
>>
>>
>> #models.py
>>
>> class Choice(models.Model):
>> choice = models.CharField(max_length=64)
>> def __unicode__(self):
>> return self.choice
>>  
>> #create a multiple choice quiz to start
>> class Question(models.Model):
>> question = models.CharField(max_length=64)
>> answer = models.CharField(max_length=64)
>> choices = models.ManyToManyField(Choice)
>> module = models.CharField(max_length=64)
>>
>> def __unicode__(self):
>> return self.question
>>
>> class Quiz(models.Model):
>> name = models.CharField(max_length=64)
>> questions = models.ManyToManyField(Question)
>>
>> def __unicode__(self):
>> return self.name
>>
>>
>> Full Traceback: http://bpaste.net/show/0YNrLYJSdjdJ7Hea5q1c/
>>
>>

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




Why is there no view for sign up in django.contrib.auth.views?

2013-04-05 Thread Cody Scott
If I want users to sign up for my site, I need to make a register view, 
register form and a register template.

Why is there a view and form for every other user account action (login, 
logout, etc.)


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




Why is a username required for a User?

2013-04-08 Thread Cody Scott
To create a User object you need to have a unique username.

I would like to use an email and a password to identify users, since an 
email is already required for my site's functionality.

It seems silly for a framework so restrict you.


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




Re: Why is a username required for a User?

2013-04-08 Thread Cody Scott
Yes I am using Django 1.5

On Monday, 8 April 2013 11:11:57 UTC-4, Anderson Borges wrote:
>
> Hey Cody are using django 1.5?
>
>
> On Mon, Apr 8, 2013 at 9:09 AM, Cody Scott 
> > wrote:
>
>> To create a User object you need to have a unique username.
>>
>> I would like to use an email and a password to identify users, since an 
>> email is already required for my site's functionality.
>>
>> It seems silly for a framework so restrict you.
>>
>>
>>  -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@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.
>>  
>>  
>>
>
>
>
> -- 
> Anderson Dias Borges
> Senior Analyst Developer
>
> Tu cumprirás o desejo do meu coração se eu Te buscar...
> I can't see but I'll take my chances
> To hear You call my name 
>

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




Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
I placed the code in those places, I put AUTH_USER_MODEL = 'auth.Users' 
right after INSTALLED_APPS

"CommandError: One or more models did not validate:
auth.user: Model has been swapped out for 'auth.Users' which has not been 
installed or is abstract.
admin.logentry: 'user' has a relation with model auth.Users, which has 
either not been installed or is abstract."

On Monday, 8 April 2013 11:56:40 UTC-4, Anderson Borges wrote:
>
> You can use BaseUserManager, AbstractBaseUser,PermissionsMixin.
> here is a exemple:
>
> from django.db import models
> from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, 
> BaseUserManager
> from django.confimport settings
>
>
> class MyUserManager(BaseUserManager):
> def create_user(self, email, password=None):
> if not email:
> raise ValueError('Users must have an email address')
>
> user = self.model(
> email=MyUserManager.normalize_email(email),
> )
> user.set_password(password)
> user.save(using=self._db)
> return user
>
> def create_superuser(self, email, password):  
> user = self.create_user(email,
> password=password
> )
> user.is_admin = True
> user.save(using=self._db)
> return user
>
> class Users(AbstractBaseUser,PermissionsMixin):
> email = models.EmailField(verbose_name='email address', 
> max_length=255,unique=True,db_index=True,)  
> name  = models.CharField(verbose_name='Name', 
> max_length=50,blank=True) 
> is_active = models.BooleanField(default=True)
> is_admin = models.BooleanField(default=False)
> is_customer = models.BooleanField(default=False)
> datecreated = models.DateField(auto_now=True)
> 
> objects = MyUserManager()
> USERNAME_FIELD = 'email'   
> REQUIRED_FIELDS = ['name']
> 
> def get_full_name(self):
> return self.email
>
> def get_short_name(self):   
> return self.email
>
> def __unicode__(self):
> return self.email
>
> @property
> def is_staff(self): 
> return self.is_admin
>
>
>
> Now in your settings you have to add : AUTH_USER_MODEL = 'auth.Users'
>
>
>
>
>
>
> If you want change in ADMIN here the code
>
>
> from django.contrib import admin
> from django import forms
> from django.contrib.auth.admin import UserAdmin
> from django.contrib.auth.forms import ReadOnlyPasswordHashField
>
> from models import Users
>
> class UserCreationForm(forms.ModelForm):   
> password1 = forms.CharField(label='Password', 
> widget=forms.PasswordInput)
> password2 = forms.CharField(label='Password confirmation', 
> widget=forms.PasswordInput)
>
> class Meta:
> model = Users
>
> def clean_password2(self):
> # Check that the two password entries match
> password1 = self.cleaned_data.get("password1")
> password2 = self.cleaned_data.get("password2")
> if password1 and password2 and password1 != password2:
> raise forms.ValidationError("Passwords don't match")
> return password2
>
> def save(self, commit=True):
> # Save the provided password in hashed format
> user = super(UserCreationForm, self).save(commit=False)
> user.set_password(self.cleaned_data["password1"])
> if commit:
> user.save()
> return user
> 
> class UserChangeForm(forms.ModelForm):
> password = ReadOnlyPasswordHashField()
> class Meta:
> model = Users
>
> def clean_password(self):
> return self.initial["password"]
> 
> class MyUserAdmin(UserAdmin):
> form = UserChangeForm
> add_form = UserCreationForm
>
> list_display = ('email', 'is_admin')
> list_filter = ('is_admin',)
> fieldsets = (
> (None, {'fields': ('email', 'password')}),   
> ('Permissions', {'fields': 
> ('is_admin','groups','user_permissions')}),
> ('Important dates', {'fields': ('last_login',)}),
> )
> add_fieldsets = (
> (None, {
> 'classes': ('wide',),
> 'fields': ('emai

Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
Thank you that was my issue. Now syncdb works I also needed to add a name 
parameter to create_superuser and create_user and make sure create_super 
user has the name in the call to self.create_user

I see h

On Tuesday, 9 April 2013 10:05:33 UTC-4, heartbr...@gmail.com wrote:
>
> Is your new 'Users' class defined in an 'auth' module/app inside your 
> project?
>
> I guess the problem here is that you are supposed to refer to the module 
> containing the 'models.py' in which you have defined 'Users' class.
>
> For example, if your module/app is 'mysite' and you have defined 'Users' 
> class in 'mysite/models.py', then your settings.AUTH_USER_MODEL should be 
> 'mysite.Users'
>
>
> On Tue, Apr 9, 2013 at 4:52 PM, Cody Scott 
> > wrote:
>
>> I placed the code in those places, I put AUTH_USER_MODEL = 
>> 'auth.Users' right after INSTALLED_APPS
>>
>> "CommandError: One or more models did not validate:
>> auth.user: Model has been swapped out for 'auth.Users' which has not been 
>> installed or is abstract.
>> admin.logentry: 'user' has a relation with model auth.Users, which has 
>> either not been installed or is abstract."
>>
>> On Monday, 8 April 2013 11:56:40 UTC-4, Anderson Borges wrote:
>>
>>> You can use BaseUserManager, AbstractBaseUser,**PermissionsMixin.
>>> here is a exemple:
>>>
>>> from django.db import models
>>> from django.contrib.auth.models import AbstractBaseUser, 
>>> PermissionsMixin, BaseUserManager
>>> from django.confimport settings
>>>
>>>
>>> class MyUserManager(BaseUserManager)**:
>>> def create_user(self, email, password=None):
>>> if not email:
>>> raise ValueError('Users must have an email address')
>>>
>>> user = self.model(
>>> email=MyUserManager.normalize_**email(email),
>>> )
>>> user.set_password(password)
>>> user.save(using=self._db)
>>> return user
>>>
>>> def create_superuser(self, email, password):  
>>> user = self.create_user(email,
>>> password=password
>>> )
>>> user.is_admin = True
>>> user.save(using=self._db)
>>> return user
>>>
>>> class Users(AbstractBaseUser,**PermissionsMixin):
>>> email = models.EmailField(verbose_**name='email 
>>> address', max_length=255,unique=True,db_**index=True,)  
>>> name  = models.CharField(verbose_name=**'Name', 
>>> max_length=50,blank=True) 
>>> is_active = models.BooleanField(default=**True)
>>> is_admin = models.BooleanField(default=**False)
>>> is_customer = models.BooleanField(default=**False)
>>> datecreated = models.DateField(auto_now=**True)
>>> 
>>> objects = MyUserManager()
>>> USERNAME_FIELD = 'email'   
>>> REQUIRED_FIELDS = ['name']
>>> 
>>> def get_full_name(self):
>>> return self.email
>>>
>>> def get_short_name(self):   
>>> return self.email
>>>
>>> def __unicode__(self):
>>> return self.email
>>>
>>> @property
>>> def is_staff(self): 
>>> return self.is_admin
>>>
>>>
>>>
>>> Now in your settings you have to add : AUTH_USER_MODEL = 'auth.Users'
>>>
>>>
>>>
>>>
>>>
>>>
>>> If you want change in ADMIN here the code
>>>
>>>
>>> from django.contrib import admin
>>> from django import forms
>>> from django.contrib.auth.admin import UserAdmin
>>> from django.contrib.auth.forms import ReadOnlyPasswordHashField
>>>
>>> from models import Users
>>>
>>> class UserCreationForm(forms.**ModelForm):   
>>> password1 = forms.CharField(label='**Password', 
>>> widget=forms.PasswordInput)
>>> password2 = forms.CharField(label='**Password confirmation', 
>>> widget=forms.PasswordInput)
>>>
>>> class Meta:
>>> model = Users
>>>
>>> def clean_password2(self):
>>> # Check that the two password entries match
&

Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
Except the super user I created with syncdb doesn't have access to anything

On Tuesday, 9 April 2013 10:24:19 UTC-4, Cody Scott wrote:
>
> Thank you that was my issue. Now syncdb works I also needed to add a name 
> parameter to create_superuser and create_user and make sure create_super 
> user has the name in the call to self.create_user
>
>
>
> On Tuesday, 9 April 2013 10:05:33 UTC-4, heartbr...@gmail.com wrote:
>>
>> Is your new 'Users' class defined in an 'auth' module/app inside your 
>> project?
>>
>> I guess the problem here is that you are supposed to refer to the module 
>> containing the 'models.py' in which you have defined 'Users' class.
>>
>> For example, if your module/app is 'mysite' and you have defined 'Users' 
>> class in 'mysite/models.py', then your settings.AUTH_USER_MODEL should be 
>> 'mysite.Users'
>>
>>
>> On Tue, Apr 9, 2013 at 4:52 PM, Cody Scott  wrote:
>>
>>> I placed the code in those places, I put AUTH_USER_MODEL = 
>>> 'auth.Users' right after INSTALLED_APPS
>>>
>>> "CommandError: One or more models did not validate:
>>> auth.user: Model has been swapped out for 'auth.Users' which has not 
>>> been installed or is abstract.
>>> admin.logentry: 'user' has a relation with model auth.Users, which has 
>>> either not been installed or is abstract."
>>>
>>> On Monday, 8 April 2013 11:56:40 UTC-4, Anderson Borges wrote:
>>>
>>>> You can use BaseUserManager, AbstractBaseUser,**PermissionsMixin.
>>>> here is a exemple:
>>>>
>>>> from django.db import models
>>>> from django.contrib.auth.models import AbstractBaseUser, 
>>>> PermissionsMixin, BaseUserManager
>>>> from django.confimport settings
>>>>
>>>>
>>>> class MyUserManager(BaseUserManager)**:
>>>> def create_user(self, email, password=None):
>>>> if not email:
>>>> raise ValueError('Users must have an email address')
>>>>
>>>> user = self.model(
>>>> email=MyUserManager.normalize_**email(email),
>>>> )
>>>> user.set_password(password)
>>>> user.save(using=self._db)
>>>> return user
>>>>
>>>> def create_superuser(self, email, password):  
>>>> user = self.create_user(email,
>>>> password=password
>>>> )
>>>> user.is_admin = True
>>>> user.save(using=self._db)
>>>> return user
>>>>
>>>> class Users(AbstractBaseUser,**PermissionsMixin):
>>>> email = models.EmailField(verbose_**name='email 
>>>> address', max_length=255,unique=True,db_**index=True,)  
>>>> name  = models.CharField(verbose_name=**'Name', 
>>>> max_length=50,blank=True) 
>>>> is_active = models.BooleanField(default=**True)
>>>> is_admin = models.BooleanField(default=**False)
>>>> is_customer = models.BooleanField(default=**False)
>>>> datecreated = models.DateField(auto_now=**True)
>>>> 
>>>> objects = MyUserManager()
>>>> USERNAME_FIELD = 'email'   
>>>> REQUIRED_FIELDS = ['name']
>>>> 
>>>> def get_full_name(self):
>>>> return self.email
>>>>
>>>> def get_short_name(self):   
>>>> return self.email
>>>>
>>>> def __unicode__(self):
>>>> return self.email
>>>>
>>>> @property
>>>> def is_staff(self): 
>>>> return self.is_admin
>>>>
>>>>
>>>>
>>>> Now in your settings you have to add : AUTH_USER_MODEL = 
>>>> 'auth.Users'
>>>>
>>>>
>>>>
>>>>
>>>>
>>>>
>>>> If you want change in ADMIN here the code
>>>>
>>>>
>>>> from django.contrib import admin
>>>> from django import forms
>>>> from django.contrib.auth.admin import UserAdmin
>>>> from django.contrib.auth.forms import ReadOnlyPasswordHashField
>>

Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
In models.py in /django/contrib/auth there is a 

u.is_superuser = True

but when I add it just like how is_staff and is_active are added I get the 
error 

"FieldError: Local field 'is_superuser' in class 'Users' clashes with field 
of similar name from base class 'PermissionsMixin'
"

On Monday, 8 April 2013 11:09:29 UTC-4, Cody Scott wrote:
>
> To create a User object you need to have a unique username.
>
> I would like to use an email and a password to identify users, since an 
> email is already required for my site's functionality.
>
> It seems silly for a framework so restrict you.
>
>
>

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




Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
In the docs
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-django-contrib-admin

It says to use with admin you need the following methods
is_active, has_perm, has_module_perms

So I added them but I don't really understand how to do permissions

Here is the code I put in Users

def __unicode__(self):
return self.email

@property
def is_staff(self):
return self.is_admin

#start of new code
def is_active(self):
return self.is_active

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, app_label):
return True


On Tue, Apr 9, 2013 at 11:05 AM, Cody Scott wrote:

> In models.py in /django/contrib/auth there is a
>
> u.is_superuser = True
>
> but when I add it just like how is_staff and is_active are added I get the
> error
>
> "FieldError: Local field 'is_superuser' in class 'Users' clashes with
> field of similar name from base class 'PermissionsMixin'
> "
>
> On Monday, 8 April 2013 11:09:29 UTC-4, Cody Scott wrote:
>>
>> To create a User object you need to have a unique username.
>>
>> I would like to use an email and a password to identify users, since an
>> email is already required for my site's functionality.
>>
>> It seems silly for a framework so restrict you.
>>
>>
>>  --
> 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/zAMBjf6WmFU/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: Why is a username required for a User?

2013-04-09 Thread Cody Scott
If I don't have them and I log in to admin I get
"You don't have permission to edit anything."


On Tue, Apr 9, 2013 at 11:28 AM, Anderson  wrote:

> You don't have to worry about permissions all these methods come with
> PermissionsMixin and is_superuser too.
>
> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#auth-custom-user
>
> Do not override those methods otherwise all users will return always true.
>
>
> On Tue, Apr 9, 2013 at 9:22 AM, Cody Scott wrote:
>
>> In the docs
>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-django-contrib-admin
>>
>> It says to use with admin you need the following methods
>> is_active, has_perm, has_module_perms
>>
>> So I added them but I don't really understand how to do permissions
>>
>> Here is the code I put in Users
>>
>> def __unicode__(self):
>> return self.email
>>
>> @property
>> def is_staff(self):
>> return self.is_admin
>>
>> #start of new code
>> def is_active(self):
>> return self.is_active
>>
>> def has_perm(self, perm, obj=None):
>> return True
>>
>> def has_module_perms(self, app_label):
>> return True
>>
>>
>> On Tue, Apr 9, 2013 at 11:05 AM, Cody Scott wrote:
>>
>>> In models.py in /django/contrib/auth there is a
>>>
>>> u.is_superuser = True
>>>
>>> but when I add it just like how is_staff and is_active are added I get
>>> the error
>>>
>>> "FieldError: Local field 'is_superuser' in class 'Users' clashes with
>>> field of similar name from base class 'PermissionsMixin'
>>> "
>>>
>>> On Monday, 8 April 2013 11:09:29 UTC-4, Cody Scott wrote:
>>>>
>>>> To create a User object you need to have a unique username.
>>>>
>>>> I would like to use an email and a password to identify users, since an
>>>> email is already required for my site's functionality.
>>>>
>>>> It seems silly for a framework so restrict you.
>>>>
>>>>
>>>>  --
>>> 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/zAMBjf6WmFU/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.
>>
>>
>>
>
>
>
> --
> Anderson Dias Borges
> Senior Analyst Developer
>
> Tu cumprirás o desejo do meu coração se eu Te buscar...
> I can't see but I'll take my chances
> To hear You call my name
>
> --
> 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/zAMBjf6WmFU/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: Why is a username required for a User?

2013-04-09 Thread Cody Scott
OK so how do I access the admin then?


On Tue, Apr 9, 2013 at 11:56 AM, Anderson  wrote:

> No . inside has_perm before check  whether you have permission or not is
> going to check if you are active and superuser.
>
> # Active superusers have all permissions.
> if self.is_active and self.is_superuser:
> return True
>
>
> On Tue, Apr 9, 2013 at 9:46 AM, Cody Scott wrote:
>
>> If I don't have them and I log in to admin I get
>> "You don't have permission to edit anything."
>>
>>
>> On Tue, Apr 9, 2013 at 11:28 AM, Anderson wrote:
>>
>>> You don't have to worry about permissions all these methods come with
>>> PermissionsMixin and is_superuser too.
>>>
>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#auth-custom-user
>>>
>>> Do not override those methods otherwise all users will return always
>>> true.
>>>
>>>
>>> On Tue, Apr 9, 2013 at 9:22 AM, Cody Scott wrote:
>>>
>>>> In the docs
>>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-django-contrib-admin
>>>>
>>>> It says to use with admin you need the following methods
>>>> is_active, has_perm, has_module_perms
>>>>
>>>> So I added them but I don't really understand how to do permissions
>>>>
>>>> Here is the code I put in Users
>>>>
>>>> def __unicode__(self):
>>>> return self.email
>>>>
>>>> @property
>>>> def is_staff(self):
>>>> return self.is_admin
>>>>
>>>> #start of new code
>>>> def is_active(self):
>>>> return self.is_active
>>>>
>>>> def has_perm(self, perm, obj=None):
>>>> return True
>>>>
>>>> def has_module_perms(self, app_label):
>>>> return True
>>>>
>>>>
>>>> On Tue, Apr 9, 2013 at 11:05 AM, Cody Scott 
>>>> wrote:
>>>>
>>>>> In models.py in /django/contrib/auth there is a
>>>>>
>>>>> u.is_superuser = True
>>>>>
>>>>> but when I add it just like how is_staff and is_active are added I get
>>>>> the error
>>>>>
>>>>> "FieldError: Local field 'is_superuser' in class 'Users' clashes with
>>>>> field of similar name from base class 'PermissionsMixin'
>>>>> "
>>>>>
>>>>> On Monday, 8 April 2013 11:09:29 UTC-4, Cody Scott wrote:
>>>>>>
>>>>>> To create a User object you need to have a unique username.
>>>>>>
>>>>>> I would like to use an email and a password to identify users, since
>>>>>> an email is already required for my site's functionality.
>>>>>>
>>>>>> It seems silly for a framework so restrict you.
>>>>>>
>>>>>>
>>>>>>  --
>>>>> 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/zAMBjf6WmFU/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.
>>>>
>>>>
>>>>
>>>
>>>
>>>
>>> --
&g

Re: Why is a username required for a User?

2013-04-09 Thread Cody Scott
Okay Anderson you were right I didn't need those methods. All I needed was 
user.is_superuser = True
after
user.is_admin = True

Thanks again for the code!

On Tuesday, 9 April 2013 11:56:00 UTC-4, Anderson Borges wrote:
>
> No . inside has_perm before check  whether you have permission or not is 
> going to check if you are active and superuser.
>
> # Active superusers have all permissions.
> if self.is_active and self.is_superuser:
> return True
>
>
> On Tue, Apr 9, 2013 at 9:46 AM, Cody Scott 
> > wrote:
>
>> If I don't have them and I log in to admin I get
>> "You don't have permission to edit anything."
>>
>>
>> On Tue, Apr 9, 2013 at 11:28 AM, Anderson 
>> > wrote:
>>
>>> You don't have to worry about permissions all these methods come with 
>>> PermissionsMixin and is_superuser too.
>>>
>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#auth-custom-user
>>>
>>> Do not override those methods otherwise all users will return always 
>>> true.
>>>
>>>
>>> On Tue, Apr 9, 2013 at 9:22 AM, Cody Scott 
>>> 
>>> > wrote:
>>>
>>>> In the docs 
>>>> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-django-contrib-admin
>>>>
>>>> It says to use with admin you need the following methods 
>>>> is_active, has_perm, has_module_perms
>>>>
>>>> So I added them but I don't really understand how to do permissions
>>>>
>>>> Here is the code I put in Users
>>>>
>>>> def __unicode__(self):
>>>> return self.email
>>>>
>>>> @property
>>>> def is_staff(self):
>>>> return self.is_admin
>>>>
>>>> #start of new code
>>>> def is_active(self):
>>>> return self.is_active
>>>>
>>>> def has_perm(self, perm, obj=None):
>>>> return True
>>>>
>>>> def has_module_perms(self, app_label):
>>>> return True
>>>>
>>>>
>>>> On Tue, Apr 9, 2013 at 11:05 AM, Cody Scott 
>>>> 
>>>> > wrote:
>>>>
>>>>> In models.py in /django/contrib/auth there is a 
>>>>>
>>>>> u.is_superuser = True
>>>>>
>>>>> but when I add it just like how is_staff and is_active are added I get 
>>>>> the error 
>>>>>
>>>>> "FieldError: Local field 'is_superuser' in class 'Users' clashes with 
>>>>> field of similar name from base class 'PermissionsMixin'
>>>>> "
>>>>>
>>>>> On Monday, 8 April 2013 11:09:29 UTC-4, Cody Scott wrote:
>>>>>>
>>>>>> To create a User object you need to have a unique username.
>>>>>>
>>>>>> I would like to use an email and a password to identify users, since 
>>>>>> an email is already required for my site's functionality.
>>>>>>
>>>>>> It seems silly for a framework so restrict you.
>>>>>>
>>>>>>
>>>>>>  -- 
>>>>> 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/zAMBjf6WmFU/unsubscribe?hl=en
>>>>> .
>>>>> To unsubscribe from this group and all its topics, 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...@googlegroups.com .
>>>>
>>>> To post to this group, send email to 
>>>> django...@googlegro

Can't get Save method to work

2013-04-09 Thread Cody Scott
I have a Question Model with a ForeignKey field (answer) and a 
ManyToManyField (choices) that link to the same model (Choice).

When I create a question I create a new Choice object for the answer field 
but that option does not show up for the choices field.

I don't want to have to cancel the creation of a Question so that I can 
select the same Choice object for both answer and choices.

So I either need the choices field to have the Choice option created form 
the answer field or I need to make sure that the answer Choice is an option 
in the choices field.

#models.pyclass Choice(models.Model):
choice = models.CharField(max_length=64)
def __unicode__(self):
return self.choice
#multiple choice questionclass Question(models.Model):
question = models.CharField(max_length=64)
answer = models.ForeignKey('Choice', related_name='is_answer_for')
choices = models.ManyToManyField(Choice, related_name='questions', 
verbose_name='other choices')
module = models.ForeignKey('Module', related_name='questions')

times_correct = models.IntegerField(editable=False, default=0)
times_total = models.IntegerField(editable=False, default=0)

def _get_average(self):
"Returns the average in percent"
if self.times_total != 0:
return (self.times_correct / float(self.times_total))*100
return 0.0
average = property(_get_average)

def save(self, *args, **kwargs):
super(Question, self).save(*args, **kwargs)
#make sure that the answer is also in choices
if self.answer not in self.choices.all():
self.choices.add(self.answer)
super(Question, self).save(*args, **kwargs)

def __unicode__(self):
return self.question
#The code should work>>> from quiz.models import *>>> q = 
Question.objects.get(id=1)

#I created q with the above model and as you can see it doesn't work>>> print 
q.answer not in q.choices.all()True>>> q.choices.add(q.answer)>>> print 
q.answer not in q.choices.all()False


I added the save above because it complained that the question field needed to 
have a value, which I don't really understand because it is a CharField

"needs to have a value for field "question" before this many-to-many 
relationship can be used."

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




How to use a list in a django model

2013-04-10 Thread Cody Scott
I am trying to store questions in a database.
I don't to set a fixed number of options for the question, some questions 
could have 4 or 2 or 5.

Currently I am using a ManyToManyField to a table that just contains a 
CharField.
This works but creating an option requires making another Choice object and 
selecting that, also when you want to select a Choice that has already been 
created you have to use that little box in the admin and it doesn't scale 
when you have hundreds of options.

Even if I wanted to have 4 options every time what is the recommended way 
without having four CharFields?

class Choice(models.Model):
choice = models.CharField(max_length=255)
def __unicode__(self):
return self.choice
 #multiple choice questionclass Question(models.Model):
question = models.CharField(max_length=64)
answer = models.CharField(max_length=255)
choices = models.ManyToManyField(Choice, related_name='questions', 
verbose_name='options')
module = models.ForeignKey('Module', related_name='questions')
 
times_correct = models.IntegerField(editable=False, default=0)
times_total = models.IntegerField(editable=False, default=0)
 
def _get_average(self):
"Returns the average in percent"
if self.times_total != 0:
return (self.times_correct / float(self.times_total))*100
return 0.0
average = property(_get_average)
 
def __unicode__(self):
return self.question

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




Re: How to use a list in a django model

2013-04-10 Thread Cody Scott
I like the is_correct and the count attributes!

The problem with that it is hard to make a quiz in the admin section. You 
create a quiz and a question but then you have to go to the choice section 
and create choices for the question. And even if you have the same choice 
in two questions you need to create the choice multiple times.

It would be nice to have text fields and be able to say add a 5th choice, 
and just enter text. It seems easier than changing forms and selecting an 
option from a large list, or even in your case creating each choice for a 
quiz.

Is there a way to have the admin link from Question to Choice in this 
configuration?

On Wednesday, 10 April 2013 14:43:54 UTC-4, BFSchott wrote:
>
> Is a many-to-many what you really want?  How common are the choices and 
> suppose someone goes in an edits one of the choices and suddenly it doesn't 
> match up right with a different linked question.  It might make sense to 
> use a reverse foreign key one-to-many relationship and provide a mechanism 
> to duplicate a question, including its member choices.  That way you could 
> add some statistics on each choice unique to a question.
>
> Several possible paths depending on how you want to go.
>
> 1.  You could just use a reverse foreign key and have a one-to-many 
> relationship.
>
> class Choice(models.Model):
> question = models.ForeignKey('Question', related_name='choices')
> choice = models.CharField(max_length=255)
> index = models.IntegerField(default=0)  # in case you want order_by 
> filtering
> count = models.IntegerField(default=0) # in case you want to count number 
> of times this is selected right or wrong
> is_correct = models.BooleanField(default=False) # boolean flag replaces 
> "answer"
>
> class Question(models.Model):
>   question = models.CharField(max_length=64)
>   module = 
>  
> def times_correct(self):
> return self.choices.objects.filter(is_correct=True).aggregate(Sum('count'))
>
> def times_total(self):
> return self.choices.objects.aggregate(Sum('count'))
>
>
> Then in the admin, you create a table inline admin and just add unique 
> entries.
>
>
> 2. Encode the thing as a JSON list and store in a JSONField
> https://github.com/derek-schaefer/django-json-field
>
> 3. There are several flavors of ListField out there:
> http://djangosnippets.org/snippets/1491/
>
>
>
> Brian Schott
> bfsc...@gmail.com 
>
>
>  
> On Apr 10, 2013, at 1:38 PM, Cody Scott > 
> wrote:
>
> I am trying to store questions in a database.
> I don't to set a fixed number of options for the question, some questions 
> could have 4 or 2 or 5.
>
> Currently I am using a ManyToManyField to a table that just contains a 
> CharField.
> This works but creating an option requires making another Choice object 
> and selecting that, also when you want to select a Choice that has already 
> been created you have to use that little box in the admin and it doesn't 
> scale when you have hundreds of options.
>
> Even if I wanted to have 4 options every time what is the recommended way 
> without having four CharFields?
>
> class Choice(models.Model):
> choice = models.CharField(max_length=255)
> def __unicode__(self):
> return self.choice
>  #multiple choice questionclass Question(models.Model):
> question = models.CharField(max_length=64)
> answer = models.CharField(max_length=255)
> choices = models.ManyToManyField(Choice, related_name='questions', 
> verbose_name='options')
> module = models.ForeignKey('Module', related_name='questions')
>  
> times_correct = models.IntegerField(editable=False, default=0)
> times_total = models.IntegerField(editable=False, default=0)
>  
> def _get_average(self):
> "Returns the average in percent"
> if self.times_total != 0:
> return (self.times_correct / float(self.times_total))*100
> return 0.0
> average = property(_get_average)
>  
> def __unicode__(self):
> return self.question
>
>
> -- 
> 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: How to use a list in a django model

2013-04-10 Thread Cody Scott
Perfect Answer! I must have been sleeping when I did that part of the 
tutorial. Now I understand it and even learned about actions and this is 
what my duplicate action looks like

def duplicate_questions(modeladmin, request, queryset):
for obj in queryset:
new_question = Question(question=obj.question, module=obj.module)
new_question.save()
for choice in obj.choices.all():
new_choice = Choice(question=new_question, 
choice=choice.choice, order=choice.order, is_correct=choice.is_correct)
new_choice.save()
duplicate_questions.short_description = "Duplicate Selected Questions"


On Wednesday, 10 April 2013 15:15:04 UTC-4, BFSchott wrote:
>
> You can create and edit choices right in the Question admin view.  You can 
> even control how many blank slots to show by default.  Go look at 
> ChoiceInline admin here in the tutorial:
> https://docs.djangoproject.com/en/dev/intro/tutorial02/
>
> The next step would be to create an admin action on Question to duplicate 
> the question and its choices.
> https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/
>
> That way, your workflow is duplicate a question, edit on a single page, 
> hit save.
>
> Brian Schott
> bfsc...@gmail.com 
>
>
>  
> On Apr 10, 2013, at 3:02 PM, Cody Scott > 
> wrote:
>
> I like the is_correct and the count attributes!
>
> The problem with that it is hard to make a quiz in the admin section. You 
> create a quiz and a question but then you have to go to the choice section 
> and create choices for the question. And even if you have the same choice 
> in two questions you need to create the choice multiple times.
>
> It would be nice to have text fields and be able to say add a 5th choice, 
> and just enter text. It seems easier than changing forms and selecting an 
> option from a large list, or even in your case creating each choice for a 
> quiz.
>
> Is there a way to have the admin link from Question to Choice in this 
> configuration?
>
> On Wednesday, 10 April 2013 14:43:54 UTC-4, BFSchott wrote:
>>
>> Is a many-to-many what you really want?  How common are the choices and 
>> suppose someone goes in an edits one of the choices and suddenly it doesn't 
>> match up right with a different linked question.  It might make sense to 
>> use a reverse foreign key one-to-many relationship and provide a mechanism 
>> to duplicate a question, including its member choices.  That way you could 
>> add some statistics on each choice unique to a question.
>>
>> Several possible paths depending on how you want to go.
>>
>> 1.  You could just use a reverse foreign key and have a one-to-many 
>> relationship.
>>
>> class Choice(models.Model):
>> question = models.ForeignKey('Question', related_name='choices')
>> choice = models.CharField(max_length=255)
>> index = models.IntegerField(default=0)  # in case you want order_by 
>> filtering
>> count = models.IntegerField(default=0) # in case you want to count number 
>> of times this is selected right or wrong
>> is_correct = models.BooleanField(default=False) # boolean flag replaces 
>> "answer"
>>
>> class Question(models.Model):
>>   question = models.CharField(max_length=64)
>>   module = 
>>  
>> def times_correct(self):
>> return 
>> self.choices.objects.filter(is_correct=True).aggregate(Sum('count'))
>>
>> def times_total(self):
>> return self.choices.objects.aggregate(Sum('count'))
>>
>>
>> Then in the admin, you create a table inline admin and just add unique 
>> entries.
>>
>>
>> 2. Encode the thing as a JSON list and store in a JSONField
>> https://github.com/derek-schaefer/django-json-field
>>
>> 3. There are several flavors of ListField out there:
>> http://djangosnippets.org/snippets/1491/
>>
>>
>>
>> Brian Schott
>> bfsc...@gmail.com
>>
>>
>>  
>> On Apr 10, 2013, at 1:38 PM, Cody Scott  wrote:
>>
>> I am trying to store questions in a database.
>> I don't to set a fixed number of options for the question, some questions 
>> could have 4 or 2 or 5.
>>
>> Currently I am using a ManyToManyField to a table that just contains a 
>> CharField.
>> This works but creating an option requires making another Choice object 
>> and selecting that, also when you want to select a Choice that has already 
>> been created you have to use that little box in the admin and it doesn't 
>> scale when you have hundreds of options.
>>
>> Even if I wanted to hav

Re: How to use a list in a django model

2013-04-10 Thread Cody Scott
I also want to have the same question in multiple quizzes. But the count 
for each option should be dependent on the Quiz. I can do the same thing to 
Quiz in the admin and add Questions Inline but then to add Choices to the 
Questions I need to go to the question panel and there will be a lot of 
duplicate questions and it will hard to tell which question is for which 
quiz.

I'm not even adding the Choices to the admin because there will be so many 
duplicates, but I can't not add Question to the admin because I still need 
to set choices.

Is there a way to Inline 2 steps? So that I can set Choices for a Question 
when I am making a Quiz?

On Wednesday, 10 April 2013 13:38:14 UTC-4, Cody Scott wrote:
>
> I am trying to store questions in a database.
> I don't to set a fixed number of options for the question, some questions 
> could have 4 or 2 or 5.
>
> Currently I am using a ManyToManyField to a table that just contains a 
> CharField.
> This works but creating an option requires making another Choice object 
> and selecting that, also when you want to select a Choice that has already 
> been created you have to use that little box in the admin and it doesn't 
> scale when you have hundreds of options.
>
> Even if I wanted to have 4 options every time what is the recommended way 
> without having four CharFields?
>
> class Choice(models.Model):
> choice = models.CharField(max_length=255)
> def __unicode__(self):
> return self.choice
>  #multiple choice questionclass Question(models.Model):
> question = models.CharField(max_length=64)
> answer = models.CharField(max_length=255)
> choices = models.ManyToManyField(Choice, related_name='questions', 
> verbose_name='options')
> module = models.ForeignKey('Module', related_name='questions')
>  
> times_correct = models.IntegerField(editable=False, default=0)
> times_total = models.IntegerField(editable=False, default=0)
>  
> def _get_average(self):
> "Returns the average in percent"
> if self.times_total != 0:
> return (self.times_correct / float(self.times_total))*100
> return 0.0
> average = property(_get_average)
>  
> def __unicode__(self):
> return self.question
>
>

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




Re: How to use a list in a django model

2013-04-10 Thread Cody Scott


Also if a Question changes and it is used in multiple quizzes all question 
instances will also need to change.

I think I am missing something. Here is my models.py


class Product(models.Model):
name = models.CharField(max_length=256, unique=True)

def __unicode__(self):
return self.name
class Topic(models.Model):
name = models.CharField(max_length=256)
product = models.ForeignKey('Product', related_name='topics')

class Meta:
unique_together = ("name", "product")

def __unicode__(self):
return self.name
class Module(models.Model):
name = models.CharField(max_length=256, unique=True)
threshold = models.IntegerField()
topic = models.ForeignKey('Topic', related_name='modules')

def __unicode__(self):
return self.name
class Choice(models.Model):
question = models.ForeignKey('Question', related_name='choices')
choice = models.CharField(max_length=255)
order = models.IntegerField(default=0)
count = models.IntegerField(default=0, editable=False)
is_correct = models.BooleanField(default=False)

def __unicode__(self):
return self.choice
#multiple choice questionclass Question(models.Model):
quiz = models.ForeignKey('Quiz', related_name='questions')
question = models.CharField(max_length=64)

module = models.ForeignKey('Module', related_name='questions')

times_correct = models.IntegerField(editable=False, default=0)
times_total = models.IntegerField(editable=False, default=0)

def _get_average(self):
"Returns the average in percent"
if self.times_total != 0:
return (self.times_correct / float(self.times_total))*100
return 0.0
average = property(_get_average)

def __unicode__(self):
return self.question
class Quiz(models.Model):
#id = models.UUIDField(primary_key=True)
name = models.CharField(max_length=64)
#questions = models.ManyToManyField(Question)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, 
related_name="quizzes")

#questions = models.ManyToManyField(QuestionManager, null=True, 
related_name="quiz")

class Meta:
verbose_name_plural = "quizzes"

def __unicode__(self):
return self.name


On Wednesday, 10 April 2013 16:30:20 UTC-4, Cody Scott wrote:
>
> I also want to have the same question in multiple quizzes. But the count 
> for each option should be dependent on the Quiz. I can do the same thing to 
> Quiz in the admin and add Questions Inline but then to add Choices to the 
> Questions I need to go to the question panel and there will be a lot of 
> duplicate questions and it will hard to tell which question is for which 
> quiz.
>
> I'm not even adding the Choices to the admin because there will be so many 
> duplicates, but I can't not add Question to the admin because I still need 
> to set choices.
>
> Is there a way to Inline 2 steps? So that I can set Choices for a Question 
> when I am making a Quiz?
>
> On Wednesday, 10 April 2013 13:38:14 UTC-4, Cody Scott wrote:
>>
>> I am trying to store questions in a database.
>> I don't to set a fixed number of options for the question, some questions 
>> could have 4 or 2 or 5.
>>
>> Currently I am using a ManyToManyField to a table that just contains a 
>> CharField.
>> This works but creating an option requires making another Choice object 
>> and selecting that, also when you want to select a Choice that has already 
>> been created you have to use that little box in the admin and it doesn't 
>> scale when you have hundreds of options.
>>
>> Even if I wanted to have 4 options every time what is the recommended way 
>> without having four CharFields?
>>
>> class Choice(models.Model):
>> choice = models.CharField(max_length=255)
>> def __unicode__(self):
>> return self.choice
>>  #multiple choice questionclass Question(models.Model):
>> question = models.CharField(max_length=64)
>> answer = models.CharField(max_length=255)
>> choices = models.ManyToManyField(Choice, related_name='questions', 
>> verbose_name='options')
>> module = models.ForeignKey('Module', related_name='questions')
>>  
>> times_correct = models.IntegerField(editable=False, default=0)
>> times_total = models.IntegerField(editable=False, default=0)
>>  
>> def _get_average(self):
>> "Returns the average in percent"
>> if self.times_total != 0:
>> return (self.times_correct / float(self.times_total))*100
>&g

How to clear all session variables without getting logged out?

2013-04-16 Thread Cody Scott
I am trying to clear all of the session variables but not logout the 
current user.

user = request.session.get('member_id', None)
request.session.flush()
request.session.modified = True
request.session['member_id'] = user
request.session.modified = True


Will this also affect other users of the site?

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




How to translate database content?

2013-04-16 Thread Cody Scott
I want the end user of the site to be able to view the site in different 
languages.

I have marked the static text in my templates for translation. I have not 
marked the verbose_names because they are used in the admin which the end 
user will not have access to.

But I just realized that the actually content in the database needs to be 
translated. If it was a blog site the blog posts which are stored in the 
database would also need to be translated.

How do I mark them for translation?

How can I see the site in a different language. In the tutorial is says you 
can see the admin section in a different language how do I do that?

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




How to view your translated site?

2013-04-18 Thread Cody Scott
I am trying to view my site in japanese. I have create the translations and 
compiled them with compilemessages.

In my urls.py I have 

urlpatterns = i18n_patterns('',
#...)


Settings.py


LANGUAGE_CODE = 'en-us'
#Used for translationsgettext = lambda s: sLANGUAGES = (
('en', gettext('English')),
('jp', gettext('Japanese')),)


But when I try to access a url with /jp/ at the start I get that there is only 
/en/


Using the URLconf defined in PLP.urls, Django tried these URL patterns, in this 
order:^en/The current URL, jp/accounts/login, didn't match any of these.

 

I am using dbgettext so I also have my database content translated in my 
messages.

But how can I display it

{% trans "Question:" %}{% trans {{question.question}} %}

Could not parse the remainder: '{{question.question}}' from 
'{{question.question}}'


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




Re: How to view your translated site?

2013-04-18 Thread Cody Scott
Thanks, I went here http://www.i18nguy.com/unicode/language-identifiers.html 
ctrl+ 
f "japanese" saw jp on the left hand side. I thought ja was a localization 
of jp so it would be jp-ja.

On Thursday, 18 April 2013 11:42:37 UTC-4, Cody Scott wrote:
>
> I am trying to view my site in japanese. I have create the translations 
> and compiled them with compilemessages.
>
> In my urls.py I have 
>
> urlpatterns = i18n_patterns('',
> #...)
>
>
> Settings.py
>
>
> LANGUAGE_CODE = 'en-us'
> #Used for translationsgettext = lambda s: sLANGUAGES = (
> ('en', gettext('English')),
> ('jp', gettext('Japanese')),)
>
>
> But when I try to access a url with /jp/ at the start I get that there is 
> only /en/
>
>
> Using the URLconf defined in PLP.urls, Django tried these URL patterns, in 
> this order:^en/The current URL, jp/accounts/login, didn't match any of these.
>
>  
>
> I am using dbgettext so I also have my database content translated in my 
> messages.
>
> But how can I display it
>
> {% trans "Question:" %}{% trans {{question.question}} %}
>
> Could not parse the remainder: '{{question.question}}' from 
> '{{question.question}}'
>
>
>

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




Re: How to view your translated site?

2013-04-18 Thread Cody Scott
I agree that link is much better, I got the other one from settings.py


On Thu, Apr 18, 2013 at 12:41 PM, Tom Evans wrote:

> On Thu, Apr 18, 2013 at 5:23 PM, Cody Scott 
> wrote:
> > Thanks, I went here
> http://www.i18nguy.com/unicode/language-identifiers.html
> > ctrl+ f "japanese" saw jp on the left hand side. I thought ja was a
> > localization of jp so it would be jp-ja.
> >
>
> The columns listed on that page are "region code", "region name",
> "language". You can't use region code for language, eg the region code
> 'ca' represents 'Canada', but the language code 'ca' represents
> Catalan. It's important to use the right one.
>
> If you're looking for the right ISO-639-1 language code to use, the
> best reference is a list of ISO-639-1 codes:
>
> http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
>
> Cheers
>
> Tom
>
> --
> 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/pCJlPwvkirQ/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.




Random translation text showing up while the rest is not translated.

2013-04-18 Thread Cody Scott


I have marked text for translation, and also database content with the 
dbgettext mdoule.

So I do:

syncdb
add some content
dbgettext_export
makemessages -l ja
add all of the translations
compilemessages

Then I change the /en/ to /ja/ to see the page in Japanese, but only two 
things are translated.

'Yes' and 'No'.

Except the displayed 'No' is not even the translation text for 'No'

Nothing else on the page is getting translated.

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




How to add Django project to sys.path?

2013-04-19 Thread Cody Scott
I am trying to use apache to serve my development site locally.

I am trying to implement download functionality and figured since it was 
best done through a web server that I would just serve the with apache from 
now on.

Is this recommended to start using your django site with a web server early?

Anyways I installed mod_wsgi and it seemed to work.

I am just trying to use http://localhost

but when I go there I get the error 

[Fri Apr 19 13:29:35 2013] [error] [client 127.0.0.1] ImportError: Could 
not import settings 'PLP.settings' (Is it on sys.path?): No module named 
PLP.settings


I am linking to wsgi.py which contains.

import os

os.environ["DJANGO_SETTINGS_MODULE"] = "PLP.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PLP.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

I tried:

>>> import sys
>>> sys,path.append(PATH_TO_DJANGO_PROJECT)

but if I close the interpreter and open it again, it is not in sys.path 
anymore.

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




Re: How to add Django project to sys.path?

2013-04-19 Thread Cody Scott
I followed getting started with djano's settings suggestions.

This is what I currently have

# here() gives us file paths from the root of the system to the directory
# holding the current file.
here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), 
*x)
PROJECT_ROOT = here("..")
# root() gives us file paths from the root of the system to whatever
# folder(s) we pass it starting at the parent directory of the current file.
root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x)
XML_PATH = root("..", "XML")

It doesn't look like you are modifying sys.path though

On Friday, 19 April 2013 14:18:29 UTC-4, Felipe wrote:
>
> You can try to use that! that's works for me!
>
> import os
>
> # Make filepaths relative to settings.
> ROOT = os.path.dirname(os.path.abspath(__file__))
> path = lambda *a: os.path.join(ROOT, *a)
>
> STATIC_ROOT = path('static')
>
> MEDIA_ROOT = path('media')
>
>  ---
>Felipe Brunelli de Andrade
> Universidade de São Paulo
> Bacharelado em Informática - 08
> http://www.fandrade.com.br/
> ---
> Cel: (16) 8121-5290 / 9718-3939
> Tel: (16) 3371-7274
> Skype: fbruandrade
> MSN: felipean...@hotmail.com 
> ICQ: 15909761
> ---
>
>  
>
> 2013/4/19 Cody Scott >
>
>> I am trying to use apache to serve my development site locally.
>>
>> I am trying to implement download functionality and figured since it was 
>> best done through a web server that I would just serve the with apache from 
>> now on.
>>
>> Is this recommended to start using your django site with a web server 
>> early?
>>
>> Anyways I installed mod_wsgi and it seemed to work.
>>
>> I am just trying to use http://localhost
>>
>> but when I go there I get the error 
>>
>> [Fri Apr 19 13:29:35 2013] [error] [client 127.0.0.1] ImportError: Could 
>> not import settings 'PLP.settings' (Is it on sys.path?): No module named 
>> PLP.settings
>>
>>
>> I am linking to wsgi.py which contains.
>>
>> import os
>>
>> os.environ["DJANGO_SETTINGS_MODULE"] = "PLP.settings"
>> os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PLP.settings")
>>
>> from django.core.wsgi import get_wsgi_application
>> application = get_wsgi_application()
>>
>> I tried:
>>
>> >>> import sys
>> >>> sys,path.append(PATH_TO_DJANGO_PROJECT)
>>
>> but if I close the interpreter and open it again, it is not in sys.path 
>> anymore.
>>  
>> -- 
>> 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: How to translate database content?

2013-04-19 Thread Cody Scott
I installed dbgettext and it allows you to mark model fields and then
export them with dbgettext_export. Then when you run django-admin.py
makemessages it includes the content in the .po file.

Then you use django-admin.py compilemessages like normal.

The only problem I am having is that only three words are being translated.

Home (which was not from the database), Yes and No.

Also I keep getting switched to the english version of the site with the
url having /en/ in the beginning while I set it to /ja/


On Fri, Apr 19, 2013 at 5:02 PM, Daniel Krol  wrote:

> Oh, just to be clear, the hack involves putting the content into the
> template, and marking it for translation.
>
>
> On Friday, April 19, 2013 1:57:44 PM UTC-7, Daniel Krol wrote:
>>
>> There isn't anything built into Django to translate the content of
>> models. This is because the GNU gettext system that Django uses for
>> translation stores the original->translation mappings in a "compiled" file
>> which only changes between restarts of the server. That means anything you
>> dynamically create in the database cannot be translated with this system,
>> at least without a sort of a hack.
>>
>> And the hack is this: If you have access to the data from the live
>> database from your development environment, you could theoretically dump it
>> (the actual full text verbatim, not just a variable containing the
>> content), to a dummy template file. Then, makemessages will pick up that
>> text and put it into the translation files. *then* you can translate it,
>> and say {% trans model_instance.field %}. Where I work, we've done this for
>> very small pieces of data (category names, of which there are less than
>> 10). It's manageable at this point. But with full blog posts, unless you
>> automate some sort of system, it's probably way too big a hack to be worth
>> it. (You'd have to make sure your spacing was 100% correct, too.)
>>
>> No, what I recommend is to create a model in the database that serves as
>> the translated version of all the specific models whose content you want to
>> translate. For instance, you want BlogPostTranslation, with an FK to
>> BlogPost, and also a locale. Then in your view, you select the appropriate
>> translation to show based on the locale in the request
>> (request.LANGUAGE_CODE).
>>
>> Since this is somewhat of a common concern, there are libraries out there
>> that facilitate this. I won't list them because I have no recommendations
>> on the matter (I have not tried any personally), your own Google search
>> will be as good as mine. But look for things along the line of "django
>> model translation".
>>
>> Hope this helps.
>>
>> On Tuesday, April 16, 2013 9:15:40 AM UTC-7, Cody Scott wrote:
>>>
>>> I want the end user of the site to be able to view the site in different
>>> languages.
>>>
>>> I have marked the static text in my templates for translation. I have
>>> not marked the verbose_names because they are used in the admin which the
>>> end user will not have access to.
>>>
>>> But I just realized that the actually content in the database needs to
>>> be translated. If it was a blog site the blog posts which are stored in the
>>> database would also need to be translated.
>>>
>>> How do I mark them for translation?
>>>
>>> How can I see the site in a different language. In the tutorial is says
>>> you can see the admin section in a different language how do I do that?
>>>
>>>  --
> 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/upzy6ohwlKc/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.




How to switch languages?

2013-04-22 Thread Cody Scott
I am trying to get translations to work on my site.

I have marked words for translation and they show up in the django.po file.

I am wondering what is the proper way to switch the current language.

Currently I have the following in my project urls.py

urlpatterns = i18n_patterns('',
# etc
)

urlpatterns += patterns('', 
(r'^i18n/', include('django.conf.urls.i18n')),
)

And to switch languages I change the /en/ in my url to /ja/ or /fr/.

I have two issues. 

1) The page is not being translated except for 'Yes' and 'No' which are 
translated even if I remove them from my .po file. So there must be a 
default set of translation words? Or Chrome is seeing the /fr/ in the URL 
and translating it for me? I can't explain why that is happening. Even if I 
change what 'Yes' and 'No' translate to it doesn't change what is displayed.

2) The next page I visit reverts to a English with the /en/. Yes english is 
my default language in settings.py.

#settings.py
#Used for translations
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('fr', gettext('French')),
('ja', gettext('Japanese')),
)


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




Re: How to switch languages?

2013-04-22 Thread Cody Scott
How do you get the preferred language?

In the 1.5 docs it says to add 'django.core.context_processors.i18n' to 
your TEMPLATE_CONTEXT_PROCESSORS which variable is that in your settings.py?

If I add it to TEMPLATE_LOADERS and refresh the page I get the error:

'function' object has no attribute 'is_usable'

/usr/local/lib/python2.7/dist-packages/django/template/loader.py in 
find_template_loader, line 112



On Monday, 22 April 2013 11:36:34 UTC-4, ayeowch wrote:
>
> There are several ways to switch language (
> https://docs.djangoproject.com/en/1.4/topics/i18n/translation/#how-django-discovers-language-preference).
>  
> I normally set django_language session variable to the preferred language.
> For 1), have you compiled your messages into .mo files? You will also need 
> to reload your server to load the new .mo files.
>
>
> On Tue, Apr 23, 2013 at 1:24 AM, Cody Scott 
> > wrote:
>
>> I am trying to get translations to work on my site.
>>
>> I have marked words for translation and they show up in the django.po 
>> file.
>>
>> I am wondering what is the proper way to switch the current language.
>>
>> Currently I have the following in my project urls.py
>>
>> urlpatterns = i18n_patterns('',
>> # etc
>> )
>>
>> urlpatterns += patterns('', 
>> (r'^i18n/', include('django.conf.urls.i18n')),
>> )
>>
>> And to switch languages I change the /en/ in my url to /ja/ or /fr/.
>>
>> I have two issues. 
>>
>> 1) The page is not being translated except for 'Yes' and 'No' which are 
>> translated even if I remove them from my .po file. So there must be a 
>> default set of translation words? Or Chrome is seeing the /fr/ in the URL 
>> and translating it for me? I can't explain why that is happening. Even if I 
>> change what 'Yes' and 'No' translate to it doesn't change what is displayed.
>>
>> 2) The next page I visit reverts to a English with the /en/. Yes english 
>> is my default language in settings.py.
>>
>> #settings.py
>> #Used for translations
>> gettext = lambda s: s
>> LANGUAGES = (
>> ('en', gettext('English')),
>> ('fr', gettext('French')),
>> ('ja', gettext('Japanese')),
>> )
>>
>>
>>  -- 
>> 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: How to switch languages?

2013-04-22 Thread Cody Scott
I installed django-localeurl and disabled 

'django.middleware.locale.LocaleMiddleware',


and

i18n_patterns


but it had the same issue of only translating 'Yes' and 'No' and it 
reverted back to /en/ on every new page load.



On Monday, 22 April 2013 12:08:34 UTC-4, אברהם סרור wrote:
>
> I suggest taking a look at 
> django-localeurl<https://bitbucket.org/carljm/django-localeurl>, 
> I used it instead of a form to change language on my last project. I 
> believe it is worth taking a look
>
>
> On Mon, Apr 22, 2013 at 6:58 PM, Cody Scott 
> > wrote:
>
>> How do you get the preferred language?
>>
>> In the 1.5 docs it says to add 'django.core.context_processors.i18n' to 
>> your TEMPLATE_CONTEXT_PROCESSORS which variable is that in your settings.py?
>>
>> If I add it to TEMPLATE_LOADERS and refresh the page I get the error:
>>
>> 'function' object has no attribute 'is_usable'
>>
>> /usr/local/lib/python2.7/dist-packages/django/template/loader.py in 
>> find_template_loader, line 112
>>
>>
>>
>> On Monday, 22 April 2013 11:36:34 UTC-4, ayeowch wrote:
>>
>>> There are several ways to switch language (https://docs.djangoproject.**
>>> com/en/1.4/topics/i18n/**translation/#how-django-**
>>> discovers-language-preference<https://docs.djangoproject.com/en/1.4/topics/i18n/translation/#how-django-discovers-language-preference>
>>> )**. I normally set django_language session variable to the preferred 
>>> language.
>>> For 1), have you compiled your messages into .mo files? You will also 
>>> need to reload your server to load the new .mo files.
>>>
>>>
>>> On Tue, Apr 23, 2013 at 1:24 AM, Cody Scott wrote:
>>>
>>>> I am trying to get translations to work on my site.
>>>>
>>>> I have marked words for translation and they show up in the django.po 
>>>> file.
>>>>
>>>> I am wondering what is the proper way to switch the current language.
>>>>
>>>> Currently I have the following in my project urls.py
>>>>
>>>> urlpatterns = i18n_patterns('',
>>>> # etc
>>>> )
>>>>
>>>> urlpatterns += patterns('', 
>>>> (r'^i18n/', include('django.conf.urls.**i18n')),
>>>> )
>>>>
>>>>  And to switch languages I change the /en/ in my url to /ja/ or /fr/.
>>>>
>>>> I have two issues. 
>>>>
>>>> 1) The page is not being translated except for 'Yes' and 'No' which are 
>>>> translated even if I remove them from my .po file. So there must be a 
>>>> default set of translation words? Or Chrome is seeing the /fr/ in the URL 
>>>> and translating it for me? I can't explain why that is happening. Even if 
>>>> I 
>>>> change what 'Yes' and 'No' translate to it doesn't change what is 
>>>> displayed.
>>>>
>>>> 2) The next page I visit reverts to a English with the /en/. Yes 
>>>> english is my default language in settings.py.
>>>>
>>>> #settings.py
>>>> #Used for translations
>>>> gettext = lambda s: s
>>>> LANGUAGES = (
>>>> ('en', gettext('English')),
>>>> ('fr', gettext('French')),
>>>> ('ja', gettext('Japanese')),
>>>> )
>>>>  
>>>>
>>>>  -- 
>>>> 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...@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.




How to create a Dynamic Hierarchical Form

2013-04-22 Thread Cody Scott
I am trying to create a form where you select product(s) and technology(s) 
and based on your selection different modules are available for selection.

forms.py

def make_quiz_form_class():
#Listing available options
products = [(i, _(i)) for i in Product.objects.all()]
technologies= [(i, _(i)) for i in Technology.objects.all()]
modules = [(i, _(i)) for i in 
Module.objects.filter(product=selected_products, 
technologies=selected_technologies)]

class _QuizForm(forms.Form):
selected_products = forms.ChoiceField(choices = products, 
widget=forms.RadioSelect())
selected_technologies = forms.ChoiceField(choices = technologies, 
widget=forms.RadioSelect())
selected_modules = forms.ChoiceField(choices = modules, 
widget=forms.RadioSelect())

return _QuizForm

views.py

form_class = make_quiz_form_class()
form = form_class(request.POST)

The problem is selected_products and selected_technologies are not defined 
for modules

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




Customizing Admin

2013-05-07 Thread Cody Scott
Is there a way to put text in the django admin?

I am trying to display information from another model, to help in your 
select of ForeignKeys.

Right now I am adding this information to the __unicode__ function so I can 
see the information but there is not context.

Also is there a way to make a MultipleSelect box larger or re-sizeable?
Is there also a way to make this field searchable?


-- 
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: Customizing Admin

2013-05-09 Thread Cody Scott
I am trying to create a form to select but I don't want to list all of the
options because there are too many.

Is there a way to allow the visitor to search and only have the query show
up in the form?

Even if it is not in the admin.


On Thu, May 9, 2013 at 8:17 AM, Rafael E. Ferrero
wrote:

> I think you can customize the django admin templates for your own purpose
>
>
> 2013/5/7 Cody Scott 
>
>> Is there a way to put text in the django admin?
>>
>> I am trying to display information from another model, to help in your
>> select of ForeignKeys.
>>
>> Right now I am adding this information to the __unicode__ function so I
>> can see the information but there is not context.
>>
>> Also is there a way to make a MultipleSelect box larger or re-sizeable?
>> Is there also a way to make this field searchable?
>>
>>
>>  --
>> 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.
>>
>>
>>
>
>
>
> --
> Rafael E. Ferrero
> Claro: (03562) 15514856
>
> --
> 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/N61oAMvbTXg/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.




django-auth-ldap

2013-05-14 Thread Cody Scott
I am trying to get django-auth-ldap working with an Active Directory LDAP 
Server.

I don't understand the documentation for the Search/Bind or Direct Bind.

Is 'uid' the LDAP attribute uid? My LDAP doesn't use this attribute.

I tried putting 'samaccountName' an attribute that is used for logon. 

Where does the 'user' come from? Is that the username field from the login 
form?

-- 
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: django-auth-ldap

2013-05-14 Thread Cody Scott
Do I need to set up groups? I have a setting for 

AUTH_LDAP_SERVER_URI
AUTH_LDAP_BIND_DN
AUTH_LDAP_BIND_PASSWORD
AUTH_LDAP_USER_SEARCH

AUTH_LDAP_USER_ATTR_MAP = {
"username": "sAMAccountName",
"email": "mail"
}

I am using a custom auth model. Maybe that is the reason it is not working?

from django.db import modelsfrom django.contrib.auth.models import 
AbstractBaseUser, PermissionsMixin, BaseUserManagerfrom django.conf import 
settingsfrom django.utils.translation import ugettext_lazy as _
class MyUserManager(BaseUserManager):
def create_user(self, username, email, name, company, password=None):
if not email:
raise ValueError('User must have an email address')
if not username:
raise ValueError('User must have a username')

user = self.model(
email=MyUserManager.normalize_email(email),
)
user.username = username
user.set_password(password)
user.name = name
user.company = company
user.save(using=self._db)
return user

def create_superuser(self, username, email, name, company, password):
user = self.create_user(username,
email,
name,
company,
password=password
)
user.is_admin = True
user.is_manager = True
user.is_superuser = True
user.save(using=self._db)
return user
class Users(AbstractBaseUser,PermissionsMixin):
email   = models.EmailField(verbose_name=_('email address'), 
max_length=255,unique=True,db_index=True,)
username= models.CharField(verbose_name=_('Username'), 
max_length=50,blank=True,unique=True)
name= models.CharField(verbose_name=_('Name'), 
max_length=50,blank=True)
company = models.CharField(verbose_name=_('Company'), 
max_length=255,blank=True)
is_manager  = models.BooleanField(default=False)
is_active   = models.BooleanField(default=True)
is_admin= models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
datecreated = models.DateField(auto_now=True)

objects = MyUserManager()
USERNAME_FIELD  = 'username'
REQUIRED_FIELDS = ['name', 'company', 'email']

class Meta:
verbose_name_plural = "Users"

def get_full_name(self):
return self.email

def get_short_name(self):
return self.email

def __unicode__(self):
return self.email

def get_attempts_list(self, quiz):
attempts = []
for attempt in self.attempts.all():
if attempt.quiz == quiz:
attempts.append(attempt)
return attempts

@property
def is_staff(self):
return self.is_admin




-- 
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: django-auth-ldap

2013-05-15 Thread Cody Scott
I put that code in a separate python file and ran it without django or 
django-auth-ldap. 

l = ldap.initialize()
AttributeError: 'module' object has no attribute 'initialize'

so python-ldap is not installed properly? 

I am not able to login, no error just invalid credentials. 

How do I get logs from ldap? I don't have a login view I am using django's

On Tuesday, 14 May 2013 17:01:44 UTC-4, Guddu wrote:
>
>
>

-- 
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: django-auth-ldap

2013-05-15 Thread Cody Scott
http://dpaste.org/EboQU/

On Wednesday, 15 May 2013 10:09:01 UTC-4, Guddu wrote:
>
> What does this give you?
>
> import ldap
> dir(ldap)
>
> Regards
> Guddu
>
> On Wed, May 15, 2013 at 10:04 AM, Cody Scott 
> 
> > wrote:
>
>> I put that code in a separate python file and ran it without django or 
>> django-auth-ldap. 
>>
>> l = ldap.initialize()
>> AttributeError: 'module' object has no attribute 'initialize'
>>
>> so python-ldap is not installed properly? 
>>
>> I am not able to login, no error just invalid credentials. 
>>
>> How do I get logs from ldap? I don't have a login view I am using django's
>>
>> On Tuesday, 14 May 2013 17:01:44 UTC-4, Guddu wrote:
>>>
>>>
>>>  -- 
>> 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: django-auth-ldap

2013-05-15 Thread Cody Scott
Ok The problem was that I had the file named ldap.py. I got it to work, I 
had to add a print to 

l.result(result)

put I get 

a tuple of a number and an empty list

(#, [])

-- 
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: django-auth-ldap

2013-05-15 Thread Cody Scott
I have that code but where does the logging go?

On Wednesday, 15 May 2013 11:04:33 UTC-4, Guddu wrote:
>
> Ok. Now try to get django-ldap-auth working. See if you can enable the 
> logging handler and grab some more information.
>
> http://pythonhosted.org/django-auth-ldap/logging.html
>
> Regards
> Guddu
>
> On Wed, May 15, 2013 at 10:56 AM, Cody Scott 
> 
> > wrote:
>
>> Ok The problem was that I had the file named ldap.py. I got it to work, I 
>> had to add a print to 
>>
>> l.result(result)
>>
>> put I get 
>>
>> a tuple of a number and an empty list
>>
>> (#, [])
>>
>>  -- 
>> 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: django-auth-ldap

2013-05-15 Thread Cody Scott
The problem was that the LDAPSearch had to start with a OU= I had it start 
with a DC=.

On Wednesday, 15 May 2013 11:27:08 UTC-4, Cody Scott wrote:
>
> I have that code but where does the logging go?
>
> On Wednesday, 15 May 2013 11:04:33 UTC-4, Guddu wrote:
>>
>> Ok. Now try to get django-ldap-auth working. See if you can enable the 
>> logging handler and grab some more information.
>>
>> http://pythonhosted.org/django-auth-ldap/logging.html
>>
>> Regards
>> Guddu
>>
>> On Wed, May 15, 2013 at 10:56 AM, Cody Scott wrote:
>>
>>> Ok The problem was that I had the file named ldap.py. I got it to work, 
>>> I had to add a print to 
>>>
>>> l.result(result)
>>>
>>> put I get 
>>>
>>> a tuple of a number and an empty list
>>>
>>> (#, [])
>>>
>>>  -- 
>>> 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.




Trees in Django

2013-05-17 Thread Cody Scott
I am categorizing models in a tree. The tree is created based on a string 
of where the model falls in the tree. The tree will not change once it is 
created.

I tried using django-mptt with this code to create the tree.

def add_new_nodes(category_string):
for category in category_string.split(','):
try:
root = Category.get_root()
except:
root = Category.objects.create(value='')
current_node = root
for step in category.split(':'):
added = False
for node in current_node.get_children().all():
print node.value
print step
if node.value == step:
added = True
current_node = node
break
if not added:
new_node = Category.objects.create(value=step, 
parent=current_node)
current_node = new_node


But it each time is creating a new branch from the root even with two children 
of the root with the same name.


Or at least that is what I get from


{% load mptt_tags %}
{% recursetree nodes %}

{{ node.name }}
{% if not node.is_leaf_node %}

{{ children }}

{% endif %}

{% endrecursetree %}



So I am trying to use django-treebeard similarly but I am getting an error. 
'str' object has no attribute 'META'


def tree(request):
try:
root = Category1.get_root_nodes()[0]
except:
root = Category1.add_root(value='')
annotated_list = root.get_annotated_list()
print annotated_list
return render("tree.html", {'annotated_list':annotated_list})


{% for item, info in annotated_list %}
{% if info.open %}

{% else %}

{% endif %}

{{ item }}

{% for close in info.close %}

{% endfor %}{% endfor %}


But I get the error 'str' object has no attribute 'META'



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




How to select a django-treebeard node in a form

2013-05-21 Thread Cody Scott
I have created my tree structure, now I am trying to create a form that 
selects a node which I will use to do some operations.

When I render the form 

class SelectNodeForm(MoveNodeForm):

class Meta:

model = Category


with {{form.as_p}}


I get the fields


Path

Depth

Numchild

Value

Position

Relative to


I would like the form to just contain relative to (but allow multiple 
selection)


Looking at the code here it looks like that field is called 

https://github.com/tabo/django-treebeard/blob/master/treebeard/forms.py


_ref_node_id = forms.TypedChoiceField(required=False,
  coerce=int,
  label=_("Relative to"))

But I cannot render a field that starts with an underscore. "Variables and 
attributes may not begin with underscores: "

So how can I select a django-treebeard node in a form?



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




How to locate django extension templates

2013-05-21 Thread Cody Scott
I am trying to use django-treebeard in the admin.

https://tabo.pe/projects/django-treebeard/docs/tip/intro.html#configuration

It says 

Note
 

If you are going to use the 
Treeadmin
 class, 
you need to add the path to treebeard’s templates in 
TEMPLATE_DIRS.
 
Also you need to 
enabledjango.core.context_processors.request
 in 
the 
TEMPLATE_CONTEXT_PROCESSORSsetting
 
in your django settings file.


How do I find where the templates for django-treebeard are located?



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




Display each language in its own language.

2013-05-23 Thread Cody Scott
 

I would like the language selector to display each language in its own 
language. So for example English will always be displayed as 'English'. 
Even if the current language is French it will still be 'English' and not 
Anglais.


  {% csrf_token %}  {% for 
lang in LANGUAGES %}  {{ lang.1 }}  {% endfor %}
  


I think all language selector forms should be like 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.




Re: Display each language in its own language.

2013-05-24 Thread Cody Scott
In my settings.py I have

#Used for translations

gettext = lambda s: s

#languages written as they would be displayed in the language selector form

LANGUAGES = (

  ('en', gettext('English')),

  ('fr', gettext('French')),

  ('ja', gettext('Japanese')),

)

and I was thinking of writing each language in its own language

LANGUAGES = (

('en', gettext('English')),

('fr', gettext('Français')),

('ja', gettext('日本人')),

)

But I get an error for having a non ascii character in settings.py




On Thu, May 23, 2013 at 3:26 PM, Cody Scott wrote:

> I would like the language selector to display each language in its own
> language. So for example English will always be displayed as 'English'.
> Even if the current language is French it will still be 'English' and not
> Anglais.
>
>
>   {% csrf_token %} onchange="$('#locale_switcher').submit()" class="btn btn-inverse">  {% 
> for lang in LANGUAGES %} selected="selected"  {% endifequal %}>  {{ lang.1 }} 
>  {% endfor %}  
>
>
> I think all language selector forms should be like this.
>
>  --
> 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/mBTgoUNIj30/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: Display each language in its own language.

2013-05-24 Thread Cody Scott
ok I also had to add
# -*- coding: utf-8 -*-
to the top of the file



On Fri, May 24, 2013 at 10:03 AM, Tom Evans wrote:

> On Fri, May 24, 2013 at 2:54 PM, Cody Scott 
> wrote:
> > In my settings.py I have
> >
> > #Used for translations
> >
> > gettext = lambda s: s
> >
> > #languages written as they would be displayed in the language selector
> form
> >
> > LANGUAGES = (
> >
> >   ('en', gettext('English')),
> >
> >   ('fr', gettext('French')),
> >
> >   ('ja', gettext('Japanese')),
> >
> > )
> >
> > and I was thinking of writing each language in its own language
> >
> > LANGUAGES = (
> >
> > ('en', gettext('English')),
> >
> > ('fr', gettext('Français')),
> >
> > ('ja', gettext('日本人')),
> >
> > )
> >
> > But I get an error for having a non ascii character in settings.py
> >
>
> If you don't want language names to be translated into other
> languages, then don't mark them up as translatable strings that will
> have their values retrieved from the active message catalogue. IE:
>
> LANGUAGES = (
>   ('en', u'English'),
>   ('fr', u'Français'),
>   ('ja', u'日本人'),
> )
>
> Cheers
>
> Tom
>
> --
> 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/mBTgoUNIj30/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.




Adding a search to a field.

2013-05-27 Thread Cody Scott
In the admin I have a many-to-many relationship which django supplies a 
default widget that is really small. I am wondering how to make that bigger 
or re-sizeable.

Is it possible to add a search so that I can type in one of the fields and 
it will search by that field and bring those options to the top of the 
field?

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




Allow visitor to add a form to a formset

2013-05-29 Thread Cody Scott
I have a form with one field for emails.

I would like to allow the visitor to add another email field. What do I 
need to do to allow the user to create another form?

#following the 
docshttps://docs.djangoproject.com/en/1.5/topics/forms/formsets/#adding-additional-fields-to-a-formset#I
 don't see an add field button or instructions on how to create it
#forms.pyclass BaseEmailFormSet(BaseFormSet):
def add_fields(self, form, index):
super(BaseEmailFormSet, self).add_fields(form, index)
form.fields["email"] = forms.CharField()

class AddMemberEmailForm(forms.Form):
email = forms.EmailField()
AddMemberEmailFormSet = formset_factory(AddMemberEmailForm,
formset=BaseEmailFormSet)
#views.pyfrom .forms import AddMemberEmailFormSet
email_formset = AddMemberEmailFormSet()
if request.method == 'POST':
  email_formset = AddMemberEmailFormSet(request.POST, request.FILES)
  if email_formset.is_valid():
print "valid!"
# pass 'email_formset': email_formset, to template
#Template{% csrf_token %}
  {{email_formset.management_form}}
  
   {% for form in email_formset %}
 {{form}}
   {%endfor%}
  
  


-- 
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: Allow visitor to add a form to a formset

2013-05-29 Thread Cody Scott
My issue was that I was putting my form_name in the 
cp['form_name-TOTAL_FORMS'] and it is always just form.

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




Using django tags in a blog post

2013-06-28 Thread Cody Scott
I have a simple model that has a TextField used to store a blog post.

body = models.TextField()


I would like to be able to use django tags in the blog post, such as {% url 
'' %} and {% trans "" %}.


I tried using the |safe filter and passing a mark_safe() value but they 
don't convert the django tags to html.



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




How to Test Querysets

2013-06-29 Thread Cody Scott
*I would like to be able to replace the hardcoded repr in the test with an 
actual queryset.*
*
*

def test_index_view_with_a_past_poll(self):
"""Polls with a pub_date in the past should be displayed on the 
index page."""
create_poll(question="Past poll.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
['']
)
#newdef test_index_view_with_a_past_poll(self):
"""Polls with a pub_date in the past should be displayed on the 
index page."""
create_poll(question="Past poll.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_poll_list'],
repr(Poll.objects.filter(question="Past poll."))
)

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




Writing Form Tests

2013-07-03 Thread Cody Scott


I am trying to extend the polls tutorial code to use a django form with tests.


I created this form, but ran into some issues when trying to test it. When 
looking up how to test it, I found this form from 
http://toastdriven.com/blog/2011/apr/17/guide-to-testing-in-django-2/ It also 
had tests.


When I try to run those tests on my form I get the error

"_VoteForm is not callable"

"AttributeError: '_VoteForm' object has no attribute 'instance'"


Which form is preferred? How can I write similar tests for _VoteForm

#my form

def vote_form_class(poll):
choices = [(i.id, _(i.choice_text)) for i in poll.choices.all()]

class _VoteForm(forms.Form):
vote = forms.ChoiceField(choices=choices, widget=forms.RadioSelect())

def save(self):
if not self.is_valid():
raise forms.ValidationError("Poll Form was not validated before 
.save()")

data = self.cleaned_data
choice_id = data['vote']
choice = Choice.objects.get(id=choice_id)
choice.record_vote()

return _VoteForm



#form with tests

class PollForm(forms.Form):
def __init__(self, *args, **kwargs):
# We require an ``instance`` parameter.
self.instance = kwargs.pop('instance')

# We call ``super`` (without the ``instance`` param) to finish
# off the setup.
super(PollForm, self).__init__(*args, **kwargs)

# We add on a ``choice`` field based on the instance we've got.
# This has to be done here (instead of declaratively) because the
# ``Poll`` instance will change from request to request.
self.fields['choice'] = 
forms.ModelChoiceField(queryset=Choice.objects.filter(poll=self.instance.pk), 
empty_label=None, widget=forms.RadioSelect)



def save(self):
if not self.is_valid():
raise forms.ValidationError("PollForm was not validated first 
before trying to call 'save'.")

choice = self.cleaned_data['choice']
choice.record_vote()
return choice




class PollFormTestCase(TestCase):
fixtures = ['polls_forms_testdata.json']

def setUp(self):
super(PollFormTestCase, self).setUp()
self.poll_1 = Poll.objects.get(pk=1)
self.poll_2 = Poll.objects.get(pk=2)

def test_init(self):
# Test successful init without data.
form = PollForm(instance=self.poll_1)
self.assertTrue(isinstance(form.instance, Poll))
self.assertEqual(form.instance.pk, self.poll_1.pk)
self.assertEqual([c for c in form.fields['choice'].choices], [(1, 
u'Yes'), (2, u'No')])

# Test successful init with data.
form = PollForm({'choice': 3}, instance=self.poll_2)
self.assertTrue(isinstance(form.instance, Poll))
self.assertEqual(form.instance.pk, self.poll_2.pk)
self.assertEqual([c for c in form.fields['choice'].choices], [(3, 
u'Alright.'), (4, u'Meh.'), (5, u'Not so good.')])

# Test a failed init without data.
self.assertRaises(KeyError, PollForm)

# Test a failed init with data.
self.assertRaises(KeyError, PollForm, {})



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




Submit a form but stay on the page and the form changes

2013-07-11 Thread Cody Scott
I would like to put a Poll Voting Form on any page like a blog post page or 
the homepage.
Here is the page that I display the form and the view that it gets posted 
to in the form action attribute.
I would like to be able to submit the form but stay on that page and have 
the form change into the results or a link to the results.

class DetailView(PublishedMixin, generic.DetailView):
model = Poll
template_name = 'polls/detail.html'

def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
context['form'] = PollForm(instance=self.get_object())
return context
{% csrf_token 
%}{{form.as_p}}


class VoteView(PublishedMixin, generic.DetailView):
model = Poll

'''def get_form(self, *args, **kwargs):form = 
PollForm(instance=self.get_object())#return super(VoteView, 
self).get_form(*args, **kwargs)return form'''
@property
def success_url(self):
return reverse(
'polls:results', args=(self.get_object().id,))

def post(self, request, *args, **kwargs):
form = PollForm(request.POST, instance=self.get_object())
if form.is_valid():
selected_choice = form.cleaned_data['choice']
selected_choice.votes += 1
selected_choice.save()  


return HttpResponseRedirect(request.META['HTTP_REFERER'])






I also thought about doing a mixin on the page, but I can't just render the 
page with the form attribute equal to something else, becuase I would need to 
redirect to avoid the refresh problem.



class PollFormMixin(SingleObjectMixin):"""puts form and "view results 
link" in contextand validates and saves the form"""model = Poll
def get_context_data(self, **kwargs):context = super(PollFormMixin, 
self).get_context_data(**kwargs)form = 
PollForm(instance=self.get_object())context['form'] = form
return contextdef post(self, request, *args, **kwargs):form = 
PollForm(request.POST, instance=self.get_object())if form.is_valid():   
 form.save()return HttpResponseRedirect(self.success_url)   
 else:return render(request, self.template_name,
{'form': form, 'poll': self.get_object()})


class VoteView(PublishedPollMixin, PollFormMixin, DetailView):"""Vote 
on a poll"""model = Polltemplate_name = 'polls/detail.html'
@propertydef success_url(self):return reverse(
'polls:results', args=(self.get_object().id,))

-- 
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: Submit a form but stay on the page and the form changes

2013-07-12 Thread Cody Scott
The code works, I can submit the form and go back to the page I came from
with the HTTP_REFERER , what I need help is getting the form to change, to
be the results.

For the syntax highlighting I submit my code to bpaste and then copy into
the message here.


On Fri, Jul 12, 2013 at 10:43 AM, Sergiy Khohlov  wrote:

> Hello Cody,
>
>  I would like to help.
>  1 ) could you please check if POST is going from  your browser to  django
> (I hope yes)
> 2)  First candidate for investigation is  function post in
> class PollFormMixin
>  I 'm proposing verify this by  adding
>  print  "form status",  form.is_valid()
>  after string form = PollForm(request.POST, instance=self.get_object())
>
>
>  P.S. How are you adding so nice formatting to your letter ?
>
>
> Many thanks,
>
> Serge
>
>
> +380 636150445
> skype: skhohlov
>
>
> On Thu, Jul 11, 2013 at 11:50 PM, Cody Scott wrote:
>
>> I would like to put a Poll Voting Form on any page like a blog post page
>> or the homepage.
>> Here is the page that I display the form and the view that it gets posted
>> to in the form action attribute.
>> I would like to be able to submit the form but stay on that page and have
>> the form change into the results or a link to the results.
>>
>> class DetailView(PublishedMixin, generic.DetailView):
>> model = Poll
>> template_name = 'polls/detail.html'
>>
>> def get_context_data(self, **kwargs):
>> context = super(DetailView, self).get_context_data(**kwargs)
>> context['form'] = PollForm(instance=self.get_object())
>> return context
>> {% csrf_token 
>> %}{{form.as_p}}
>>
>>
>> class VoteView(PublishedMixin, generic.DetailView):
>> model = Poll
>>
>> '''def get_form(self, *args, **kwargs):form = 
>> PollForm(instance=self.get_object())#return super(VoteView, 
>> self).get_form(*args, **kwargs)return form'''
>> @property
>> def success_url(self):
>> return reverse(
>> 'polls:results', args=(self.get_object().id,))
>>
>> def post(self, request, *args, **kwargs):
>> form = PollForm(request.POST, instance=self.get_object())
>> if form.is_valid():
>> selected_choice = form.cleaned_data['choice']
>> selected_choice.votes += 1
>> selected_choice.save()
>>
>>
>> return HttpResponseRedirect(request.META['HTTP_REFERER'])
>>
>>
>>
>>
>>
>>
>> I also thought about doing a mixin on the page, but I can't just render the 
>> page with the form attribute equal to something else, becuase I would need 
>> to redirect to avoid the refresh problem.
>>
>>
>>
>> class PollFormMixin(SingleObjectMixin):"""puts form and "view 
>> results link" in contextand validates and saves the form"""model 
>> = Polldef get_context_data(self, **kwargs):context = 
>> super(PollFormMixin, self).get_context_data(**kwargs)form = 
>> PollForm(instance=self.get_object())context['form'] = form
>> return contextdef post(self, request, *args, **kwargs):form = 
>> PollForm(request.POST, instance=self.get_object())if 
>> form.is_valid():form.save()return 
>> HttpResponseRedirect(self.success_url)else:return 
>> render(request, self.template_name,{'form': form, 'poll': 
>> self.get_object()})
>>
>>
>> class VoteView(PublishedPollMixin, PollFormMixin, DetailView):"""
>> Vote on a poll"""model = Polltemplate_name = 'polls/detail.html' 
>>@propertydef success_url(self):return reverse(
>> 'polls:results', args=(self.get_object().id,))
>>
>>  --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>>
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>>
>
>  --
> You received this message because you are subscr

Treebeard Hierarchical Form

2013-07-15 Thread Cody Scott
I am trying to create a hierarchical form with nodes in django-treebeard.
I am using code from the docs, but it doesn't reset when I have another 
root node, it should be on the left side if it has a depth of 1.


Also how would you make it expand when I click Products to expand products.

I organised my data into a tree so that displaying it in a hierarchical form 
would be easier. Is there a better way to do this?



{% for item, info in annotated_list %}
{% if not item.is_leaf %}

{% if info.open %}

{% else %}

{% endif %}
{{item}} - {{item.get_depth}}

{% for close in info.close %}

{% endfor %}
{%endif%}{% endfor %}



   - Products - 1
  - Computers - 2
 - Desktops - 3
 - Laptops - 3
- Net books - 4
- Tablets - 3
- Tablet Accessories - 4
- Services - 1
   - Replacement Parts - 2
  - Hard drives - 3
  - Monitors - 3
 - LCD - 4
 - Keyboards - 3
 - Contact - 1
  



-- 
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: Submit a form but stay on the page and the form changes

2013-07-15 Thread Cody Scott
I don't care if the page reloads, how do I change the form?


On Sat, Jul 13, 2013 at 1:19 AM, Babatunde Akinyanmi
wrote:

> I'm assuming you want the form to morph on the screen without a page
> reload. If that's the case, you need JavaScript like jQuery. let the view
> you are submitting your POST to return the data you need in JSON and use
> jQuery to remove the form and add the results or url
>
> Sent from my Windows Phone
> ------
> From: Cody Scott
> Sent: 7/12/2013 11:51 PM
> To: django-users@googlegroups.com
> Subject: Re: Submit a form but stay on the page and the form changes
>
> The code works, I can submit the form and go back to the page I came from
> with the HTTP_REFERER , what I need help is getting the form to change, to
> be the results.
>
> For the syntax highlighting I submit my code to bpaste and then copy into
> the message here.
>
>
> On Fri, Jul 12, 2013 at 10:43 AM, Sergiy Khohlov wrote:
>
>> Hello Cody,
>>
>>  I would like to help.
>>  1 ) could you please check if POST is going from  your browser to
>>  django (I hope yes)
>> 2)  First candidate for investigation is  function post in
>> class PollFormMixin
>>  I 'm proposing verify this by  adding
>>  print  "form status",  form.is_valid()
>>  after string form = PollForm(request.POST, instance=self.get_object())
>>
>>
>>  P.S. How are you adding so nice formatting to your letter ?
>>
>>
>> Many thanks,
>>
>> Serge
>>
>>
>> +380 636150445
>> skype: skhohlov
>>
>>
>> On Thu, Jul 11, 2013 at 11:50 PM, Cody Scott wrote:
>>
>>> I would like to put a Poll Voting Form on any page like a blog post page
>>> or the homepage.
>>> Here is the page that I display the form and the view that it gets
>>> posted to in the form action attribute.
>>> I would like to be able to submit the form but stay on that page and
>>> have the form change into the results or a link to the results.
>>>
>>> class DetailView(PublishedMixin, generic.DetailView):
>>> model = Poll
>>> template_name = 'polls/detail.html'
>>>
>>> def get_context_data(self, **kwargs):
>>> context = super(DetailView, self).get_context_data(**kwargs)
>>> context['form'] = PollForm(instance=self.get_object())
>>> return context
>>> {% csrf_token 
>>> %}{{form.as_p}}
>>>
>>>
>>>
>>>
>>> class VoteView(PublishedMixin, generic.DetailView):
>>> model = Poll
>>>
>>> '''def get_form(self, *args, **kwargs):form = 
>>> PollForm(instance=self.get_object())#return super(VoteView, 
>>> self).get_form(*args, **kwargs)return form'''
>>> @property
>>> def success_url(self):
>>> return reverse(
>>> 'polls:results', args=(self.get_object().id,))
>>>
>>> def post(self, request, *args, **kwargs):
>>> form = PollForm(request.POST, instance=self.get_object())
>>> if form.is_valid():
>>> selected_choice = form.cleaned_data['choice']
>>> selected_choice.votes += 1
>>> selected_choice.save()
>>>
>>>
>>> return HttpResponseRedirect(request.META['HTTP_REFERER'])
>>>
>>>
>>>
>>>
>>>
>>>
>>> I also thought about doing a mixin on the page, but I can't just render the 
>>> page with the form attribute equal to something else, becuase I would need 
>>> to redirect to avoid the refresh problem.
>>>
>>>
>>>
>>> class PollFormMixin(SingleObjectMixin):"""puts form and "view 
>>> results link" in contextand validates and saves the form"""
>>> model = Polldef get_context_data(self, **kwargs):context = 
>>> super(PollFormMixin, self).get_context_data(**kwargs)form = 
>>> PollForm(instance=self.get_object())context['form'] = form
>>> return contextdef post(self, request, *args, **kwargs):form = 
>>> PollForm(request.POST, instance=self.get_object())if 
>>> form.is_valid():form.save()return 
>>> HttpResponseRedirect(self.success_url)else:return 
>>> render(request, self.templa

How to Create an Auto Incrementing Integer Field

2013-07-19 Thread Cody Scott
 

I have a list of articles and you can control the order of the articles by 
changing the order field in the model


order = models.IntegerField(default=1)


I would like it to default to one more than the last article or one more 
than the largest order (since you can set the order)


I can't use AutoField because it is only for primary keys.

-- 
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: How to Create an Auto Incrementing Integer Field

2013-07-22 Thread Cody Scott
Thank you very much, that was exactly what I was looking for.

On Monday, 22 July 2013 09:48:51 UTC-4, Christian Erhardt wrote:
>
> Have a look at this post: 
> http://stackoverflow.com/questions/3123796/how-to-make-an-auto-filled-and-auto-incrementing-field-in-django-admin
>  
> They determine the next value by calling a function called number(). In 
> your case it would look something like this:
>
> class Cliente(models.Model):
>> """This is the client data model, it holds all client information. 
>> This
>>docstring has to be improved."""
>> def number():
>> no = Cliente.objects.all().aggregate(Max(order))
>> if no == None:
>> return 1
>> else:
>> return no + 1
>>
>> clientcode = models.IntegerField(_('Code'), max_length=6, 
>> unique=True, \
>> default=number)
>>
>  
>

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




How to set the email to lowercase on User Creation?

2013-07-22 Thread Cody Scott
I have a custom auth app. I am trying to only allow emails to be lower case 
in the database.
I can create a user in the admin with Capitalized letters, even with 
email.lower() in the create_user method.

Another solution would be to specify to the authenticate that the email can 
be any case.

user = authenticate(email=email, password=password)

#models.py

class MyUserManager(BaseUserManager):
def create_user(self, username, name, email, company, password, is_manager):
#if not username:
#raise ValueError('User must have a username')

user = self.model(username=username,
email=MyUserManager.normalize_email(email.lower()),
#email=email.lower(),
name=name, company=company, is_manager=is_manager
)

user.set_password(password)
user.save(using=self._db)

#checks pending teams in the login view
return user

def create_superuser(self, password, username='', email=''):
user = self.create_user(username=username,
name='',
email=email,
company='not_a_companyNAMe',
password=password,
is_manager=False
)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user

class Users(AbstractBaseUser, PermissionsMixin):
email   = models.EmailField(verbose_name=_('email address'), 
max_length=255, blank=True, unique=True)
name= models.CharField(verbose_name=_('Name'), max_length=50, 
blank=True)
company = models.CharField(verbose_name=_('Company'), 
max_length=255, blank=True)
is_manager  = models.BooleanField(default=False, verbose_name=_('Check 
this box if you are a manager or need to create teams'))
is_active   = models.BooleanField(default=True)
is_admin= models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
datecreated = models.DateField(auto_now=True)

objects = MyUserManager()
if settings.LDAP:
username= models.CharField(verbose_name=_('Username'), 
max_length=50, unique=True)
USERNAME_FIELD  = 'username'
else:
username= models.CharField(verbose_name=_('Username'), 
max_length=50)
USERNAME_FIELD  = 'email'

REQUIRED_FIELDS = []

class Meta:
verbose_name_plural = "Users"


#admin.py

class UserCreationForm(forms.ModelForm):

password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', 
widget=forms.PasswordInput)
name  = forms.CharField(label='Name', widget=forms.TextInput)
company   = forms.CharField(label='Company', widget=forms.TextInput)
is_manager= forms.BooleanField(label='Manager', required=False)

class Meta:
model = Users

def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2

def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.name = self.cleaned_data["name"]
user.company = self.cleaned_data["company"]
user.is_manager = self.cleaned_data['is_manager']
if commit:
user.save()
return user

class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()

class Meta:
model = Users

def clean_password(self):
return self.initial["password"]

class MyUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm

readonly_fields = ('last_login',)

list_display = ('name', 'email', 'is_manager', 'company',)
list_editable = ('email', 'is_manager', 'company',)
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('username', 'email', 'name', 'company', 
'password')}),
('Permissions', {'fields': ('is_manager', 'is_admin', 'groups', 
'user_permissions')}),
('Important dates', {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'name', 'company', 'password1', 'password2', 
'is_manager')}
),
)
search_fields = ('email', 'name', 'company', 'username',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(Users, MyUserAdmin)




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

Using input for an IntegerField

2013-12-28 Thread Cody Scott
I have a model with an IntegerField and I would like to display the model 
form for it with a  input.

With the following code I get an error :

'ChoiceField' object has no attribute 'is_hidden'


Here is a minimal django 1.6.1 project with the 
problem. https://github.com/Siecje/choice_widget/


class Education(models.Model):
school = models.CharField(max_length=255)
start_year = models.IntegerField()
end_year = models.IntegerField()
degree = models.CharField(max_length=255, null=True, blank=True)

def __unicode__(self):
display_txt = '%s, (%s - %s)' % (self.school, self.start_year, 
self.end_year)
return display_txt

class EducationForm(forms.ModelForm):

class Meta:
model = Education
fields = ['school', 'start_year', 'end_year', 'degree']
widgets = {
#'start_year': forms.TextInput(attrs={'placeholder': '2005'}),
#'end_year': forms.TextInput(attrs={'placeholder': '2009'}),
'start_year': forms.ChoiceField(choices=YEAR_CHOICES),
'end_year': forms.ChoiceField(choices=YEAR_CHOICES),
}

-- 
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/e5a83572-df4c-4ebf-955e-3c4cdd172b72%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Using input for an IntegerField

2013-12-28 Thread Cody Scott
There should be a  widget to use in the 'widgets' dict. I was able 
to override the default of number field with a text field with the lines 
that are commented out. 

On Saturday, 28 December 2013 17:14:53 UTC-5, Daniel Roseman wrote:
>
> On Saturday, 28 December 2013 20:12:24 UTC, Cody Scott wrote:
>>
>> I have a model with an IntegerField and I would like to display the model 
>> form for it with a  input.
>>
>> With the following code I get an error :
>>
>> 'ChoiceField' object has no attribute 'is_hidden'
>>
>>
>> Here is a minimal django 1.6.1 project with the problem. 
>> https://github.com/Siecje/choice_widget/
>>
>>
>> class Education(models.Model):
>> school = models.CharField(max_length=255)
>> start_year = models.IntegerField()
>> end_year = models.IntegerField()
>> degree = models.CharField(max_length=255, null=True, blank=True)
>>
>> def __unicode__(self):
>> display_txt = '%s, (%s - %s)' % (self.school, self.start_year, 
>> self.end_year)
>> return display_txt
>>
>> class EducationForm(forms.ModelForm):
>>
>> class Meta:
>> model = Education
>> fields = ['school', 'start_year', 'end_year', 'degree']
>> widgets = {
>> #'start_year': forms.TextInput(attrs={'placeholder': '2005'}),
>> #'end_year': forms.TextInput(attrs={'placeholder': '2009'}),
>> 'start_year': forms.ChoiceField(choices=YEAR_CHOICES),
>> 'end_year': forms.ChoiceField(choices=YEAR_CHOICES),
>> }
>>
>>
> That's not what the `widgets` dict is for. ChoiceField is a field, not a 
> widget, hence the name. If you want to override the field, do it at class 
> level:
>
> class EducationForm(forms.ModelForm):
> start_year = forms.ChoiceField(choices=YEAR_CHOICES)
> end_year = forms.ChoiceField(choices=YEAR_CHOICES)
>
> class Meta:
> model = Education
> fields = ['school', 'start_year', 'end_year', 'degree'] 
>
> --
> DR.
>

-- 
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/b34b5f21-53a6-4b70-91ba-78585fc20df8%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.