Re: django.db.migrations.graph.NodeNotFoundError:

2016-12-23 Thread Collin Anderson
Hi,

Do you want to copy and paste your error message? (I assume it's similar, 
but it might have some better clues.)

My guess you have a migration that's referencing a migration file that was 
deleted or something.

Collin

On Thursday, December 22, 2016 at 7:33:48 PM UTC-6, skerdi wrote:
>
> I have the same problem, but with an existing project. I've deleted 
> migrations and the database and shows the same problem.
> I have 2+ hours searching but I haven't fixed it. 
>
> On Wednesday, June 1, 2016 at 12:58:55 AM UTC+2, Bose Yi wrote:
>>
>> When new project start,   commands makemigrations and runserver  get 
>>  error message.I do not know what I did wrong.   I cannot find solution 
>> to fix it.  Please  any suggestion ? 
>>
>>
>> 
>>
>> System check identified no issues (0 silenced).
>>
>> Unhandled exception in thread started by 
>>
>> Traceback (most recent call last):
>>
>>   File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 
>> 229, in wrapper
>>
>> fn(*args, **kwargs)
>>
>>   File 
>> "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py",
>>  
>> line 116, in inner_run
>>
>> self.check_migrations()
>>
>>   File 
>> "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py",
>>  
>> line 168, in check_migrations
>>
>> executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
>>
>>   File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", 
>> line 19, in __init__
>>
>> self.loader = MigrationLoader(self.connection)
>>
>>   File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", 
>> line 47, in __init__
>>
>> self.build_graph()
>>
>>   File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", 
>> line 318, in build_graph
>>
>> _reraise_missing_dependency(migration, parent, e)
>>
>>   File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", 
>> line 288, in _reraise_missing_dependency
>>
>> raise exc
>>
>> django.db.migrations.graph.NodeNotFoundError: Migration 
>> auth.0007_user_following dependencies reference nonexistent parent node 
>> (u'account', u'0003_contact')
>>
>

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


Re: ProgrammingError: relation "auth_user" does not exist.

2016-12-23 Thread Collin Anderson
Hi,

Have you tried running ./manage.py makemigrations and then ./manage.py 
migrate? That's needed to actually create the table.

Collin

On Thursday, December 22, 2016 at 12:25:58 PM UTC-6, Biplab Gautam wrote:
>
> I tried to set up custom user model by inheriting from AbstractBaseUser as 
> instructed in django documentation, but I am encountering relation 
> "auth_user" does not exist error.
>
> #models.py
> from django.db import models
> from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
>
> class MyUserManager(BaseUserManager):
> def create_user(self, email, date_of_birth, password=None):
> """Creates and saves the user with the given email, DOB and password"""
> if not email:
> raise ValueError('Users must have an email address')
> user = 
> self.model(email=self.normalize_email(email),date_of_birth=date_of_birth,)
> user.set_password(password)
> user.save(using=self._db)
> return user
>
> def create_superuser(self, email, date_of_birth, password):
> """Creates and saves a superuser with the given email, date of birth and 
> password."""
> user = self.create_user(email, password=password, 
> date_of_birth=date_of_birth)
> user.is_admin = True
> user.save(using=self._db)
> return user
>
> class MyUser(AbstractBaseUser):
> email = models.EmailField(verbose_name='email address', max_length=255, 
> unique=True,)
> date_of_birth = models.DateField()
> is_active = models.BooleanField(default=True)
> is_admin = models.BooleanField(default=False)
>
> objects = MyUserManager()
>
> USERNAME_FIELD = 'email'
> REQUIRED_FIELDS = ['date_of_birth']
>
> def get_full_name(self):
> return self.email
> def get_short_name(self):
> return self.email
> def __str__(self):
> return self.email
> def has_perm(self, perm, obj=None):
> return True
> def has_module_perms(self, app_label):
> return True
> @property
> def is_staff(self):
> return self.is_admin
>
> #admin.py
> from django import forms
> from django.contrib import admin
> from django.contrib.auth.models import Group
> from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
> from django.contrib.auth.forms import ReadOnlyPasswordHashField
>
> from user.models import MyUser
>
> class UserCreationForm(forms.ModelForm):
> """A form for creating new users. Includes all the required fields, plus a 
> repeated password."""
> password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
> password2 = forms.CharField(label='Password confirmation', 
> widget=forms.PasswordInput)
>
> class Meta:
> model = MyUser
> fields = ('email', 'date_of_birth')
>
> 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):
> """A form for updating users. Includes all the fields on the user, but 
> replaces the password field with admin's password hash display field."""
> password = ReadOnlyPasswordHashField()
> class Meta:
> model = MyUser
> fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
> def clean_password(self):
> return self.initial["password"]
> # Regardless of what the user provides, return the initial value.
> # This is done here, rather than on the field, because the
> # field does not have access to the initial value
>
>
>
> class UserAdmin(BaseUserAdmin):
> # The forms to add and change user instances
> form = UserChangeForm
> add_form = UserCreationForm
>
> # The fields to be used in displaying the User model.
> # These override the definitions on the base UserAdmin
> # that reference specific fields on auth.User.
> list_display = ('email', 'date_of_birth', 'is_admin')
> list_filter = ('is_admin',)
> fieldsets = (
> (None, {'fields': ('email', 'password')}),
> ('Personal info', {'fields': ('date_of_birth',)}),
> ('Permissions', {'fields': ('is_admin',)}),
> )
> # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
> # overrides get_fieldsets to use this attribute when creating a user.
> add_fieldsets = (
> (None, {
> 'classes': ('wide',),
> 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
> ),
> )
> search_fields = ('email',)
> ordering = ('email',)
> filter_horizontal = ()
>
> # Now register the new UserAdmin...
> admin.site.register(MyUser, UserAdmin)
> # ... and, since we're not using Django's built-in permissions,
> # unregister the Group model from admin.
> admin.site.unregister(Group)
>
> #views.py
> from 

Re: existing database connectivity

2016-12-23 Thread Collin Anderson
Hi,

You could try re-installing psycopg2 to see if that fixes it.

Collin

On Thursday, December 22, 2016 at 1:55:53 AM UTC-6, Rasika wrote:
>
>
> I am followed the steps as I am getting in tutorials
> when I run the command :
> python manage.py migrate
> this is giving me following error
>
> from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
> ImportError: DLL load failed: The specified module could not be found.
>
> During handling of the above exception, another exception occurred:
>
> Traceback (most recent call last):
>   File "manage.py", line 22, in 
> execute_from_command_line(sys.argv)
> On Monday, December 19, 2016 at 7:50:19 PM UTC+5:30, Derek wrote:
>>
>> Suggest you look at Django authentication:
>>
>> https://docs.djangoproject.com/en/1.10/topics/auth/customizing/
>> "Authentication backends provide an extensible system for when a username 
>> and password stored with the user model need to be authenticated against a 
>> different service than Django’s default."
>>
>> It also seems as if your Django project was not set up properly (again 
>> from the docs):
>>
>> "By default, the required configuration is already included in the 
>> settings.py generated by django-admin startproject, these consist of two 
>> items listed in your INSTALLED_APPS setting:
>> 1. 'django.contrib.auth' contains the core of the authentication 
>> framework, and its default models.
>> 2.  'django.contrib.contenttypes' is the Django content type system, 
>> which allows permissions to be associated with models you create"
>>
>>
>> On Monday, 19 December 2016 13:34:39 UTC+2, Rasika wrote:
>>>
>>> Hello all,
>>>  I am using Django framework for our website.I am stuck on the 
>>> database connectivity.I want to change the default database sqlite with our 
>>> for test purpose but in that also I am getting problems.
>>>  My aim is I have to use our compnies database so that already 
>>> registered users have not to create their account again
>>> AsDjango already comes with its own builtin apps for login,logout 
>>> authentication and registration .Also I am not able to find the 
>>> 'django.contrib.auth',
>>> 'django.contrib.contenttypes',
>>> 'django.contrib.sessions',
>>> 'django.contrib.sites',
>>> 'django.contrib.admin',
>>> etc and all default apps also.
>>> Please help me.
>>>
>>> Thank you.
>>>
>>

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


Re: MultiWidget not rendering

2016-12-23 Thread Collin Anderson
Hi,

I think you want something like this.

class Fourteen(forms.Form):
mywidget = forms.DateField(widget=DateSelectorWidget())

Collin

On Monday, December 19, 2016 at 1:13:17 PM UTC-6, Farhan Khan wrote:
>
> Unfortunately that does not display.
> In the template I had it as {{ fourteen }} and saw it was rendering 
> everything but my custom widget.
>
> --
> Farhan Khan
> PGP Fingerprint: 4A78 F071 5CB6 E771 B8D6 3910 F371 FE22 3B20 B21B
>
> On Mon, Dec 19, 2016 at 2:02 PM, Matthew Pava  > wrote:
>
>> I’m not that familiar with MultiWidget, but it would seem that your print 
>> statement should be:
>>
>> print(fourteen.mywidget)
>>
>>  
>>
>> *From:* django...@googlegroups.com  [mailto:
>> django...@googlegroups.com ] *On Behalf Of *Farhan Khan
>> *Sent:* Monday, December 19, 2016 11:40 AM
>> *To:* Django users
>> *Subject:* MultiWidget not rendering
>>
>>  
>>
>> Hi all!
>>
>> I am trying to get a MultiWidget with two TextFields ,however I am not 
>> able to get anything to render. Here is my code.
>>
>>  
>>
>> from django import forms
>> from django.forms import widgets
>>
>> class DateSelectorWidget(widgets.MultiWidget):
>> def __init__(self, attrs=None):
>> _widgets = (forms.TextInput(),
>> forms.TextInput())
>> super(DateSelectorWidget, self).__init__(_widgets, attrs)
>>
>> def format_output(self, rendered_widgets):
>> return ''.join(rendered_widgets)
>>
>> class Fourteen(forms.Form):
>> mywidget = DateSelectorWidget()
>>
>>  
>>
>> In the shell I will do:
>>
>>  
>>
>> >>> fourteen = Fourteen()
>>
>> >>> print(fourteen)
>>
>>  
>>
>> >>> 
>>
>>
>> Nothing will render. I suspect that I need to manually render the HTML, 
>> but the documentation 
>>  
>> is fairly light on this topic.
>>
>>  
>>
>> Any assistance would be greatly appreciated!
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to djang...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/86bebdb4-1d45-4612-84d1-456f86942709%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>> -- 
>> You received this message because you are subscribed to a topic in the 
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit 
>> https://groups.google.com/d/topic/django-users/hUmvw-mdaiY/unsubscribe.
>> 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 https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/ebd9f58fca3a4009abcfd05e16fca9dc%40ISS1.ISS.LOCAL
>>  
>> 
>> .
>>
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

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


Re: return values from static files to django admin

2015-11-05 Thread Collin Anderson
Hi,

You may need to also calculate the possible options in python. Some hacky 
code that might help:

class AdminRoutingInlineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AdminRoutingInlineForm, self).__init__(*args, **kwargs)
field1 = self.data.get('field1', '')
CHOICES = [('a', '%s any' % field1),('b', '%s blah' % field1),] 
self.fields['choice_text'].choices = CHOICES

Collin

On Monday, November 2, 2015 at 9:32:58 PM UTC+1, dc wrote:
>
> I tried that. But in that case I need to declare choices in models.py for 
> that field (so that the field is displayed as a dropdown in admin) and then 
> django doesn't accept any string that's not part of the choices list. I am 
> pretty sure I am missing something here.
>
> On Mon, Nov 2, 2015 at 2:55 PM, Andreas Kuhne  > wrote:
>
>> Hi,
>>
>> Yes you could just populate the dropdown list with javascript. 
>>
>> Regards,
>>
>> Andréas
>>
>> 2015-11-02 17:27 GMT+01:00 dc :
>>
>>> Thanks a lot. Let me look into it.
>>>
>>> Is there any other way I can populate my choice list with user input?
>>>
>>> On Monday, November 2, 2015 at 10:19:22 AM UTC-5, Andréas Kühne wrote:

 Hi,

 What you are suggesting doesn't work. You can't communicate with the 
 django backend via javascript if you don't use a lot of ajax requests. I 
 would check django-smart-selects and see if you could use that?

 Regards,

 Andréas

 2015-11-02 15:57 GMT+01:00 dc :

> Any lead will be extremely helpful. I am still stuck. :(
>
> On Thursday, October 29, 2015 at 11:40:32 PM UTC-4, dc wrote:
>>
>> I have declared a charfield 'choice_text' in one of my models. I want 
>> to convert it to a dropdown box in django admin. The choices in the 
>> dropdown list depend on user input to a textbox defined in another 
>> model class. I have a javascript (declared  as Media class inside a 
>> ModelAdmin class) that reads user input in the textbox. But I am unable 
>> to 
>> this choice list back from .js file to django admin. How do I do that? 
>> Thanks in advance.
>>
>> I have tried this.
>>
>> *models.py*
>> class Routing(models.Model):
>> choice_text = models.CharField(_('Choices'), max_length=100, 
>> default="(any)", null=False)
>>
>> *admin.py*
>> class AdminRoutingInlineForm(forms.ModelForm):
>> def __init__(self, *args, **kwargs):
>> super(AdminRoutingInlineForm, self).__init__(*args, **kwargs)
>> CHOICES = [('a', 'any'),('b', 'blah'),] * // override 
>> this with choices from populate_dropdown.js (code below)*
>> self.fields['choice_text'].choices = CHOICES
>>
>> class RoutingInlineAdmin(StackedInline):
>> form = AdminRoutingInlineForm
>> fields = (('choice_text', 'next'),)
>> model = Routing
>>
>>
>> class FormModelAdmin(ModelAdmin):
>> inlines = [RoutingInlineAdmin]
>>
>> class Media:
>> js= ("sforms/admin/populate_dropdown.js",)
>>
>>
>> *populate_dropdown.js*
>> (function($) {
>> $(document).ready(function() {
>>
>> $("[id^=id_fields-][id$=_options_0]").each(function(){ *  
>> // user input from this field will be used as choices*
>> choices = '(any),' + $(this).val().split("\n");
>> alert(choices);
>> 
>> *// send this choices back to admin.py and override CHOICES 
>> in AdminRoutingInlineForm class*
>> });  
>> });
>>  
>>
>>
>> -- 
> You received this message because you are subscribed to the Google 
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send 
> an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/6ef56f22-dce0-4a85-b348-381b3a93e88f%40googlegroups.com
>  
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

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

Re: jquery and django template

2015-11-05 Thread Collin Anderson
Hi,

Are you trying to show the user what filters are being applied to the data, 
or are you trying to filter the data based on a user selection?

Collin

On Monday, November 2, 2015 at 2:51:36 AM UTC+1, varun naganathan wrote:
>
> I basically have the database entries in the namespace of my template.I 
> basically need to get the filter i want to apply on the databse entry using 
> data available from user selection(using jquery).Any suggestions on how i 
> can achieve 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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/37a720f5-020b-49ec-8119-120da188ca5a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django bootstrap3_datetime widget in admin site doesn't pass form data

2015-11-05 Thread Collin Anderson
Hi Ilia,

The default admin widget looks for id_0 and id_1, but if you use a custom 
widget, that is responsible for looking for its own value (like 
publish_time_1). You could check out DateTimePicker's source code to see 
what it's actually doing.

Thanks,
Collin

On Sunday, November 1, 2015 at 3:04:28 PM UTC+1, Ilia wrote:
>
> I'm trying to replace the standard AdminSplitDateTime widget in my admin 
> site for better functionality (basically I want to display only 'available' 
> dates in my calender which I couldn't find how to do with the default 
> picker). I decided to use the bootstrap3_datetime widget.
>
> After overriding my field to use the new widget, it doesn't seem to be 
> transferred into the 'clean' method (isn't in self.cleaned_data) for 
> validation.
>
> *models.py*
>
> publish_time = models.DateTimeField('Date to publish')
>
> *admin.py*
>
> class MyForm(forms.ModelForm):
>
> def __init__(self, *args, **kwargs):
> super(MyForm, self).__init__(*args, **kwargs)
> bad_dates = []
> #populating bad_dates with application logic
>
> def clean(self):
>
> # This will always return None when using the new widget.
> # When working with the default widget, I have the correct value.
> publish_time = self.cleaned_data.get('publish_time', None)
>
>
> publish_time = forms.DateTimeField(widget=DateTimePicker(options=
> {"format": "DD-MM- HH:mm",
>  "startDate": timezone.now().strftime('%Y-%m-%d'),
>  "disabledDates": bad_dates,
>  })
>
> class MyModelAdmin(admin.ModelAdmin):
> form = MyForm
>
> admin.site.register(MyModel, MyModelAdmin)
>
> HTML-wise, the widget works well and the text field is populated with the 
> correct date (and with the 'bad_dates' disabled). The problem is that it 
> seems it isn't saved on the form.
>
> I also tried initializing the widget in the init method by doing:
>
> self.fields['publish_time'].widget = DateTimePicker(options=...)
>
> But the result was the same.
>
> I've analysed the POST request that is sent using each of the widgets. In 
> the default admin widget, I see that it generates two fields: 
> "publish_time_0" (for date) and "publish_time_1" (for time). In the 
> bootstrap3 widget, only a single "publish_time" field is sent.
>
> I'm assuming that the admin site understands that the field is a 
> DateTimeField (from models), looks for id_0 and id_1 and that's why it 
> fails. Does that make sense? Is there anyway around it?
>
> Thanks a lot!
> Ilia
>

-- 
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/60cd4c0a-3220-46f7-8527-2230f291432c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: mssql databASE CONNECTION to Django

2015-11-05 Thread Collin Anderson
Hello,

I'd recommend using django 1.7 until mssql gets compatible with django 1.8.

Thanks,
Collin

On Friday, October 30, 2015 at 3:31:35 PM UTC+1, Sid wrote:
>
> sorry tim I know I am asking a dumb question...can you please tell me what 
> is the best way to make it work please if possibe...because I am struck 
> form last 2 days
>

-- 
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/111d7267-3597-4bdb-8bb9-20e3eb13879c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Locking / serializing access to one element in database

2015-11-05 Thread Collin Anderson
Hi Carsten,

If you're just updating one field, this _might_ work for you:

try:
TestMonthModel.objects.create(jahr=Jahr, monat=Monat)  # create() uses 
force_insert.
except IntegrityError:
pass # It already exists. No Problem.
# ... calculate some things.
TestMonthModel.objects.filter(jahr=Jahr, monat=Monat).update(value=new_value
)

Collin

On Wednesday, October 28, 2015 at 8:50:09 PM UTC+1, Carsten Fuchs wrote:
>
> Hi Collin, hi all, 
>
> Am 27.10.2015 um 19:56 schrieb Collin Anderson: 
> > Yes, an exception will be raised. 
>
> Thinking further about this, all we need is a method that gives us an 
> exception if we 
> accidentally create a second object when in fact only one is wanted. Your 
> suggestion 
> with manually dealing with the PKs and using .save(force_insert=True) is 
> one method to 
> achieve that, another one that works well for me is using an 
> (application-specific) 
>
>  unique_together = (year, month) 
>
> constraint, which achieves the desired result (guarantee uniqueness where 
> required, 
> raise an exception otherwise) without having to manually deal with PKs. 
>
> Alas, I wonder how to proceed to complete the solution. As I find it 
> simpler to deal 
> with the above mentioned unique_together rather than with coming up with a 
> PK based 
> solution, I refer to my original code from [1], which was: 
>
>
>  try: 
>  mm = TestMonthModel.objects.select_for_update().get(jahr=Jahr, 
> monat=Monat) 
>  except TestMonthModel.DoesNotExist: 
>  mm = TestMonthModel(jahr=Jahr, monat=Monat) 
>
>  # A *long* computation, eventually setting fields in mm and save: 
>
>  mm.value = 123 
>  mm.save() 
>
>
> Combining everything from this thread, this could be changed into this 
> code 
> (pseudo-code, not tested): 
>
>
>  while True: 
>  try: 
>  mm = 
> TestMonthModel.objects.select_for_update().get(jahr=Jahr, monat=Monat) 
>  break   # Got what we wanted! 
>  except TestMonthModel.DoesNotExist: 
>  try: 
> # Create the expected but missing instance. 
>  # No matter if the following succeeds normally or throws 
>  # an Integrity error, thereafter just restart the loop. 
>  TestMonthModel(jahr=Jahr, monat=Monat).save() 
>  except IntegrityError: 
>  pass 
>
>  # A *long* computation, eventually setting fields in mm and save: 
>
>  mm.value = 123 
>  mm.save() 
>
>
> Afaics, this solves the problem, but it also feels quite awkward and I 
> wonder if there 
> is a more elegant solution. 
>
> Comments? Does this sound reasonable at all? 
>
> Best regards, 
> Carsten 
>
> [1] https://groups.google.com/forum/#!topic/django-users/SOX5Vjedy_s 
>
>

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


Re: [django_tables2] Expected table or queryset, not 'str'.

2015-11-05 Thread Collin Anderson
Hi,

Do you to post your traceback if you're still getting this error?

Thanks,
Collin

On Wednesday, October 28, 2015 at 2:17:28 PM UTC+1, Leutrim Osmani wrote:
>
> Can you please tell me how did you fixed this error ?
>
> On Monday, April 29, 2013 at 9:21:29 AM UTC+2, binith a k wrote:
>>
>> You were correct, it was indeed a version problem.
>> I was using latest django-tables2 in my new python virtual env and I had 
>> an older version (of django-tables2) installed as default, and the 
>> PYTHONPATH environment variable was pointing to the older version.
>>
>> Problem solved, thanks for the time
>>
>> thanks
>> -binith
>>
>> On Friday, 26 April 2013 07:25:35 UTC-7, Binith Babu wrote:
>>>
>>> I am sorry I coud not find a solution in this thread
>>>
>>> Did you mean I am using an older version of django tables2 ?
>>> In that case I am not, I am using the latest version installed with pip.
>>> May be its my mistake, I am still trying to figure whether I am doing 
>>> something wrong.
>>> WIll post back if I find something.
>>>
>>> Thanks
>>> binith
>>>
>>>
>>>
>>> On Friday, 26 April 2013 06:53:06 UTC-7, Tom Evans wrote:

 On Fri, Apr 26, 2013 at 2:30 PM, Binith Babu  wrote: 
 > 
 > I got the same error today, anybody know a solution? 
 > 

 Apart from the solution I already posted to the list in this thread? 

 Cheers 

 Tom 

>>>

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


Re: Standalone Project using django ORM

2015-11-05 Thread Collin Anderson
Hi,

It looks like you stack trace is somehow getting cut off.

My guess is it's trying to import something that either doesn't exist or 
has a syntax error.

Collin

On Wednesday, October 28, 2015 at 12:39:06 AM UTC+1, ADEWALE ADISA wrote:
>
> The screen shot is attached. There is no error message but the trace. But 
> the program seem stop at django.setup(). Though it ran smoothly in django 
> 1.50
> On Oct 28, 2015 12:27 AM, "Dheerendra Rathor"  > wrote:
>
>> Is this the full stacktrace? Looks like error message is missing in 
>> stacktrace. 
>>
>> On Wed, 28 Oct 2015 at 04:05 ADEWALE ADISA > > wrote:
>>
>>> Hello;
>>> I have being having issues trying to use django orm in my application. 
>>> This issues occur when using django 1.85. The application run perfectly 
>>> well on django 1.50. Bellow are the snippet :
>>>
>>> Model.py:
>>> from django.db import models
>>>
>>> class Person(models.Model):
>>> name = models.CharField(max_length=100)
>>> email = models.CharField(max_length=100)
>>> birthdate = models.DateField()
>>> class Meta:
>>> app_label = 'runnable'
>>> 
>>> def __unicode__(self):
>>> return u'%d: %s' % (self.id, self.name)
>>>
>>> app.py:
>>>
>>> import sys
>>> from os import path
>>> import collections
>>> import datetime
>>> sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..'
>>> )))
>>>
>>> from django.core.management import call_command
>>> from django.conf import settings
>>>
>>> #print(sys.path)
>>> if not settings.configured:
>>> settings.configure(
>>>DEBUG=True,
>>> DATABASES={
>>> 'default': {
>>> # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 
>>> 'oracle'.
>>> 'ENGINE': 'django.db.backends.sqlite3',
>>> # Or path to database file if using sqlite3.
>>> 'NAME': ':memory:',
>>> }
>>> },
>>> INSTALLED_APPS=("runnable", )
>>> 
>>> )
>>>
>>> import django
>>> django.setup()
>>> #call_command('syncdb')
>>> call_command('makemigrations')
>>> call_command('migrate')
>>> call_command('inspectdb')
>>> from models import Person
>>> print("PERSON: "+ Person)
>>>
>>> Console msg:
>>> p.py", line 28, in 
>>> django.setup()
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/__init__.py",
>>>  
>>> line 18, in setup
>>> apps.populate(settings.INSTALLED_APPS)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/apps/registry.py",
>>>  
>>> line 108, in populate
>>> app_config.import_models(all_models)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/apps/config.py",
>>>  
>>> line 198, in import_models
>>> self.models_module = import_module(models_module_name)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/python32.zip/importlib/__init__.py",
>>>  
>>> line 124, in import_module
>>>
>>> Note:
>>> The application run successfully with django 1.50  by uncomment syncdb 
>>> and comment out migration, make migrations.
>>>
>>> Thanks.
>>>
>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to django-users...@googlegroups.com .
>>> To post to this group, send email to django...@googlegroups.com 
>>> .
>>> Visit this group at http://groups.google.com/group/django-users.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/CAMGzuy9BSMrgqw8uMgp3kd9eBu5fTdF4DCB9%3Di-8r6EmZmN-WA%40mail.gmail.com
>>>  
>>> 
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/CAByqUgjWYn%3DtfSeA-EBrzeur2_jodiPysZUS%3Dor%2BFeCFpKhbwg%40mail.gmail.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this 

Re: Safe tag is working differently for different view.

2015-11-05 Thread Collin Anderson
Hello,

Are you sure they're using the same template? (If you change something does 
it actually affect both views?)

Is one of the views using mark_safe?

Collin

On Tuesday, October 27, 2015 at 9:29:02 PM UTC+1, sonu kumar wrote:
>
> I am having two views both are extending from same base.html and both of 
> them have loaded same template tags, but one is escaping string using safe 
> and other is not what could be 
> Code 
>
> view 1
>
> {% extends 'base.html' %}
> {% load inplace_edit mezzanine_tags rating_tags keyword_tags comment_tags 
> nano_tags staticfiles %}
>
> ...
>
> {% comments_for object %}
>
> ...
>
> view 2
>
> {% extends "base.html" %}
>
> {% load inplace_edit mezzanine_tags comment_tags keyword_tags nano_tags i18n 
> future staticfiles %}
>
> ...
>
> {% comments_for blog_post %}
>
> ...
>
>
> view3 (comment.html)
>
> {% load i18n mezzanine_tags comment_tags  nano_tags future %}
>
> ...
>
> {{ comment.comment|safe  }}
>
> ...
>
>
> As we can see both view 1 and 2 are using same function so it would be using 
> same template but in view2 safe is working and in view1 it's not working.
>
>
> What could be the reason for this ?
>
>
>

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


Re: Django Models Joining and Normalising

2015-10-28 Thread Collin Anderson
Hello,

I'd personally keep it all in one model for as long as possible. It will 
really simplify queries and it should make your code a lot cleaner. Wait 
til you have some actual performance problems before splitting the models 
up.

Collin

On Wednesday, October 14, 2015 at 12:11:55 PM UTC-4, Yunti wrote:
>
> I'm still relatively new to Django and now working on a project that has 
> much more complex models than I've used before.  
>
> The question is about when is it best to separate out large models into 
> separate models (and the impact caused by joining the smaller models 
> together and also keeping data normalised).  
>
> I'm trying to model magazine subscriptions, which are available from 
> different suppliers - the costs vary slightly per region (due to delivery 
> costs) and the available subscriptions vary slightly dependent on payment 
> type (direct debit, card, cheque etc...). 
>
> The subscriptions have a lot of different fields for each subscriptions so 
> I'm not clear on how best to represent this in django - one large model or 
> split into smaller models.
>
> Firstly,  each supplier will have multiple magazines - to keep the data 
> normalised should the suppliers be kept in a separate table/model separate 
> to the subscriptions table? How will this impact performance when having to 
> join the data back together when querying a list of subscriptions. 
> (e.g. similarly for payment types of which there are only 4 should these 
> be pulled out into a separate table? and regions)
>
> There will be a form field for: 
> supplier
> payment type,
> region,
> should a separate model be made for these 3 fields to ease with making the 
> form and how should that tie into the above tables (if they should be 
> separated? Should I make e.g. an Input model class with ForeignKeys to each 
> of the separate tables?). 
>
> Thanks.  
>
>
>

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


Re: Flakey tests and django.db.utils.InterfaceError: connection already closed

2015-10-28 Thread Collin Anderson
Hello,

Here are some questions that might help debugging this:

Do other tests that use the database run ok?

If you run _only_ this test, is it still a problem?

Are you using threads at all?

Is there an exception that's being silenced somewhere else?

Collin


On Tuesday, October 27, 2015 at 9:14:13 AM UTC-4, Christopher R. wrote:
>
> Have you been able to fix the problem? I am encountering the same issue on 
> both Django 1.8.4 and 1.8.5.
>
> Any help would be appreciated.
>
> On Thursday, October 8, 2015 at 3:38:16 PM UTC+1, thinkwell wrote:
>>
>> I could use some assistance in troubleshooting a psycopg2.InterfaceError 
>> problem that has erratic behavior. Here is the test module 
>>  suite that I'm running to test these 
>> models , and in this state all the tests 
>> in the module pass. However, it's extremely easy to trigger a 
>> psycopg2.InterfaceError, although not relating to the lines changed. For 
>> example, if I change:
>>
>> class TestSilly(SimpleTestCase): 
>>   
>> def test_is_not_false(self): 
>> self.assertTrue(False is not True)
>>
>>
>> to 
>>
>> class TestSilly(TestCase): 
>>   
>> def test_is_not_false(self): 
>> self.assertTrue(False is not True)
>>
>>   
>>
>> Then this error is raised, but referencing TestPolicyModel instead of 
>> TestSilly!
>>
>> ==
>> ERROR: test_toggle_autofix (accounts.tests.test_models.TestPolicyModel)
>> --
>> Traceback (most recent call last):
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", 
>> line 137, in _cursor
>> return self.create_cursor()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql_psycopg2/base.py"
>> , line 212, in create_cursor
>> cursor = self.connection.cursor()
>> psycopg2.InterfaceError: connection already closed
>>
>> The above exception was the direct cause of the following exception:
>>
>> Traceback (most recent call last):
>>   File "apps/accounts/tests/test_models.py", line 174, in 
>> test_toggle_autofix
>> p = Policy.objects.first()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/models/manager.py", 
>> line 127, in manager_method
>> return getattr(self.get_queryset(), name)(*args, **kwargs)
>>   File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py"
>> , line 490, in first
>> objects = list((self if self.ordered else self.order_by('pk'))[:1])
>>   File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py"
>> , line 162, in __iter__
>> self._fetch_all()
>>   File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py"
>> , line 965, in _fetch_all
>> self._result_cache = list(self.iterator())
>>   File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py"
>> , line 238, in iterator
>> results = compiler.execute_sql()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py"
>> , line 838, in execute_sql
>> cursor = self.connection.cursor()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", 
>> line 164, in cursor
>> cursor = self.make_cursor(self._cursor())
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", 
>> line 137, in _cursor
>> return self.create_cursor()
>>   File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py", line 
>> 97, in __exit__
>> six.reraise(dj_exc_type, dj_exc_value, traceback)
>>   File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py", 
>> line 658, in reraise
>> raise value.with_traceback(tb)
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", 
>> line 137, in _cursor
>> return self.create_cursor()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql_psycopg2/base.py"
>> , line 212, in create_cursor
>> cursor = self.connection.cursor()
>> django.db.utils.InterfaceError: connection already closed
>>
>>
>> For another example, if I change 
>>
>> TestPolicyModel(TestCase)
>>
>>
>> to
>>
>> TestPolicyModel(SimpleTestCase)
>>
>>
>> then, I get the following error regarding TestRedwoodModel
>>
>> ==
>> ERROR: setUpClass (accounts.tests.test_models.TestRedwoodModel)
>> --
>> Traceback (most recent call last):
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/base/base.py", 
>> line 137, in _cursor
>> return self.create_cursor()
>>   File 
>> "/usr/local/lib/python3.4/dist-packages/django/db/backends/postgresql_psycopg2/base.py"
>> , line 212, in create_cursor
>> cursor = self.connection.cursor()
>> psycopg2.InterfaceError: connection already 

Re: Polymorphic class and geomodels?

2015-10-28 Thread Collin Anderson
Hello,

Are you trying to combine multiple models into one, like this?

class PolyModel(pdmpunto, pdmtransetto, pdmarea):
pass

You could also try asking on the geodjango list: 
http://groups.google.com/group/geodjango

Collin

On Monday, October 26, 2015 at 7:18:24 AM UTC-4, Luca Moiana wrote:
>
> Hi, working on my first django app, and run into a problem.
>
> I tend to create geodjango objects, and add all data from external tables 
> with pk.
>
> Then I want to have different geometries 8points, lines, polygons) into a 
> unique polymorphic class, can I do that?
>
> I have an error that I'll document later, and I'm trying to figure out 
> what to do.
>
> Here is the model:
> import datetime
>
> from django.db import models
> from django.contrib.gis.db import models as geomodels
> from django.utils import timezone
> from django.forms import ModelForm
> from polymorphic import PolymorphicModel
>
> # Geometria linea da monitorare
> class geolinea(geomodels.Model):
> progetto = models.CharField(max_length=14, primary_key=True)
> geom = geomodels.MultiLineStringField()
> objects = geomodels.GeoManager()
> def __str__(self):
> return '%s' % (self.progetto)
> # Oggetto Progetto soggetto a PMA
> class linea(models.Model):
> progetto = models.ForeignKey(geolinea)
> nome = models.CharField(max_length=200)
> TENSIONE = (
> ('132', '132kV'),
> ('150', '150kV'),
> ('220', '220kV'),
> ('380', '380kV'),
> )
> tensione = models.CharField(max_length=5,
> choices=TENSIONE)
> def __str__(self):
> return '%s' % (self.nome)
>
> # Geometria dei pdm
> class pdmpunto(geomodels.Model):
> linea = models.ForeignKey(linea)
> numero = models.CharField(max_length=3)
> geom = geomodels.PointField()
> objects = geomodels.GeoManager()
>
> class pdmtransetto(geomodels.Model):
> linea = models.ForeignKey(linea)
> numero = models.CharField(max_length=3)
> geom = geomodels.LineStringField()
> objects = geomodels.GeoManager()
>
> class pdmarea(geomodels.Model):
> linea = models.ForeignKey(linea)
> numero = models.CharField(max_length=3)
> geom = geomodels.PolygonField()
> objects = geomodels.GeoManager()
>
> class pdm(PolymorphicModel):
> numero = models.CharField(max_length=14, primary_key=True)
> class punto(pdm):
> rifpunto = models.ForeignKey(pdmpunto)
> class transetto(pdm):
> riftransetto = models.ForeignKey(pdmtransetto)
> class area(pdm):
> rifarea = models.ForeignKey(pdmarea)
>
>
>
>

-- 
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/45f813d4-c476-4cc5-a299-03fb10edd6b7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Adding gif file to existing project

2015-10-27 Thread Collin Anderson
Hi Gary,

This sounds like an issue with Ninja-IDE. You could try asking on their 
mailing list: http://groups.google.com/group/ninja-ide/topics

Thanks,
Collin

On Sunday, October 25, 2015 at 10:51:13 PM UTC-4, Gary Roach wrote:
>
> Django 1.8 
> Python 3.4 
> Debian 8 (jessie) with kde desktop 
> Postresql 9.4 
> Apache2 
> venv environment setup 
> Ninja-IDE 
>
> The problem is that I am having trouble getting the image.gif file in 
> the project to show up in the IDE directory. The project tree is as 
> follows: 
>
> . 
> ├── archive 
> │   ├── archive 
> │   │   ├── __init__.py 
> │   │   ├── __pycache__ 
> │   │   │   ├── __init__.cpython-34.pyc 
> │   │   │   ├── settings.cpython-34.pyc 
> │   │   │   ├── urls.cpython-34.pyc 
> │   │   │   └── wsgi.cpython-34.pyc 
> │   │   ├── settings.py 
> │   │   ├── urls.py 
> │   │   └── wsgi.py 
> │   ├── archive.nja 
> │   ├── db.sqlite3 
> │   ├── home 
> │   │   ├── admin.py 
> │   │   ├── __init__.py 
> │   │   ├── migrations 
> │   │   │   ├── __init__.py 
> │   │   │   └── __pycache__ 
> │   │   │   └── __init__.cpython-34.pyc 
> │   │   ├── models.py 
> │   │   ├── __pycache__ 
> │   │   │   ├── admin.cpython-34.pyc 
> │   │   │   ├── __init__.cpython-34.pyc 
> │   │   │   ├── models.cpython-34.pyc 
> │   │   │   └── views.cpython-34.pyc 
> │   │   ├── tests.py 
> │   │   └── views.py 
> │   ├── __init__.py 
> │   ├── main 
> │   │   ├── admin.py 
> │   │   ├── __init__.py 
> │   │   ├── migrations 
> │   │   │   ├── 0001_initial.py 
> │   │   │   ├── 0002_auto_20151019_1147.py 
> │   │   │   ├── 0003_auto_20151021_1441.py 
> │   │   │   ├── __init__.py 
> │   │   │   └── __pycache__ 
> │   │   │   ├── 0001_initial.cpython-34.pyc 
> │   │   │   ├── 0002_auto_20151019_1147.cpython-34.pyc 
> │   │   │   ├── 0003_auto_20151021_1441.cpython-34.pyc 
> │   │   │   └── __init__.cpython-34.pyc 
> │   │   ├── models.py 
> │   │   ├── __pycache__ 
> │   │   │   ├── admin.cpython-34.pyc 
> │   │   │   ├── __init__.cpython-34.pyc 
> │   │   │   └── models.cpython-34.pyc 
> │   │   ├── tests.py 
> │   │   └── views.py 
> │   ├── manage.py 
> │   ├── static 
> │   │   ├── home 
> │   │   │   ├── images 
> │   │   │   │   ├── django.gif 
> │   │   │   │   └── __init__.py 
> │   │   │   ├── __init__.py 
> │   │   │   └── style.css 
> │   │   └── __init__.py 
> │   └── templates 
> │   ├── admin 
> │   │   ├── base_site.html 
> │   │   └── __init__.py 
> │   ├── home 
> │   │   ├── index.html 
> │   │   └── __init__.py 
> │   └── __init__.py 
>
> You will notice that there is a django.gif file under static / home / 
> images. Unfortunately, this file does not show up in the IDE's tree. 
> I can't seem to figure out why. Below is the settings.py file for the 
> project. Have I done something wrong here. 
>
> _ 
>
> # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 
> import os 
>
> BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
>
>
> # Quick-start development settings - unsuitable for production 
> # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ 
>
> # SECURITY WARNING: keep the secret key used in production secret! 
> SECRET_KEY = '$ey(n0ld$2v7x*4b+!zt#+ub519+km9n=_4yz2f2kd' 
>
> # SECURITY WARNING: don't run with debug turned on in production! 
> DEBUG = True 
>
> ALLOWED_HOSTS = [] 
>
>
> # Application definition 
>
> INSTALLED_APPS = ( 
>  'django.contrib.admin', 
>  'django.contrib.auth', 
>  'django.contrib.contenttypes', 
>  'django.contrib.sessions', 
>  'django.contrib.messages', 
>  'django.contrib.staticfiles', 
>  'main', 
>  'home', 
> ) 
>
> MIDDLEWARE_CLASSES = ( 
>  'django.contrib.sessions.middleware.SessionMiddleware', 
>  'django.middleware.common.CommonMiddleware', 
>  'django.middleware.csrf.CsrfViewMiddleware', 
>  'django.contrib.auth.middleware.AuthenticationMiddleware', 
>  'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 
>  'django.contrib.messages.middleware.MessageMiddleware', 
>  'django.middleware.clickjacking.XFrameOptionsMiddleware', 
>  'django.middleware.security.SecurityMiddleware', 
> ) 
>
> ROOT_URLCONF = 'archive.urls' 
>
> TEMPLATES = [ 
>  { 
>  'BACKEND': 'django.template.backends.django.DjangoTemplates', 
>  'DIRS': [os.path.join(BASE_DIR, 'templates')], 
>  'APP_DIRS': True, 
>  'OPTIONS': { 
>  'context_processors': [ 
>  'django.template.context_processors.debug', 
>  'django.template.context_processors.request', 
>  'django.contrib.auth.context_processors.auth', 
>  'django.contrib.messages.context_processors.messages', 
>  ], 
>  }, 
>  }, 
> ] 
>
> WSGI_APPLICATION = 'archive.wsgi.application' 
>
>
> # Database 
> # 

Re: Locking / serializing access to one element in database

2015-10-27 Thread Collin Anderson
Yes, an exception will be raised. As an example, Django uses force_insert 
when creating sessions:

https://github.com/django/django/blob/32ef48aa562e6aaee9983f5d0f1c60f02fd555fb/django/contrib/sessions/backends/db.py#L86

On Saturday, October 24, 2015 at 2:36:15 PM UTC-4, Joakim Hove wrote:
>
> Hi Collin;
>
> thank you for your suggestion:
>
> [...] if the thread thinks that the object is new, it could try using 
>> .save(force_insert=True). 
>>
>
> I have read to read the force_insert documentation without understanding 
> 100%. Assume threads t1 and t2 are racing to create the first element with 
> this primary key, and that t1 wins the race. Then when t2 issues:
> 
> save( force_insert = True )
>
> will an exception be raised?
>
>  
>

-- 
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/249303c1-2a39-41a0-8ab9-0d6e4a1bf9fd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: makemigrations and language_code

2015-10-27 Thread Collin Anderson
Hi,

is libapp using ugettext_lazy? That's what the admin app is using.

Collin

On Thursday, October 22, 2015 at 2:53:53 AM UTC-4, Hugo Osvaldo Barrera 
wrote:
>
>  
> On Tue, Oct 20, 2015, at 10:39, Aron Podrigal wrote:
>
> Simply run 
>
> ./manage.py makemigrations myapp 
>
>  
> That will avoid running for all your installed apps.
>
>  
> That's merely a workaround, but it still doesn't solve the problem. 
> Mainly, other users of libapp will still encounter the same issue.
>  
> I'm curious as to how the admin app avoid this particular issue.
>  
>
>  
> On Monday, October 19, 2015 at 12:58:23 AM UTC-4, Hugo Osvaldo Barrera 
> wrote:
>
> I'm having a rather confusing scenario regarding makemigrations and 
> language_code: 
>  
> * I've an app (let's call it myapp) which I'm developing. 
> * myapp relies on the another app (let's call it libapp). 
> * myapp has language_code set to "es-ar". 
> * libapp was developed separately, and has been installed via pip. 
>  
> While developing myapp, whenever I run "makemigrations" a migrations is 
> also created for libapp. The migrations updates all the verbose_name and 
> help_text fields and nothing else. I don't want this, especially since 
> it creates a conflict in the migration graph when I later upgrade 
> libapp. 
>  
> How can I have makemigrations *ignore* the language_code? 
>  
> Also, why does makemigrations create this migration for libapp, but not 
> an equivalent one for django.contrib.admin? 
> I tried looking at things like the admin to see how they avoid this, and 
> found no clues. 
>  
> Thanks, 
>  
> -- 
> Hugo Osvaldo Barrera 
>
>  
> --
> Hugo Osvaldo Barrera
>  
>

-- 
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/c7dc176c-7df4-4f7a-acf6-75b4a3d29ad4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Dynamic Formset Radiobutton Issue

2015-10-24 Thread Collin Anderson
Hello,

That formset jQuery script it quite ancient (2009). You could try using 
jQuery 1.2.6 and see if it works correctly with that version.

Collin

On Friday, October 23, 2015 at 8:54:49 AM UTC-4, Jur Remeijn wrote:
>
> So I'm using a dynamic formset within django: 
> https://github.com/elo80ka/django-dynamic-formset
> I'm using it to render a page with a form (say, a pizza) and a formset 
> (say, a set of toppings). Because the number of toppings isn't determined, 
> I want to use a dynamical formset. 
> Right now, I have the page display one instance of topping form, with a 
> button to add another instance, which is added with the javascript found in 
> the github repo (and as a attachment).
> Only I have a problem: When I fill in the form for one topping, and then 
> add another topping, all the radiobuttons get reset so the data from the 
> first topping is lost. 
>
> Does anyone see what goes wrong here? This is my code, simplified (I 
> actually have a lot more fields for the form and subset, all choicefields 
> needing radiobuttons, so this is quite a big issue for me). 
>
> models.py:
> *class Pizza(models.Model):*
> *name= models.CharField(max_length=55)*
> *pricerange=models.CharField(max_length=55, 
> choices=PRICERANGE_CHOICES)*
>
> *class Topping(models.Model):*
> *pizza = models.ForeignKey(Pizza)*
> *number = models.IntegerField(null=True, blank=True)*
> *name=models.CharField(max_length=55, choices=TOPPINGNAME_CHOICES)*
>
> forms.py:
> class PizzaForm(forms.ModelForm):
>
>   class Meta:
> model = Pizza
> fields = ['name', 'pricerange']
> 
>   pricerange= 
> forms.ChoiceField(required=True,widget=forms.RadioSelect(),choices=PRICERANGE_CHOICES)
>
> class ToppingForm(forms.ModelForm):
>   class Meta:
> model = Topping
> fields = ['number', 'name'
> *]*
>   
>   number = forms.IntegerField(required=True)
>   name = 
> forms.ChoiceField(required=True,widget=forms.RadioSelect(),choices=TOPPINGNAME_CHOICES)
>
> ToppingFormset = formset_factory(ToppingForm, max_num=8)
>
> form.html:
> * src="/static/pizza/jquery-1.11.3.min.js">*
> * src="/static/pizza/jquery.formset.js">*
> **
> *$(function() {*
> *$('.ToppingForm').formset();*
> *})*
> **
>
>
>
>
> *.add-row {padding-left:18px;
> background:url(/static/arts/images/add.png) no-repeat left center;}
> .delete-row {display:block;margin:6px 0 0 0;
> padding-left:18px;background:url(/static/arts/images/delete.png) 
> no-repeat left center;}.dynamic-form { padding: 5px 15px; 
> }   {% csrf_token %} {{ 
> form.non_field_errors }}{{ form.name  }}
> {{ form.pricerange}}  {% for form in 
> formset.forms %}  
>  {{ 
> form.name.label_tag }} {{ form.name.errors }}  {% for radio 
> in form.name  %} {{ radio }} {% endfor %}  
> {{ form.number.errors }}{{ 
> form.number}}  {% endfor %}  {{ formset.management_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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4881d596-f1f5-4182-8124-7c5ff2e0e5fe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Locking / serializing access to one element in database

2015-10-24 Thread Collin Anderson
Hi Carsten,

Something that might help: depending on how your unique keys are set up, if 
the thread thinks that the object is new, it could try using 
.save(force_insert=True). That way it won't overwrite a different object 
with the same PK.

Thanks,
Collin

On Thursday, October 22, 2015 at 9:56:36 AM UTC-4, Carsten Fuchs wrote:
>
> Am 22.10.2015 um 01:16 schrieb Simon Charette: 
> > I would suggest you use select_for_update() 
> > <
> https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-for-update>
>  
> in a 
> > transaction. 
>
> This only covers the case where the object with the given ID already 
> exists, doesn't it? 
>
> That is, if a new object is created in the except-clause, concurrent 
> threads might 
> create a new object each, whereas it would presumably be expected that 
> new_text is 
> (twice) added to a single common instance. 
>
> As I had the quasi exact same question a while ago (see 
> https://groups.google.com/forum/#!topic/django-users/SOX5Vjedy_s) but 
> never got a reply, 
> I (too) am wondering how the new-object case in the except-clause could be 
> handled? 
>
> Best regards, 
> Carsten 
>
>

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


Re: Complex form in modelform

2015-10-24 Thread Collin Anderson
Hi,

For starters, here's an example of a formset for multiple images:
http://stackoverflow.com/questions/32889199/how-to-upload-multiple-images-using-modelformset-django

Collin

On Monday, October 19, 2015 at 4:56:18 PM UTC-4, Arnab Banerji wrote:
>
> Hi - I am trying to create a form from a model, say M with the following:
>
> (1) a certain field FOO is a text field which would be constructed in 
> views.py by concatenating a dynamic set of rows (so I need a jQuery plugin 
> for that).
>
> (2) multiple images can be tied to the model M, and I have a ForeignKey in 
> the image model that maps to M - I need a jQuery plugin for that too so 
> that users can add images dynamically.
>
> (3) If a user gave a name already in use, the form goes into "edit" mode 
> for the already existing model (modelchoiceform with validation to the 
> rescue?)
>
> Any good examples of the above scenarios? Or a form handling API?
>
> Thanks a ton!
> -AB
>

-- 
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/2077f73a-b3b4-4830-bf70-adb7da60ac60%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 1.7.6 TypeError when applying migration with ForeignKey with default

2015-03-12 Thread Collin Anderson
Hi,

Maybe g() should return the id instead of the instance? That does seem a 
bit odd that it wouldn't accept an A() instance as the default.

Collin

On Wednesday, March 11, 2015 at 7:43:35 AM UTC-4, Krzysztof Ciebiera wrote:
>
> I have created a model A:
>
> def g():
> return A.objects.get(pk=1)
>
> class A(models.Model):
> a = models.IntegerField()
>
> ./manage.py makemigrations
> ./manage.py migrate
>
> then I've added some data:
>
> a = A(a=1)
> a.save()
>
> then I have created another model with a ForeignKey field with a default 
> set to g function (that really returns one instance od A) and I was trying 
> to migrate it:
>
> class B(models.Model):
> b = models.ForeignKey(A, default=g)
>
> ./manage.py makemigrations
> ...
> ./manage.py migrate
> 
>   File 
> ".../e/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py",
>  
> line 627, in get_db_prep_save
> prepared=False)
>   File 
> ".../e/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py",
>  
> line 907, in get_db_prep_value
> value = self.get_prep_value(value)
>   File 
> ".../p/e/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py",
>  
> line 915, in get_prep_value
> return int(value)
> TypeError: int() argument must be a string or a number, not 'A'
>
> Is it expected behaviour or a bug?
>

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


Re: Testing Django: testing template at different time

2015-03-12 Thread Collin Anderson
Hi,

You could try using freezegun to run the test as if it were a certain time 
of day.
https://pypi.python.org/pypi/freezegun

Or, you could say something like:
if 9 <= datetime.datetime.now().hour < 17:
self.assertContains(response, "It's working time!") 
else:
self.assertContains(response, "Happy holiday!")

That way it will at least not fail (most of the time :).

Collin

On Wednesday, March 11, 2015 at 7:43:35 AM UTC-4, Zaki Akhmad wrote:
>
> Hello, 
>
> I'd like to write a test script for my django app. 
>
> Example, if within business hour, my django app will render: 
> "It's working time!" 
>
> And if not within business hour, my django app will render: 
> "Happy holiday!" 
>
> So the views, will check when the url is accessed. 
>
> How do I write the test script? 
> Following django docs here[1], I started to write my test code. 
>
> from django.test import Client, TestCase 
>
> class TestPage(TestCase): 
> def test_holiday(self): 
> response = self.client.get('/day/') 
> self.assertEqual(response.status_code, 200) 
> self.assertContains(response, "It's working time!") 
>
> This test code will success if I run within business hour. But If I 
> run it not within business hour, the test code will fail. 
>
> * How to write a better test code? 
> * How do I use mock/patch? 
> * How to write test code that will check the within and not within 
> business hour in one file that both will success whenever I run the 
> test code? 
>
> [1]
> https://docs.djangoproject.com/en/1.7/topics/testing/tools/#testing-responses 
>
> Thanks, 
>
> -- 
> Zaki Akhmad 
>

-- 
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/3003d453-3d31-4fed-ab9a-eadd40fee8af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Different user profile associated to a each user group

2015-03-12 Thread Collin Anderson
Hi,

I'd personally recommend re-using the same model and having a "type" field 
for whether it's corporate or private.

Otherwise, you'd need to do something like:

class Corporate(models.Model):
user = models.OneToOneField(User)

class Private(models.Model):
user = models.OneToOneField(User)

Then, you would need to try to query for the profile. Something like:
try:
corporate = request.user.corporate
except Corporate.DoesNotExist:
corporate = None

Collin

On Wednesday, March 11, 2015 at 3:50:31 AM UTC-4, elpaso wrote:
>
> Hi, 
>
> I've used custom user profiles in the past, but they were associated 
> to all users, now I need to associate a different custom profile for 
> each user group (for example: "corporate", "private"). 
>
> Any hint about the best approach? 
>
> -- 
> Alessandro Pasotti 
> w3:   www.itopen.it 
>

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


Re: Django OperationalError

2015-03-12 Thread Collin Anderson
Hi,

Do you have the correct file path set to your sqlite3 database? Does it 
have proper permissions?

I found a similar issue here:
https://www.pythonanywhere.com/forums/topic/1814/

Collin

On Wednesday, March 11, 2015 at 2:04:45 AM UTC-4, Petar Pilipovic wrote:
>
> Hey Collin,
> I have done what have you told me, but I still have that error, I even 
> created data base on www.pythonanywhere.com, and amend mine setting.py 
> file to use that db.
> I have manually deleted database and done syncdb, migrate etc.
> Here are the output for syncdb <http://ur1.ca/jvzba>, and then I have 
> made mine superuser, this is the Operational Error <http://ur1.ca/jvzbq>.
> Question: Why is he reporting this template rendering error on line 40? 
> <http://ur1.ca/jvzbz>
> Tank you
> Best 
> Petar
>
> On Tue, Mar 10, 2015 at 6:49 PM, Petar Pilipovic <iam...@gmail.com 
> > wrote:
>
>> Heh, lol, Ok tax Collin I will do that. I was thinking that i need to 
>> delete mine migration from the terminal, but I will try that, tnx
>> 10.03.2015. 18.01, "Collin Anderson" <cmawe...@gmail.com > 
>> је написао/ла:
>>
>> Hi Petar,
>>>
>>> I'm actually not sure why you want to call sqlflush. If you're trying to 
>>> clear out the database, you may need to delete the migrations table 
>>> manually, but it just might be simpler to delete the either database and 
>>> re-create it, rather than the individual tables.
>>>
>>> Collin
>>>
>>> On Friday, March 6, 2015 at 11:24:19 PM UTC-5, Petar Pilipovic wrote:
>>>>
>>>> Hello Collin,
>>>> No the problem is, i have tried to drop mine migrations whit python 
>>>> manage sqlflush, then I have recreate the db whit 
>>>> python manage.py migrate.
>>>> Here this is the all operation whit python manage sqlflush, syncdb, 
>>>> migrate <http://ur1.ca/jv371>. I have notice that there was no 
>>>> migration to apply at the end, and the error is still there.
>>>> Is there something else I can do, or how can I approach this 
>>>> differently.
>>>> Best
>>>> Petar
>>>>
>>>> On Fri, Mar 6, 2015 at 11:21 PM, Collin Anderson <cmawe...@gmail.com> 
>>>> wrote:
>>>>
>>>>> Hi,
>>>>>
>>>>> The problem is that django_session doesn't exist in your database. 
>>>>> Either it was never created or it was created and then later deleted.
>>>>>
>>>>> Does running manage.py migrate re-create it?
>>>>>
>>>>> Collin
>>>>>
>>>>> On Monday, March 2, 2015 at 11:36:51 PM UTC-5, Petar Pilipovic wrote:
>>>>>>
>>>>>> Hello James, sorry for not uploading mine answer on this mater, I was 
>>>>>> busy whit something else this day, ok now back to mine Operational Error 
>>>>>> I 
>>>>>> have got.
>>>>>> I tried to google some solution to this problem had no luck, and I 
>>>>>> did what have you told me.
>>>>>> I heave done some 
>>>>>> python manage.py sqlflush
>>>>>>
>>>>>> and that has gave me this output: 
>>>>>>
>>>>>> (django17)04:20 ~/mineDjango$ python manage.py sqlflush BEGIN;DELETE 
>>>>>> FROM "django_admin_log";DELETE FROM "auth_permission";DELETE FROM 
>>>>>> "auth_group";DELETE FROM "auth_group_permissions";DELETE FROM 
>>>>>> "django_session";DELETE FROM "auth_user_groups";DELETE FROM 
>>>>>> "auth_user_user_permissions";DELETE FROM "account_emailaddress";
>>>>>> DELETE FROM "django_site";DELETE FROM "profiles_profile";DELETE FROM 
>>>>>> "auth_user";DELETE FROM "profiles_userstripe";DELETE FROM 
>>>>>> "account_emailconfirmation";DELETE FROM "django_content_type";COMMIT;
>>>>>>
>>>>>> Then I have done 
>>>>>> python manage.py syncdb python manage.py migrate
>>>>>>
>>>>>> Output of mine recreating tables are this:
>>>>>> (django17)04:20 ~/mineDjango$ python manage.py syncdbOperations to 
>>>>>> perform: Synchronize unmigrated apps: allauth, crispy_forms Apply 
>>>>>> all migrations: account, sessions, admin, sites, profiles, 
>>

Re: [django 1.7.6] system error: 10054 An existing connection was forcibly closed by the remote host

2015-03-12 Thread Collin Anderson
Hi,

Interesting. If you switch back to previous version of django you don't 
have that problem?

Is it a slow query?

Are you using MySQL or MSSQL?

Collin

On Tuesday, March 10, 2015 at 8:55:44 PM UTC-4, Weifeng Pan wrote:
>
> Hi,
>
>
> I upgrade to latest version of django.  Every time I navigate to django 
> admin site "User" page.  I got this error:
>
> File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\core\handlers\base.py", 
> line 111, in get_response
> response = wrapped_callback(request, *callback_args, **callback_kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\options.py",
>  
> line 583, in wrapper
> return self.admin_site.admin_view(view)(*args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\utils\decorators.py", 
> line 105, in _wrapped_view
> response = view_func(request, *args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\views\decorators\cache.py",
>  
> line 52, in _wrapped_view_func
> response = view_func(request, *args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\sites.py", 
> line 206, in inner
> return view(request, *args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\utils\decorators.py", 
> line 29, in _wrapper
> return bound_func(*args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\utils\decorators.py", 
> line 105, in _wrapped_view
> response = view_func(request, *args, **kwargs)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\utils\decorators.py", 
> line 25, in bound_func
> return func.__get__(self, type(self))(*args2, **kwargs2)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\options.py",
>  
> line 1485, in changelist_view
> self.list_max_show_all, self.list_editable, self)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\views\main.py",
>  
> line 109, in __init__
> self.queryset = self.get_queryset(request)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\views\main.py",
>  
> line 359, in get_queryset
> filters_use_distinct) = self.get_filters(request)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\views\main.py",
>  
> line 175, in get_filters
> self.model, self.model_admin, field_path=field_path)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\filters.py",
>  
> line 158, in create
> model, model_admin, field_path=field_path)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\contrib\admin\filters.py",
>  
> line 172, in __init__
> self.lookup_choices = field.get_choices(include_blank=False)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\fields\__init__.py",
>  
> line 750, in get_choices
> self.get_limit_choices_to())]
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\query.py", 
> line 141, in __iter__
> self._fetch_all()
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\query.py", 
> line 966, in _fetch_all
> self._result_cache = list(self.iterator())
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\query.py", 
> line 265, in iterator
> for row in compiler.results_iter():
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\sql\compiler.py",
>  
> line 700, in results_iter
> for rows in self.execute_sql(MULTI):
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\models\sql\compiler.py",
>  
> line 786, in execute_sql
> cursor.execute(sql, params)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\backends\utils.py", 
> line 81, in execute
> return super(CursorDebugWrapper, self).execute(sql, params)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\django\db\backends\utils.py", 
> line 65, in execute
> return self.cursor.execute(sql, params)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\mysql\connector\django\base.py", 
> line 135, in execute
> return self._execute_wrapper(self.cursor.execute, query, args)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\mysql\connector\django\base.py", 
> line 124, in _execute_wrapper
> utils.DatabaseError(err.msg), sys.exc_info()[2])
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\mysql\connector\django\base.py", 
> line 115, in _execute_wrapper
> return method(query, args)
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\mysql\connector\cursor.py", 
> line 507, in execute
> self._handle_result(self._connection.cmd_query(stmt))
>   File 
> "C:\MyProjects\WuWuKe\venv\lib\site-packages\mysql\connector\connection.py", 
> line 722, in cmd_query
> result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
>   File 
> 

Re: Filtering a QuerySet by the result of user.has_perm

2015-03-12 Thread Collin Anderson
Hi Adam,

It's pretty inefficient, but you can do:
MyModel.objects.filter(pk__in=[obj.pk for obj in MyModel.objects.all() if 
user.has_perm('read', obj)])

But, actually, I think you want to use get_objects_for_user():
http://django-guardian.readthedocs.org/en/v1.2/userguide/check.html#get-objects-for-user

Collin

On Tuesday, March 10, 2015 at 5:47:57 PM UTC-4, Adam Gamble wrote:
>
> Hi all,
>
> I'm stuck on how to restructure the following in order to return a 
> QuerySet instead of a List (needed for Lazy evaluation):
>
> filter(lambda o: user.has_perm('read', o), MyModel.objects.all())
>
> Using django-guardian , for 
> object-level permissions.
>
> Appreciate any ideas,
>
> Adam
>

-- 
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/d4e2e9f4-941d-4cf9-b77e-b7a2bacb54fb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Getting 500 error on ASO

2015-03-11 Thread Collin Anderson
Hi Michael,

Are you checking your Apache log? Also, be sure to set up ADMINS so you can 
get emails for any django errors.

I believe runfastcgi is gone from django now, along with all 
of django.core.servers.fastcgi.

At work we used to host on ASO too. We now use Linode. Digital Ocean is 
good too.

Collin

On Monday, March 9, 2015 at 9:57:47 PM UTC-4, mfox_chi wrote:
>
> Hi Everyone,
>
> I've been working on learning Django the past few months and have been 
> following the django tutorials here:
>
> https://docs.djangoproject.com/en/1.7/.
>
> I've followed the tutorial on my local machine in addition to on my A 
> Small Orange account.
>
> A Small Orange has this tutorial:
>
>
> https://kb.asmallorange.com/customer/portal/articles/1603414-install-django-using-virtualenv
>
> which has gotten me to reach the default django "Congrats" webpage. This 
> pages appears on both my local machines django setup and the ASO website. 
> The next step is to run the startapp function within the mysite folder.
>
> My folder structure is as follows on the ASO server
>
> home/"username"/
>website/
>   mysite/ 
> polls/ (after I run the startapp command)
>(all the startapp default files) 
> mysite/
>  (all the startproject default files)
>   public_html/
>   dispatch.fcgi
>   .htaccess
>
> My issue is that when I run "python27 manage.py startapp polls" from 
> within the website/mysite folder my server immediately goes to a 500 
> internal server error page online while this function causes no issues on 
> my local computer.
>
> The only lead I have on the problem currently is that when I run my 
> dispatch.fcgi file via "python27 dispatch.fcgi" from within the public_html 
> directory I get the HTML output that should be up on my website. The output 
> is shown within my SSH. This makes me think the error has something to do 
> with the communication between the .htaccess file and the dispatch file. 
>
> -dispatch.fcgi 
>
> from traceback import formate_exc
> try:
> #!/home#/theopeni/.env/env/bin/python
>
>  import sys
>  import os
>
>  sys.path.insert(0, 
> "/home/(myusername)/.env/env/lib/python2.7/site-packages")
>  sys.path.append("/home/(my username)/website/mysite/mysite")
>
> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
>
> from django.core.servers.fastcgi import runfastcgi
> runfastcgi(method="threaded", daemonize="false")
>
> except Exception:
> open("/home/(my username)/website/error.txt", "w").write(format_exc())
> raise
>
> -.htaccess
>
> AddHandler fcgi-script .fcgi
> RewriteEngine On
> RewriteCon %{REQUEST_FILENAME} !-f
> RewriteRule ^(.*)$ dispatch.fcgi/$1 [QSA,L]
>
> I've talked to the ASO customer support and I worked with a technical 
> support person for about a week to solve it and they were able to get an 
> app started without error but then told me that this was beyond the scope 
> of their customer support. I then tried adding my own app with the python27 
> manage.py startapp command and it broke the website again. 
>
> Has anyone else encountered this problem?
>
> Thank you!
>
> Michael
>

-- 
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/8bd55f77-8617-43bf-9d88-4d04e95683d4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django server serving cached template pages

2015-03-10 Thread Collin Anderson
Hi,

Yes, apparently many people get tripped up on this step. Is this django1.7?

create a blank "blank_site.html".  <- I assume you mean create a blank 
base_site.html?

I assume this is with manage.py runserver? (If it's apache/uwsgi/gunicorn, 
you need to reload the program when changing the setting.)

Caching should only be an issue if the cached template loader is installed, 
which it isn't by default.

Collin

On Sunday, March 8, 2015 at 4:10:09 PM UTC-4, Bryan Arguello wrote:
>
> I am on the second page of the blog tutorial and am trying to change the 
> base-site.html template.  
>
> I make a few small changes, set the permissions to 755, put it in
> a subdirectory named 'admin' within a directory called 'template' inside 
> of the project directory.  
>
> I also add the template directory path to the TEMPLATE_DIRS variable
> in settings.py and restart the server.  
>
> After several hours of trying things suggested in different forums on this 
> topic, I decided to just rename the original base_site.html in 
> django/contrib/admin/templates/admin and create a blank "blank_site.html".  
>
> After doing this, one would expect to get a blank page if the templates in 
> TEMPLATE_DIRS were not found.  However, I am getting the same "Django 
> administration" page.  Also, I did go into the manage.py shell and check 
> TEMPLATE_DIRS: it is set to the correct directory.  I am starting to think 
> this is some kind of Django server cache issue (tried clearing browser 
> cache).
>
> I can see that many new-comers to Django have come across this issue and 
> none of the suggestions for these users seem to work.  However, I have 
> never seen anyone mention a cache being the issue.  Does anyone have any 
> suggestions?
>

-- 
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/1e222d27-64fc-44e3-909a-2668a7f3d1e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: my mysite/templates/admin/base_site.html is ignored (tutorial unclear?)

2015-03-10 Thread Collin Anderson
Hi,

To be clear, you should have this setting:
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

and in your mysite/templates/admin/base_site.html you should have something 
like:

{% block branding %}
Polls 
Administration
{% endblock %}

Does that all look right?

Thanks,
Collin

On Sunday, March 8, 2015 at 3:09:19 PM UTC-4, Bryan Arguello wrote:
>
> Have you solved this problem, Andreas?  I am having the same issue and 
> have done
> everything that the tutorial described as well as everything that people 
> on this thread
> have suggested.
>
> On Sunday, November 16, 2014 at 12:15:59 PM UTC-6, Andreas Ka wrote:
>>
>> I am working through 
>> https://docs.djangoproject.com/en/1.7/intro/tutorial02 
>> 
>> so far all went fine - but now *templates changes just don't work.*
>>
>>
>>
>> I think there must be a flaw in that tutorial, something missing,
>> or something different in django 1.7.1 ?
>>
>> https://docs.djangoproject.com/en/1.7/intro/tutorial02/#customize-the-admin-look-and-feel
>>
>>
>> my versions:
>>
>> python -c "import django; print(django.get_version())"
>> 1.7.1
>>
>> python --version
>> Python 2.7.3
>>
>>
>>
>> *SYMPTOM:*
>>
>> my changes in 
>> mysite/templates/admin/base_site.html   
>> are simply ignored.
>>
>>
>>
>> These are my files:
>>
>> mysite# tree
>> .
>> ├── db.sqlite3
>> ├── manage.py
>> ├── mysite
>> │   ├── __init__.py
>> │   ├── settings.py
>> │   ├── urls.py
>> │   └── wsgi.py
>> ├── polls
>> │   ├── admin.py
>> │   ├── __init__.py
>> │   ├── migrations
>> │   │   ├── 0001_initial.py
>> │   │   └── __init__.py
>> │   ├── models.py
>> │   ├── tests.py
>> │   └── views.py
>> └── templates
>> └── admin
>> └── base_site.html
>>
>>
>>
>> mysite/settings.py:
>>
>> TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
>>
>>
>> *Whatever I do, the page*
>> *http://myserver:8000/admin/polls/question/ 
>> *
>> *still keeps the old title 'Django administration'*
>>
>>
>> I want to understand how templates work, because I need them for my real 
>> project.
>>
>> Thanks a lot!
>>
>>
>>

-- 
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/74b79ef9-b70a-4a1c-956e-9364378c12bd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Accessing Django models using DJANGO_SETTINGS_MODULE

2015-03-10 Thread Collin Anderson
Hi,

Hmm... maybe try ChatRoom.objects.all().all() ? :)

If you run this, you can see if it's actually running sql or not:
import logging; logging.basicConfig(level=logging.DEBUG)

Are you sure you're using the same database? :)

Collin

On Sunday, March 8, 2015 at 8:41:30 AM UTC-4, Dheerendra Rathor wrote:
>
> I've a django project and I've few models like ChatRoom and Chat etc
>
> I'm accessing the ChatRooms from commandline using ipython as follow
> In [1]: import os
>
> In [2]: os.environ['DJANGO_SETTINGS_MODULE'] = 'chat_project.settings'
>
> In [3]: from chat.models import Chat, ChatRoom
>
> In [4]: ChatRoom.objects.all()
> Out[4]: [, , , 
> , , ,  07>, , , ,  Lab 15>, ]
>
> Now, I'm adding more ChatRooms through web interface - Lab 17, Lab 18 and 
> deleting Lab 10
> Now the new output of 
> In [5]: ChatRoom.objects.all()
>
> The output is still the same
> Out[5]: [, , , 
> , , ,  07>, , , ,  Lab 15>, ]
>
> the webinterface is running as wsgi application on gunicorn server. 
>
> I think the output on command line is not changed because the django 
> default model manager is accessing the objects from cache and not from 
> database itself. Is there anyway I can get the updated models here on 
> command line? Or can I force django ORM to fetch objects from database and 
> not from cache?
>
>

-- 
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/737ec68b-d2eb-46be-a86a-8703f665e4bc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Existing database - new project

2015-03-10 Thread Collin Anderson
Hi,

inspectdb makes step #1 much easier.

If you're not planning on removing some of the columns or restructuring 
things, I'd recommend #1.

Collin 

On Saturday, March 7, 2015 at 9:31:24 AM UTC-5, Derek wrote:
>
> I have taken route 1 before; its a bit more messy because you may have to 
> explicitly map your desired model names to the actual column names.  You 
> also face the issue of dealing with primary keys. 
>
> If you have the choice, and the current database is not in use anymore, I 
> would create a new one, using Django conventions (such as an auto-increment 
> primary key, with "unique_together" constraints) and then import the 
> existing data.  This has the added benefit of allowing you to validate the 
> existing data and ensure that you start with a 'clean' data set. 
>
> HTH
> Derek
>
> On Friday, 6 March 2015 23:39:33 UTC+2, Robert Daniels wrote:
>>
>> I understand it is possible to use an existing database on a new Django 
>> project. 
>>
>> As I see it, I have 2 choices.
>>
>> 1 - Use the existing database and deal with it in that fashion.
>>
>> or
>>
>> 2 - Create a new project to store the same type of data as if there were 
>> no existing database, Then write a separate export-import script to move 
>> the data from the existing db to the new structure. 
>>
>> Wondering if anyone has gone through the "good" and "bad" of each of 
>> these. I have about 100,000 records in the database, but moving the data 
>> across should not be that difficult as its a pretty flat model
>>
>

-- 
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/374949d8-09a9-4dcc-bdde-76dcd1d9f795%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django OperationalError

2015-03-10 Thread Collin Anderson
Hi Petar,

I'm actually not sure why you want to call sqlflush. If you're trying to 
clear out the database, you may need to delete the migrations table 
manually, but it just might be simpler to delete the either database and 
re-create it, rather than the individual tables.

Collin

On Friday, March 6, 2015 at 11:24:19 PM UTC-5, Petar Pilipovic wrote:
>
> Hello Collin,
> No the problem is, i have tried to drop mine migrations whit python manage 
> sqlflush, then I have recreate the db whit 
> python manage.py migrate.
> Here this is the all operation whit python manage sqlflush, syncdb, 
> migrate <http://ur1.ca/jv371>. I have notice that there was no migration 
> to apply at the end, and the error is still there.
> Is there something else I can do, or how can I approach this differently.
> Best
> Petar
>
> On Fri, Mar 6, 2015 at 11:21 PM, Collin Anderson <cmawe...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> The problem is that django_session doesn't exist in your database. Either 
>> it was never created or it was created and then later deleted.
>>
>> Does running manage.py migrate re-create it?
>>
>> Collin
>>
>> On Monday, March 2, 2015 at 11:36:51 PM UTC-5, Petar Pilipovic wrote:
>>>
>>> Hello James, sorry for not uploading mine answer on this mater, I was 
>>> busy whit something else this day, ok now back to mine Operational Error I 
>>> have got.
>>> I tried to google some solution to this problem had no luck, and I did 
>>> what have you told me.
>>> I heave done some 
>>> python manage.py sqlflush
>>>
>>> and that has gave me this output: 
>>>
>>> (django17)04:20 ~/mineDjango$ python manage.py sqlflush BEGIN;DELETE 
>>> FROM "django_admin_log";DELETE FROM "auth_permission";DELETE FROM 
>>> "auth_group";DELETE FROM "auth_group_permissions";DELETE FROM 
>>> "django_session";DELETE FROM "auth_user_groups";DELETE FROM 
>>> "auth_user_user_permissions";DELETE FROM "account_emailaddress";DELETE 
>>> FROM "django_site";DELETE FROM "profiles_profile";DELETE FROM 
>>> "auth_user";DELETE FROM "profiles_userstripe";DELETE FROM 
>>> "account_emailconfirmation";DELETE FROM "django_content_type";COMMIT;
>>>
>>> Then I have done 
>>> python manage.py syncdb python manage.py migrate
>>>
>>> Output of mine recreating tables are this:
>>> (django17)04:20 ~/mineDjango$ python manage.py syncdbOperations to 
>>> perform: Synchronize unmigrated apps: allauth, crispy_forms Apply all 
>>> migrations: account, sessions, admin, sites, profiles, contenttypes, 
>>> authSynchronizing apps without migrations: Creating tables... 
>>> Installing custom SQL... Installing indexes...Running migrations: No 
>>> migrations to apply.(django17)04:20 ~/mineDjango$ python manage.py 
>>> migrateOperations to perform: Synchronize unmigrated apps: allauth, 
>>> crispy_forms Apply all migrations: account, sessions, admin, sites, 
>>> profiles, contenttypes, authSynchronizing apps without migrations: 
>>> Creating tables... Installing custom SQL... Installing indexes...Running 
>>> migrations: No migrations to apply.
>>> Basically I have had no changes in mine attempt to drop and recreate 
>>> tables in mine application.
>>> The error is still there.
>>> Error:
>>> Environment:
>>>
>>>
>>>
>>>
>>> Request Method: GET
>>> Request URL: http://copser.pythonanywhere.com/
>>>
>>>
>>> Django Version: 1.7.2
>>> Python Version: 2.7.6
>>> Installed Applications:
>>> ('django.contrib.admin',
>>>  'django.contrib.auth',
>>>  'django.contrib.contenttypes',
>>>  'django.contrib.sessions',
>>>  'django.contrib.messages',
>>>  'django.contrib.staticfiles',
>>>  'profiles',
>>>  'crispy_forms',
>>>  'django.contrib.sites',
>>>  'allauth',
>>>  'allauth.account',
>>>  'stripe')
>>> Installed Middleware:
>>> ('django.contrib.sessions.middleware.SessionMiddleware',
>>>  'django.middleware.common.CommonMiddleware',
>>>  'django.middleware.csrf.CsrfViewMiddleware',
>>>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>>>  'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
>>>  'django.contrib.messages.middleware.MessageMiddleware',
>>>  'django.middlewa

Re: Django Admin Page

2015-03-06 Thread Collin Anderson
Hi,

That's odd. Maybe try updating django? It looks like you're using 1.8 
pre-alpha from 3 months ago.

Collin

On Friday, February 20, 2015 at 1:40:03 AM UTC-5, Tim Co wrote:
>
> Hello,
>
> We are trying to run a local development server for our django python app. 
> We are able to connect to our localhost index and get the "It Worked!" 
> Dango page. However when we try to connect to 127.0.0.1/admin/ we are 
> getting an error that the server dropped the connection. Here is the log 
> for the django project:
>
> Exception happened during processing of request from ('130.191.204.231', 
> 62070)
> Traceback (most recent call last):
>   File "/System/Library/Frameworks/Python.framework/Versions/2.7/
> lib/python2.7/SocketServer.py", line 593, in process_request_thread
> self.finish_request(request, client_address)
>   File "/System/Library/Frameworks/Python.framework/Versions/2.7/
> lib/python2.7/SocketServer.py", line 334, in finish_request
> self.RequestHandlerClass(request, client_address, self)
>   File "/Library/Python/2.7/site-packages/Django-1.8.
> dev20141212211410-py2.7.egg/django/core/servers/basehttp.py", line 101, 
> in __init__
> super(WSGIRequestHandler, self).__init__(*args, **kwargs)
>   File "/System/Library/Frameworks/Python.framework/Versions/2.7/
> lib/python2.7/SocketServer.py", line 649, in __init__
> self.handle()
>   File "/Library/Python/2.7/site-packages/Django-1.8.
> dev20141212211410-py2.7.egg/django/core/servers/basehttp.py", line 173, 
> in handle
> handler.run(self.server.get_app())
>   File "/System/Library/Frameworks/Python.framework/Versions/2.7/
> lib/python2.7/wsgiref/handlers.py", line 92, in run
> self.close()
>   File "/System/Library/Frameworks/Python.framework/Versions/2.7/
> lib/python2.7/wsgiref/simple_server.py", line 33, in close
> self.status.split(' ',1)[0], self.bytes_sent
> AttributeError: 'NoneType' object has no attribute 'split'
>
> 
> ///
> Our urls.py file
>
> urls.py
>
> from django.conf.urls import include, url
> from django.contrib import admin
>
> admin.autodiscover()
>
> urlpatterns = [
> # Examples:
> # url(r'^$', 'mysite.views.home', name='home'),
> # url(r'^blog/', include('blog.urls')),
> url(r'^admin/', include(admin.site.urls)),
> ]
>
>
> 
> ///
> settings.py
>
>
> # Application definition
>
> INSTALLED_APPS = (
> 'django.contrib.admin',
> 'django.contrib.auth',
> 'django.contrib.contenttypes',
> 'django.contrib.sessions',
> 'django.contrib.messages',
> 'django.contrib.staticfiles',
> 'trainstar',
> )
>
> MIDDLEWARE_CLASSES = (
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> 'django.middleware.security.SecurityMiddleware',
> )
>
> TEMPLATE_CONTEXT_PROCESSORS = (
> "django.contrib.auth.context_processors.auth",
> "django.core.context_processors.debug",
> "django.core.context_processors.i18n",
> "django.core.context_processors.media",
> "django.core.context_processors.static",
> "django.core.context_processors.tz",
> 'django.contrib.messages.context_processors.messages'
> )
>
>
> ROOT_URLCONF = 'mysite.urls'
>
> WSGI_APPLICATION = 'mysite.wsgi.application'
>
>
> Please advise. I've exhausted Google/stackoverflow for possible fixes to 
> of no avail. 
>

-- 
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/e15cb4e6-bf0a-453b-8262-d0a9a5b9312f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: how pass get parameter django bootstrap pagination

2015-03-06 Thread Collin Anderson
Hi,

If you have the request context processor installed, you can do this:

{% bootstrap_paginate object_list range=request.GET.range %}

Collin

On Thursday, March 5, 2015 at 4:35:33 AM UTC-5, SHINTO PETER wrote:
>
>  {% load bootstrap_pagination %}
>   {% bootstrap_paginate object_list range=10 %}
>

-- 
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/c135d389-2bac-46b1-8816-287f35fa20cd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: getting tuples from http request.GET

2015-03-06 Thread Collin Anderson
Hi,

Normally query arguments are separated by &. If you're able to send the 
data like this:

https://mydesktop.com/validator?hostname1=host1.example.com=ca=2.2.2.2=host2.example.com=wa=3.3.3.3

Then you could do something like:

data = []
i = 0
while True:
i += 1
try:
data.append((request.GET['hostname%s' % i], request.GET['location%s' 
% i], request.GET['ip%s' % i]))
except KeyError:
break

Collin

On Wednesday, March 4, 2015 at 7:57:17 PM UTC-5, Sunil Sawant wrote:

> Hi Guys,
>
> Pretty new to Django, but used it blindly and works wonders. But here is a 
> situation I am blocked at now for a new project
>
> I request.GET the following URL
>
>
> https://mydesktop.com/validator?hostname1=host1.example.com,location1=ca,ip1=2.2.2.2,hostname2=host2.example.com,location2=wa,ip2=3.3.3.3
>
> Am using request.GET I want to get the output in a tuple or hash form as:
>
> [{host1.example.com:[ca,2.2.2.2]},{host2.example.com:[wa,3.3.3.3]}]
>
>
>
> Once I have this data I can process it further.
> Please help
>
>
>
>
>
>

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


Re: Rolling back to practice on old bugs

2015-03-06 Thread Collin Anderson
Hi,

I always type: PYTHONPATH=.. ./runtests.py

Collin

On Wednesday, March 4, 2015 at 4:30:54 PM UTC-5, Javis Sullivan wrote:
>
> I am following this tutorial here 
>  "Writing your 
> first Django patch" and while it directs me to rollback to this 
> 39f5bc7fc3a4bb43ed8a1358b17fe0521a1a63ac 
> 
>  commit, 
> when I do so I am not able to run the runtests.py script. I guess the 
> directory structure or something has changed along the way, I assume. As I 
> am getting the error below:
>
> Traceback (most recent call last):
>   File "runtests.py", line 327, in 
> options.failfast, args)
>   File "runtests.py", line 153, django_tests
> state = setup(verbosity, test_labels)
>   File "runtests.py", line 111, in setup
> from django.db.models.loading import get_apps, load_app
> ImportError: No module named 'django.db.models.loading'
>
>
>
> I poked around to see if I could find the loadings module but it is not 
> longer there. Should I just practice on a recent bug? Because runtests.py 
> does fine when the git head is located at the most recent commit. 
>

-- 
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/1c17d272-ab2f-4f46-941d-d936a826ff33%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Populating Django app db with JSON data

2015-03-06 Thread Collin Anderson
Hi Sandeep,

A snapshot (or at least a diff from the previous one) is stored when you 
run makemigrations.

Collin

On Wednesday, March 4, 2015 at 2:15:41 PM UTC-5, Murthy Sandeep wrote:
>
> Hi 
>
> thanks for the info. 
>
> The docs also say that RunPython runs “custom Python code 
> in a historical context”.  What does that mean exactly?  It seems 
> related to the apps and schema_editor arguments passed to 
> the custom method that will be called by RunPython - is this something 
> like a snapshot of the app model that is stored when I do `python 
> manage.py migrate`? 
>
> Sandeep 
>
>
> > On 2 Mar 2015, at 19:37, aRkadeFR  
> wrote: 
> > 
> > Hello, 
> > 
> > Indeed, the data migration is the best way. Check out 
> > the documentation here: 
> > 
> https://docs.djangoproject.com/en/1.7/ref/migration-operations/#django.db.migrations.operations.RunPython
>  
> > 
> > You write your function that will be called by the RunPython 
> > and will load your JSON. 
> > Migration are ordered, your first migration will create the 
> > tables and the second (your data migration) will load your 
> > JSON. 
> > 
> > To create an empty migration: 
> > ./manage.py makemigrations  --empty 
> > 
> > You can rename to a useful descriptive name the migration 
> > file. 
> > 
> > Have a good one 
> > 
> > 
> > On 03/02/2015 08:16 AM, Sandeep Murthy wrote: 
> >> Hi 
> >> 
> >> I've tried to get the answer to this question (which is a bit 
> open-ended) on stackoverflow without much success, which 
> >> is basically this: what is the recommended approach to populating a 
> pre-existing Django app database table (generated 
> >> from a model and which is currently empty) with JSON data? 
> >> 
> >> There seem to be several alternatives given in the Django documentation 
> (Django 1.7 manual) which include (1) fixtures, 
> >> (2) SQL scripts, (3) data migrations.  Of these I am a bit confused by 
> the advice in the manual which suggests that (1) 
> >> and (2) are only useful for loading initial data.  That's not what I 
> want to do.  The data that the app needs is going to be 
> >> persistent and permanent because the app is intended to be a web query 
> tool for a large dataset that is currently in the 
> >> form of several JSON files, each containing on average thousands of 
> JSON objects, each object representing an entry 
> >> corresponding to a table entry in a relational db.  The data is not 
> going to be re-loaded or change after entry, and there 
> >> is no user facility for changing the data. 
> >> 
> >> The table has been created using the makemigrations and migrate tools, 
> but is empty.  I just need to populate the 
> >> table with the JSON data.  It seems that I need to write a custom data 
> migration script that will insert the data into the 
> >> table via the interpreter, and then I need to run python manage.py 
> migrate.  Is this the case, and if so, are there 
> >> are examples that I could use? 
> >> 
> >> Thanks in advance for any suggestions. 
> >> 
> >> SM 
> >> -- 
> >> You received this message because you are subscribed to the Google 
> Groups "Django users" group. 
> >> To unsubscribe from this group and stop receiving emails from it, send 
> an email to django-users...@googlegroups.com . 
> >> To post to this group, send email to django...@googlegroups.com 
> . 
> >> Visit this group at http://groups.google.com/group/django-users. 
> >> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/db5919c5-ace4-4556-b90e-aa47baa26552%40googlegroups.com.
>  
>
> >> For more options, visit https://groups.google.com/d/optout. 
> > 
> > 
> > -- 
> > You received this message because you are subscribed to the Google 
> Groups "Django users" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> an email to django-users...@googlegroups.com . 
> > To post to this group, send email to django...@googlegroups.com 
> . 
> > Visit this group at http://groups.google.com/group/django-users. 
> > To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/54F42164.6040505%40arkade.info.
>  
>
> > For more options, visit https://groups.google.com/d/optout. 
>
>

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


Re: Django(1.7) admin - separate user-profile section

2015-03-06 Thread Collin Anderson
Hi,

If you just add a custom __str__ (or __unicode__ on py2) it might do what 
you want.

def __str__(self):
return str(user)

Otherwise, in UserTokenAdmin, set list_display = ['user']

Collin

On Wednesday, March 4, 2015 at 2:15:32 PM UTC-5, Flemming Hansen wrote:
>
> Hi all,
>
> I need to make a `passwordless` token system, and want to have a "Home › 
> Passwordless › User tokens" in the Admin section. For the "User tokens" 
> `list_display` I need all the "Users". (I do _not_ want to display the 
> token information on the regular "User"-admin as just an extended 
> "profile".) 
>
> Any ideas on how to go about doing this?
>
> So far I have this skeleton in `passwordless/model.py`, but I probably 
> need some magic in `passwordless/admin.py` to list all the users with links 
> to a custom token-manager form with custom widgets (create-token button, 
> delete token button etc)...
>
> from django.db import models
> import jwt
>
> class UserTokens(models.Model):
> class Meta:
> verbose_name = "User tokens"
> verbose_name_plural = "User tokens"
>
> user = models.OneToOneField(User)
>
>
> class TokenBase(models.Model):
> class Meta:
> abstract = True
>
> token = models.CharField(max_length=1000)
> created_ts = models.DateTimeField('Date created')
> expires_ts = models.DateTimeField('Date expired')
>
> def __str__(self):
> return self.user.email
>
>
> class AuthenticateToken(TokenBase):
> manager = models.OneToOneField(UserTokens)
>
> def validate(self, token):
> pass
>
>
> class AuthorizeToken(TokenBase):   
> manager = models.ForeignKey(UserTokens)
> revoked_ts = models.DateTimeField('Date revoked')
>
> def validate(self, token):
> pass  
>
>
>

-- 
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/783e5939-eb30-4f5d-ab9c-29002a5523b4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 1.7 tutorial part 4, url

2015-03-06 Thread Collin Anderson
Hi,

That seems strange. The error says that there's no question with id=1. Are 
you sure there's a question with id=1?

The ending slash seems important to me. I don't know why it would work 
without it.

Collin

On Wednesday, March 4, 2015 at 2:15:32 PM UTC-5, Daniel Altschuler wrote:
>
> I ran into the following problem with the tutorial.
>
> When I'm at http://127.0.0.1:8000/polls/1/, I get the expected page:
>
> What's up? Not much
>  The sky
>
>
> However when I try to vote I get the error 
>
> Page not found (404)Request Method:POSTRequest URL:
> http://127.0.0.1:8000/polls/1/vote/
>
> No Question matches the given query.
>
> You're seeing this error because you have DEBUG = True in your Django 
> settings file. Change that to False, and Django will display a standard 
> 404 page.
>
> After some time I found that something is wrong with the urls. My 
> polls/urls.py file was:
>
> -
> from django.conf.urls import patterns, url
>
> from polls import views
>
> urlpatterns = patterns('',
> # ex: /polls/
> url(r'^$', views.index, name='index'),
> # ex: /polls/5/
> url(r'^(?P\d+)/$', views.detail, name='detail'),
>
> url(r'^(?P\S+)/$', views.search, name='search'),
> # ex: /polls/5/results/
> url(r'^(?P\d+)/results/$', views.results, name='results'),
> # ex: /polls/5/vote/
> url(r'^(?P\d+)/vote/$', views.vote, name='vote'),
> )
> --
>
> If I remove the "/" after "vote", then everything works. I had the same 
> error when attempting to view the results, so I also
> removed the "/" after results. My urls.py now looks like
>
> ...
> # ex: /polls/5/results
> url(r'^(?P\d+)/results$', views.results, name='results'),
> # ex: /polls/5/vote
> url(r'^(?P\d+)/vote$', views.vote, name='vote'),
>...
>
> Can someone explain me what is going on? thanks.
>
> Note that the file mysite/urls.py is:
>
> --
> from django.conf.urls import patterns, url
>
> from polls import views
>
> urlpatterns = patterns('',
> # ex: /polls/
> url(r'^$', views.index, name='index'),
> # ex: /polls/5/
> url(r'^(?P\d+)/$', views.detail, name='detail'),
>
> url(r'^(?P\S+)/$', views.search, name='search'),
> # ex: /polls/5/results
> url(r'^(?P\d+)/results$', views.results, name='results'),
> # ex: /polls/5/vote
> url(r'^(?P\d+)/vote$', views.vote, name='vote'),
> )
> 
>

-- 
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/db705c9f-f8a1-46e6-add8-a637671a603e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Fatal Error in initializing sys standard streams

2015-03-06 Thread Collin Anderson
Hi,

That doesn't look good :)

Maybe try reinstalling python.

Collin

On Wednesday, March 4, 2015 at 11:11:12 AM UTC-5, sriraag paawan wrote:
>
>
> Hello Guys,
>
> I am new to Django.. i am using Django 1.7.4 and Python 3.4
>
> I was about to complete Django tutorial part-5 about tests but a Fatal 
> Error caused me trouble.. I am attaching an image file which contains 
> detail view of my problem... Please anyone could figure it out and solve 
> it..
>
> Thank You in Advance
>
>
> 
>
>

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


Re: Can't make ManyToMany form fields hidden

2015-03-06 Thread Collin Anderson
https://code.djangoproject.com/ticket/24453

On Wednesday, March 4, 2015 at 12:40:40 AM UTC-5, Eric Abrahamsen wrote:
>
> Hi, 
>
> I'm making some heavily customized model formsets, to encourage my users 
> to input data. Mostly that involves cutting down the number of huge 
> drop-down menus they have to go surfing through. 
>
> So I have a model like this: 
>
> class Work(models.Model): 
>   authors = models.ManyToManyField(Author,blank=True,related_name="works") 
>
> I first present them with a pre-query form, to choose an Author, then 
> give them a Work modelformset with the "authors" field pre-filled with 
> that author. So the initial data sort of looks like: 
>
> init["authors"] = [pre_query.cleaned_data["authors"]] # must be a list 
>
> for i in range(0, number_of_additional_forms): 
>   initial.append(init) 
>
> formset = WorkFormSet(queryset=Work.objects.none(), initial=initial) 
>
> Nothing unusual there. Now I want to make the "authors" field hidden. 
> This is both to reassure my users, and to reduce the size of the page -- 
> these are really long dropdowns. 
>
> Adding the hidden widget to the "authors" field, however, gives me this 
> validation error: 
>
> (Hidden field authors) Enter a list of values. 
>
> The form input field looks like this: 
>
>  value="[37L]" /> 
>
> Looks like a list of values to me, but maybe it's not getting read that 
> way. 
>
> In the meantime it's not a disaster if the monster "authors" dropdown is 
> visible for each of my Work forms, but it would be really nice to 
> eventually get it hidden. 
>
> In the past I did this by manually *removing* fields from the forms, and 
> adding the values in during the POST/save process, but that always felt 
> bad to me. 
>
> Thanks! 
> Eric 
>
>

-- 
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/53c18174-9439-462d-8a8e-34783a065bcf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django OperationalError

2015-03-06 Thread Collin Anderson
Hi,

The problem is that django_session doesn't exist in your database. Either 
it was never created or it was created and then later deleted.

Does running manage.py migrate re-create it?

Collin

On Monday, March 2, 2015 at 11:36:51 PM UTC-5, Petar Pilipovic wrote:
>
> Hello James, sorry for not uploading mine answer on this mater, I was busy 
> whit something else this day, ok now back to mine Operational Error I have 
> got.
> I tried to google some solution to this problem had no luck, and I did 
> what have you told me.
> I heave done some 
> python manage.py sqlflush
>
> and that has gave me this output: 
>
> (django17)04:20 ~/mineDjango$ python manage.py sqlflush BEGIN;DELETE FROM 
> "django_admin_log";DELETE FROM "auth_permission";DELETE FROM "auth_group";
> DELETE FROM "auth_group_permissions";DELETE FROM "django_session";DELETE 
> FROM "auth_user_groups";DELETE FROM "auth_user_user_permissions";DELETE 
> FROM "account_emailaddress";DELETE FROM "django_site";DELETE FROM 
> "profiles_profile";DELETE FROM "auth_user";DELETE FROM 
> "profiles_userstripe";DELETE FROM "account_emailconfirmation";DELETE FROM 
> "django_content_type";COMMIT;
>
> Then I have done 
> python manage.py syncdb python manage.py migrate
>
> Output of mine recreating tables are this:
> (django17)04:20 ~/mineDjango$ python manage.py syncdbOperations to 
> perform: Synchronize unmigrated apps: allauth, crispy_forms Apply all 
> migrations: account, sessions, admin, sites, profiles, contenttypes, 
> authSynchronizing 
> apps without migrations: Creating tables... Installing custom SQL... 
> Installing indexes...Running migrations: No migrations to 
> apply.(django17)04:20 
> ~/mineDjango$ python manage.py migrateOperations to perform: Synchronize 
> unmigrated apps: allauth, crispy_forms Apply all migrations: account, 
> sessions, admin, sites, profiles, contenttypes, authSynchronizing apps 
> without migrations: Creating tables... Installing custom SQL... 
> Installing indexes...Running migrations: No migrations to apply.
> Basically I have had no changes in mine attempt to drop and recreate 
> tables in mine application.
> The error is still there.
> Error:
> Environment:
>
>
>
>
> Request Method: GET
> Request URL: http://copser.pythonanywhere.com/
>
>
> Django Version: 1.7.2
> Python Version: 2.7.6
> Installed Applications:
> ('django.contrib.admin',
>  'django.contrib.auth',
>  'django.contrib.contenttypes',
>  'django.contrib.sessions',
>  'django.contrib.messages',
>  'django.contrib.staticfiles',
>  'profiles',
>  'crispy_forms',
>  'django.contrib.sites',
>  'allauth',
>  'allauth.account',
>  'stripe')
> Installed Middleware:
> ('django.contrib.sessions.middleware.SessionMiddleware',
>  'django.middleware.common.CommonMiddleware',
>  'django.middleware.csrf.CsrfViewMiddleware',
>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>  'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
>  'django.contrib.messages.middleware.MessageMiddleware',
>  'django.middleware.clickjacking.XFrameOptionsMiddleware')
>
>
>
>
> Template error:
> In template /home/copser/static/templates/home.html, error at line 40
>no such table: django_session
>30 :  
>
>
>
>
>31 : {% block content %}
>
>
>
>
>32 :  
>
>
>
>
>33 : 
>
>
>
>
>34 :   
>
>
>
>
>35 : 
>
>
>
>
>36 : 
>
>
>
>
>37 :  {#   src="{% static 'img/07.jpg' %}"/>  #}
>
>
>
>
>38 :
>
>
>
>
>39 : 
>
>
>
>
>40 :  {% if request.user.is_authenticated %} 
>
>
>
>
>41 : Hello {{ request.user }}
>
>
>
>
>42 : {% else %}
>
>
>
>
>43 :   
>
>
>
>
>44 :  value="sczg1f8U4tWQRa8kgNJC1QsSBKAD9Lvw"> {% csrf_token %}
>
>
>
>
>45 :  for="id_login" class="control-label  requiredField">
>
>
>
>
>46 : Login class="asteriskField">* autofocus="autofocus" class="textinput textInput form-control" 
> id="id_login" name="login" placeholder="Username or e-mail" type="text"> 
>  for="id_password" class="control-label  requiredField">
>
>
>
>
>47 : Password class="asteriskField">* class="textinput textInput form-control" id="id_password" name="password" 
> placeholder="Password" type="password">  class="form-group"> for="id_remember" class=""> id="id_remember" name="remember" type="checkbox">
>
>
>
>
>48 : Remember Me
>
>
>
>
>49 : 
>
>
>
>
>50 : 
>
>
>
>
> Traceback:
> File 
> "/home/copser/.virtualenvs/django17/local/lib/python2.7/site-packages/django/core/handlers/base.py"
>  
> in get_response
>   111. response = wrapped_callback(request, 
> *callback_args, **callback_kwargs)
> File "/home/copser/mineDjango/profiles/views.py" in home
>   7. return render(request, template, context)
> File 
> 

Re: django Search page

2015-03-06 Thread Collin Anderson
Hi,

You'll need to use javascript for that.

Collin

On Monday, March 2, 2015 at 2:27:35 AM UTC-5, Sabeen Sha wrote:
>
>  which is the best way to implement the following::
> i will be having a text box and a Add button
>
> Along with a table below it containing headers class 
> AssesmentBuildingDetails(models.Model): 
>
>
>  numbuildingid1 = models.CharField(max_length=14,unique=True) 
>
> numbuildingid2 = models.CharField(max_length=7,primary_key=True) 
>
> previous_year = models.CharField(max_length=4, blank=True) 
>
> previous_year_wardname = models.CharField(max_length=100,blank=True, 
> null=True) 
>
> previous_doorno1 = models.CharField(max_length=4,blank=True, null=True) 
>
> previous_doorno2 = models.CharField(max_length=10,blank=True, null=True) 
>
> current_year = models.CharField(max_length=4, blank=True) 
>
> current_year_wardname = models.CharField(max_length=100,blank=True, 
> null=True) 
>
> current_doorno1 = models.CharField(max_length=10,blank=True, null=True) 
>
> current_doorno2 = models.CharField(max_length=10,blank=True, null=True) 
>
> buildingusage = models.CharField(max_length=500,blank=True, null=True) 
>
> ownernameaddressmal = models.CharField(max_length=500,blank=True, 
> null=True) 
>
> ownernameaddresseng = models.CharField(max_length=500,blank=True, 
> null=True) 
>
> plintaarea = models.DecimalField(max_digits=7, 
> decimal_places=2,blank=True, null=True) 
>
> class Meta: 
>
> db_table = 'assesment_building_details' 
>
>
>  
> my logic is to take the numbuildingid2 as input from the text box and when 
> i press enter either on the text field or click the add button it should 
> search through the database
> and add the details to the table without refreshing the whole page. and 
> the clear the textfield and focus on it.
>  It will give proper error msg if the numbuildingid2 is not found
>
> please help how and which is the best way to implement this... 
>
> thanks
>
>
>  

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


Re: [1.8] MultiHost with template dir per Host

2015-03-06 Thread Collin Anderson
Hi,

You might need to modify the template engine directly.

Collin

On Sunday, March 1, 2015 at 6:31:57 PM UTC-5, Neyoui wrote:
>
> Hi,
>
> I had create a middleware, that is able to change the template directory 
> per host on the fly.
> But it stopped working since I upgraed to Django 1.8 and I tried to fix it.
>
> My problem is:
> If I visit domain1.tld, all works fine. Django loads the templates from 
> the right directory. (/path/domain1.tld/templates/)
> But if I visit now domain2.tld, Django tried to load the template from the 
> domain1.tld directory /path/domain1.tld/templates/ and not from 
> /path/domain2.tld/templates/.
> The debug messages shows me, that the middleware overrides the template 
> path successfully.
>
> Maybe someone can help me to fix it.
>
> Details:
> Django version: 1.8b1
> Python: 3.4
>
> If you need some other information, just ask for it.
>
> - settings.py
>
> MIDDLEWARE_CLASSES = (
> 'core.middleware.MultiHostMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.locale.LocaleMiddleware',
> 'django.middleware.common.CommonMiddleware',
> ...
> )
>
>
> TEMPLATES = [
> {
> 'BACKEND': 'django.template.backends.django.DjangoTemplates',
> 'DIRS': [],
> 'OPTIONS': {
> 'context_processors': [
> 'django.contrib.auth.context_processors.auth',
> 'django.template.context_processors.debug',
> 'django.template.context_processors.i18n',
> 'django.template.context_processors.media',
> 'django.template.context_processors.static',
> 'django.template.context_processors.tz',
> 'django.contrib.messages.context_processors.messages',
> ],
> 'loaders': [
> 'django.template.loaders.filesystem.Loader',
> 'django.template.loaders.app_directories.Loader',
> ],
> 'debug': True
> },
> },
> ]
>
>
> ROOT_URLCONF = 'core.urls'
>
> HOST_MIDDLEWARE_TEMPLATE_DIRS = {
>"domain1.tld": BASE_DIR + "/domain1.tld/templates/",
>"domain2.tld": BASE_DIR + "/domain2.tld/templates/",
> }
>
> HOST_MIDDLEWARE_URLCONF_MAP = {
>"domain1.tld": "domain1.urls",
>"domain2.tld": "domain2.urls",
> }
>
>
> INSTALLED_APPS = (
> 'django.contrib.admin',
> 'django.contrib.auth',
> 'django.contrib.contenttypes',
> 'django.contrib.sessions',
> 'django.contrib.messages',
> 'core',
> 'domain1',
> 'domain2',
> )
>
>
> - middleware.py
>
> from django.conf import settings
> from django.utils.cache import patch_vary_headers
>
>
> class MultiHostMiddleware:
>
> def get_settings(self, request):
>
> host = request.META["HTTP_HOST"]
> host_port = host.split(':')
>
> if len(host_port) == 2:
> host = host_port[0]
>
> if host in settings.HOST_MIDDLEWARE_URLCONF_MAP:
>
> urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
> template_dirs = settings.HOST_MIDDLEWARE_TEMPLATE_DIRS[host],
>
> else:
> urlconf = settings.ROOT_URLCONF
> template_dirs = None
>
> return urlconf, tuple(template_dirs)
>
> def process_request(self, request):
>
> urlconf, template_dirs = self.get_settings(request)
>
> request.urlconf = urlconf
> settings.TEMPLATES[0]['DIRS'] = template_dirs
>
> def process_response(self, request, response):
>
> if getattr(request, "urlconf", None):
> patch_vary_headers(response, ('Host',))
>
> return response
>
>
>
>
>

-- 
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/7bdc0770-2606-42c1-b581-1293cae44344%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to save user to foreignKey field for new records in modelFormset case?

2015-03-06 Thread Collin Anderson
Hi,

The form doesn't have access to the current user. I'd attach it using the 
view.

Thanks,
Collin

On Wednesday, February 25, 2015 at 3:53:40 AM UTC-5, Mike wrote:
>
> Hi,
> I have created modelFormset using SchoolHistory model and SchoolForm form.
>
> "SchoolFormSet = modelformset_factory(SchoolHistory, form=SchoolForm)"
>
> I get other content from Form, but should save current user to 
> SchoolHistory model too.
>   
> user=models.ForeignKey(User)
> school_name = models.CharField(max_length = 100)
> rating_average = models.PositiveIntegerField()
>
> I am overriding is_valid or save in order to save user field. 
> My question is how to find current user in model or form level as there is 
> no request parameter available ( request.user).
> request was available in Formset level but I cannot save user to each 
> record there, or could I?
>
> -Thanks
>
>
>
>

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


Re: JSON Response

2015-02-20 Thread Collin Anderson
Hi,

It sounds like you click "submit" and then get a page showing the raw json? 
That sounds like it could be a bug in your code. Either the event handler 
is not connected, or there's an error. You could try checking "Preserve 
Log" in the developer console.

Collin

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

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


Re: matplotlib pyplot stop working

2015-02-20 Thread Collin Anderson
Hi,

The freezing could be a memory 
leak. 
http://stackoverflow.com/questions/7125710/matplotlib-errors-result-in-a-memory-leak-how-can-i-free-up-that-memory

Could the image be cached by the browser, does shift+F5 refresh it? The 
easiest way to fix it would be to use a different url/filename every time 
you generate an new image.

Collin

On Thursday, February 19, 2015 at 4:26:16 PM UTC-5, dk wrote:
>
> I am using matplotlib.pyplot to generate a plot image, put it in a temp 
> folder, 
> and then use that to populate a webpage.
>
> the problem is:
> 1) always display the same image,  I all ready deleted the image before 
> creating the new one, 
> I also set pyplot .close()  to close all my figures.
>
> 2) some times everything freeze and stop working.
>
> my suspicions is since django is constantly running keeps the figure in 
> the memory some how.   have any one got issues like this?
> thanks.
>

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


Re: How to host django application in redhat using virtual environment?

2015-02-20 Thread Collin Anderson
Hi,

Here's a tutorial.

https://devops.profitbricks.com/tutorials/deploy-django-with-virtualenv-on-centos-7/

Collin

On Thursday, February 19, 2015 at 8:29:47 AM UTC-5, SHINTO PETER wrote:
>
> How to host django application in redhat using virtual environment?
>

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


Re: Seems like a geodjango bug with multiple databases

2015-02-19 Thread Collin Anderson
Hi,

Interesting. What version of django is this?

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

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

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

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

Collin

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

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


Re: Trouble changing from sqlite3 to postgres

2015-02-19 Thread Collin Anderson
Hi,

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

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

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

Collin

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

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

2015-02-19 Thread Collin Anderson
Hi,

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

Collin

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

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


Re: Can migrated apps depend on unmigrated apps?

2015-02-19 Thread Collin Anderson
Hi Carsten,

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

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

Collin

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

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


Re: Handling FormSet client side with javascript

2015-02-19 Thread Collin Anderson
Hi,

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

Collin

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

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


Re: JsonResponse and Ajax function.

2015-02-19 Thread Collin Anderson
Hi,

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

Collin

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

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


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

2015-02-19 Thread Collin Anderson
Hi,

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

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

Collin

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

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


Re: Custom model field and custom widget

2015-02-19 Thread Collin Anderson
Hi,

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

Collin

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

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


Re: How to detect (daily) User Login when using cookies?

2015-01-30 Thread Collin Anderson
Hi,

If you use a custom authentication backend, you could update it every time 
get_user(request) is called.

Collin

On Wednesday, January 28, 2015 at 4:58:30 AM UTC-5, Tobias Dacoir wrote:
>
> Yes that would be enough. I know in the User Model there is last_login but 
> that is only updated when the User actually logs in. And the signal from 
> django-allauth is also only send when the user uses the login form. The 
> only other alternative I found was to check in every view I have for 
> request.user and store / update datetime.now. But this is quite ugly.
>
>
> On Tuesday, January 27, 2015 at 9:00:15 PM UTC+1, Collin Anderson wrote:
>>
>> Hi,
>>
>> Would it make sense to simply keep a record of when the last time you've 
>> seen the user is?
>>
>> Collin
>>
>> On Friday, January 23, 2015 at 4:43:41 AM UTC-5, Tobias Dacoir wrote:
>>>
>>> I'm using django-allauth and I receive a signal when a user logs in. Now 
>>> I want to store each day the user logs in. However, when the user does not 
>>> logout he can still log in the next day thanks to the cookies. I know that 
>>> I can set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in settings.py. But this 
>>> may annoy some Users. 
>>>
>>> So is there a way to use cookies but still tell if a User has accessed 
>>> the site for the first time today?
>>>
>>

-- 
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/d2d6d493-2c95-43c1-a1ae-c08b9e0fbea4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Reduce start up time for manage.py

2015-01-30 Thread Collin Anderson
Hi,

Many people would recommend against this, but if you can put the imports 
for your heavy 3rd party libraries inside functions and methods, that allow 
them to be loaded only if needed.

I would also recommend in general to simply have fewer libraries and apps 
(easier said than done :)

Also, is it slow only for the first load, or are repeated loads slow too?

I hope you aren't doing database queries or other expensive calls on 
startup.

Try putting this at the top of your manage.py to see more of what's going on

import logging; logging.basicConfig(level=logging.DEBUG)

Collin

If you want some benchmarks, here are some of my websites
221243 function calls (214987 primitive calls) in 0.394 seconds
448659 function calls (437433 primitive calls) in 0.611 seconds 
698349 function calls (687730 primitive calls) in 0.749 seconds

On Wednesday, January 28, 2015 at 4:42:09 AM UTC-5, chj wrote:
>
> Hi,
>
> I'm having a quite large Django project with dozens of apps and many 
> reusable third-party libraries. All the custom management commands (being 
> used with manage.py ) take a long time to be executed, since the 
> start up sequence takes between 3 and 5 seconds. Using the cProfile module 
> I was able to see that quite a lot of function calls are executed and it 
> looks like that every app is loaded, including its libraries and such 
> before the actual management command is executed. Is there any common way 
> to speed that up (e.g. by not loading apps/libraries that are not required 
> for a specific management command)? Django 1.7+ is used on Python 3.4.
>
> Output from `python3 -m cProfile manage.py` (truncated): 1100697 function 
> calls (1064507 primitive calls) in 5.172 seconds
>

-- 
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/0ac3ca3d-78a5-49bf-be96-05bc0017bf40%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Best practice to render the view based on the user

2015-01-30 Thread Collin Anderson
Hi,

Not sure about whether it's a good idea or not. If statements might also be 
good enough.

Be careful with security, but in theory something like this should work:

method_name = 'person' + person.type
method = getattr(self, method_name)
output = method()

Collin

On Wednesday, January 28, 2015 at 12:04:06 AM UTC-5, Karim Gorjux wrote:
>
> Hi! I would like to render views based on the user. I have some differents 
> type of users on my app and I would like to create a class like this one 
> for the view:
>
> class MyView(MyCustomView)  # MyCustomView subclass View 
>
> def __init__(self, *args, **kwargs):
> # common code for all persons
>
> def personA(self):
> # code for personA
>
> def personB(self):
> # code for personA
>
> # 
>
> def personN(self):
> # code for personA
>
> def anyPerson(self)
> # For any user non listed above
> 
>
> Then if the MyView is run, the function based on the user is automatically 
> fired.
>
> My doubts (at the moment):
>
> 1) Do you think is the a good way to face the problem?
>
> 2) I have methods in the models to know what person is logged. How I can 
> automatically load the right function in the class based on the user?
>
> Thank you
>
> -- 
> Karim N. Gorjux
>  

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


Re: django / tastypie - how to exclude a resource attribute from obj_create, but keep it for listing

2015-01-30 Thread Collin Anderson
Hi Eugene,

Would it work to something like this in your obj_create?
bundle.data.pop('blueprint', None)

Collin

On Tuesday, January 27, 2015 at 11:01:56 AM UTC-5, Eugene Goldberg wrote:
>
>   I have the following tastypie resource:
>
>  class WorkloadResource(ModelResource):
> # blueprints = ManyToManyField(Blueprint, 'blueprints')
> blueprint = fields.OneToManyField('catalog.api.BlueprintResource', 
> attribute='blueprint',
>  related_name='workloads', full=True, 
> null=True)
>
> def obj_create(self, bundle, request=None, **kwargs):
> # return super(WorkloadResource, self).obj_create(bundle, request, 
> **kwargs)
> return super(WorkloadResource, self).obj_create(bundle, 
> request=request, **kwargs)
>
> def obj_update(self, bundle, request=None, **kwargs):
>
> workload = Workload.objects.get(id=kwargs.get("pk"))
> workload.description = bundle.data.get("description")
> workload.name = bundle.data.get("name")
> workload.image = bundle.data.get("image")
> workload.flavor = bundle.data.get("flavor")
> workload.save()
>
> def obj_delete(self, bundle, **kwargs):
>
> return super(WorkloadResource, self).obj_delete(bundle)
>
> def determine_format(self, request):
> return 'application/json'
>
> class Meta:
> queryset = Workload.objects.all()
> resource_name = 'workload'
> authorization=Authorization()
> filtering = {
> "blueprint": ('exact', ),
> }
>
>
>  When I use curl to POST: 
>
>  curl -i -H "Content-Type: application/json" -X POST -d 
>  @wkl.json  http://localhost:8000/api/workload/
>
>  where wkl.json is:
>
>  { "name":"w 5", "description":"w 5 desc" }
>
>
>  I get this error:
>
>  AttributeError: 'Workload' object has no attribute 'blueprint'
>
>  I do need to have this attribute, so I can list all child workloads for a 
> given blueprint 
>  like this:  GET /api/workload/?blueprint=1
>
>  but I need to exclude this 'blueprint' attribute from participating in 
> the obj_create
>
>  What is the proper place and syntax to do this?
>
>
> -Eugene
>
>
>
>

-- 
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/7940ec09-b130-43ab-ab43-c25a26466284%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: path to django from jython

2015-01-30 Thread Collin Anderson
Hi,

I think you to make sure django is on your PYTHONPATH / sys.path

Collin

On Tuesday, January 27, 2015 at 10:51:13 AM UTC-5, Josh Stratton wrote:
>
> Okay, stupid question, but how do I source django when jusing jython?  I 
> have django installed using pip and jython installed locally.  I've built 
> my project using python and after adding "doj" to the installed apps, I get 
> a path error building a war.  
>
> $ jython manage.py buildwar
> Traceback (most recent call last):
>   File "manage.py", line 8, in 
> from django.core.management import execute_from_command_line
> ImportError: No module named django
>
> https://pythonhosted.org/django-jython/war-deployment.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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1d542d5c-07ed-46c0-ad6d-4fc3bab8e29e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Create Django token-based Authentication

2015-01-30 Thread Collin Anderson
Hi,

What happens when you try? :)

Your setup is pretty complicated, but I don't know if REST framework will 
help much.

Collin

On Tuesday, January 27, 2015 at 12:00:59 AM UTC-5, Hossein Rashnoo wrote:
>
> I have my authentication service on django. I want to role as web-service 
> to gave other website a token and authenticate users with that token.
>
> This is my scenario:
>
>1. user visit external website and try to login
>2. when hit the login button that website redirect user to my site to 
>use username and password for login
>3. When successfully logged in users will redirect to external website 
>with a token
>4. And every time that website send me that token, I recognize that 
>user and pass some data to external website I'm try to use REST-Framework 
>authentication but it is too complicated Please help me.
>
>

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


Re: Putting picture thumbnails within admin page

2015-01-29 Thread Collin Anderson
Hi,

Any luck?

Try looking at the Network tab of the developer console to see what the 
errors are.

Collin

On Monday, January 26, 2015 at 7:31:54 PM UTC-5, bradford li wrote:
>
>
> I am trying to put thumbnail pictures of my photos within my admin page. I 
> am currently running into the issue where the thumbnail isn't displayed, 
> when I click on thumbnail I am redirected to the homepage of my project 
> with this as the URL: 
>
> http://127.0.0.1:8000/media/tumblr_ngotb4IY8v1sfie3io1_1280.jpg
>
> Here is a gist of my code: 
>
> https://gist.github.com/liondancer/678752e8bf31cc7d2c63
>
> Stackoverflow question:
>
>
> http://stackoverflow.com/questions/28159740/configuring-admin-to-display-thumnails
>
> If anything else is needed please let me know! 
>
>
>
> 
>
>
>

-- 
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/d0302752-6a77-4d67-89da-f9bd27178ab1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Wanted: Best practices for setting "_" (to ugettext/ugettext_lazy)

2015-01-27 Thread Collin Anderson
Hi,

Why reset it at the end of your module?

Why not use ugettext_lazy everywhere?
from django.utils.translation import ugettext_lazy as _

(Disclaimer: I've never used translations before :)

Collin

On Saturday, January 24, 2015 at 3:46:31 AM UTC-5, Torsten Bronger wrote:
>
> Hallöchen! 
>
> This is not about where to use ugettext/ugettext_lazy.  I know 
> that.  :-) 
>
> But I was fed up with all those "_ = ugettext" scattered in my code 
> and tried to find a more systematic approach.  The following test 
> program runs through: 
>
> ugettext = lambda x: x 
> ugettext_lazy = lambda x: x 
>
> _ = ugettext_lazy 
>
> def function(): 
> assert _ == ugettext 
>
> class A(object): 
> assert _ == ugettext_lazy 
>
> def method(self): 
> assert _ == ugettext 
>
> assert _ == ugettext_lazy 
>
> assert _ == ugettext_lazy 
>
> def function_b(): 
> assert _ == ugettext 
>
> _ = ugettext 
>
>
> function() 
> function_b() 
> a = A() 
> a.method() 
>
> Do you think this is a good idea?  Simply setting _ to 
> ugetttext_lazy at the beginning of a module and to ugettext at the 
> end (and dealing with the very few remaining exceptions)?  How do 
> you do that? 
>
> Tschö, 
> Torsten. 
>
> -- 
> Torsten BrongerJabber ID: torsten...@jabber.rwth-aachen.de 
>  
>   or http://bronger-jmp.appspot.com 
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To 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/021586ad-9efd-4c31-949a-ed6f15fbf03b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: gis: geo_db_type error in run_checks() in 1.7 (not 1.6)

2015-01-27 Thread Collin Anderson
Hi,

You could also try the geodjango mailing list if nothing else.
http://groups.google.com/group/geodjango

Collin

On Sunday, January 25, 2015 at 6:04:57 PM UTC-5, dne...@destinati.com wrote:
>
> Hi,
>
> Wanted to throw this out there, not sure truly if it is my fault or a bug.
>
> Just upgraded from (python 2.6.x, django 1.6) to (python 2.7.x, django 
> 1.7).
> If I invoke manage.py on any subcommand, I get an error as follows:
>
> 
> [app_dev]$ python2.7 manage.py sql
> Traceback (most recent call last):
>   File "manage.py", line 10, in 
> execute_from_command_line(sys.argv)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", 
> line 385, in execute_from_command_line
> utility.execute()
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", 
> line 377, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", 
> line 288, in run_from_argv
> self.execute(*args, **options.__dict__)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", 
> line 337, in execute
> self.check()
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", 
> line 371, in check
> all_issues = checks.run_checks(app_configs=app_configs, tags=tags)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/checks/registry.py", 
> line 59, in run_checks
> new_errors = check(app_configs=app_configs)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/core/checks/model_checks.py", 
> line 28, in check_all_models
> errors.extend(model.check(**kwargs))
>   File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", 
> line 1046, in check
> errors.extend(cls._check_fields(**kwargs))
>   File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", 
> line 1122, in _check_fields
> errors.extend(field.check(**kwargs))
>   File 
> "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" 
> , line 192, in check
> errors.extend(self._check_backend_specific_checks(**kwargs))
>   File 
> "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" 
> , line 290, in _check_backend_specific_checks
> return connection.validation.check_field(self, **kwargs)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/validation.py",
>  
> line 23, in check_field
> field_type = field.db_type(connection)
>   File 
> "/usr/local/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py",
>  
> line 221, in db_type
> return connection.ops.geo_db_type(self)
> AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
> 
>
> In mysql/validation.py in Django 1.7 it attempts 'field_type = 
> field.db_type(connection)'. This call isn't made in the same function in 
> Django 1.6, so this problem doesn't arise. If I add this call into the 
> Django 1.6 function the same error appears.
>
> Something to do with the fact that connection.ops is  'django.db.DefaultConnectionProxy'>. 'django.db.backends.mysql.base.DatabaseOperations'> so it isn't correctly 
> getting to contrib/gis/db/backends/mysql/operations.py (?).
>
> This error occurs for a PointField field (not sure about any others), e.g. 
> a model of the type:
>
> ---
> from django.contrib.gis.db import models class MyModel(models.Model):
> point_xy = models.PointField()
> objects = models.GeoManager()
> ---
>
> CentOS release 6.6 (Final)
> geos.x86_64 3.3.2-1.el6
> mysql.x86_645.1.73-3.el6_5
> Django (1.7.3)
> Python 2.7.9
> MySQL-python (1.2.5)
>
> I fixed this with a hack (avoid the db_type call based on the few field 
> names I use for PointField's), but perhaps this should be looked into.
>
> Dylan Nelson
>
>

-- 
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/c9508757-e433-4d33-9b30-e81c44e37fc7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Forms test run on development database instead of test database

2015-01-27 Thread Collin Anderson
Hi,

I just tried out your project. Looking at the stacktrace, the test module 
is importing forms (before the test starts). The forms module is running a 
query on startup for choices.

https://github.com/merwan/django-choicefield/blob/master/myapp/forms.py

Don't do queries on startup. :)

Collin

On Monday, January 26, 2015 at 7:07:54 AM UTC-5, Merouane Atig wrote:
>
> Hi,
>
> I have a strange issue with a forms test and I would like to know if I'm 
> doing something wrong or if it is a Django bug.
>
> I created a repo to reproduce the issue I have: 
> https://github.com/merwan/django-choicefield
>
> I have a DomainForm class with a choice field populated from a table in 
> the database. I'm trying to test it using the Django testing tools, but I 
> get the error "django.db.utils.OperationalError: no such table: 
> myapp_topleveldomain" (see the README in the Github repo for the full stack 
> trace).
>
> If I first create my development database and migrate it, then I do not 
> have any error. I expected that the test would run on the test database but 
> it is not the case.
>
> My test environment should work properly as I also created a model test 
> which runs correctly on the test database and do not need the development 
> database.
>
> Can you tell me what would be the proper way to write this test so that it 
> runs on the test database? Is it a bug with the Django testing tools or am 
> I doing something wrong when populating my ChoiceField?
>
> I'm using Django 1.7.3 and Python 3.4.0
>
> Thanks for your help
>

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


Re: sending email

2015-01-27 Thread Collin Anderson
Hi,

You should be able to figure out which box is checked from 
form.cleaned_data.

Collin

On Sunday, January 25, 2015 at 11:53:12 PM UTC-5, suabiut wrote:
>
> Hi Collin,
> Thank you very much for your help. its works perfectly.
> The next thing i want to do is to send an email to a specific user that i 
> select on a table. when an authorized user select a user to approve his or 
> her leave i want an email to be send to the user. so basically when i click 
> on the checkbox on the Test User form the table below. i should get a form 
> to approve the leave as below. now when i click on authorized Leave button 
> an email should be send to the test user. please point me to right 
> direction.
>  [image: Inline image 1]
>
> [image: Inline image 2]
>
> Cheers,
>
> On Fri, Jan 23, 2015 at 1:18 PM, Collin Anderson <cmawe...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> Just query the users you want.
>>
>> to_emails = [u.email for u in 
>> User.objects.filter(username__in=['person1', 'person2', 'person3'])]
>> send_mail('Subject here', 'Here is the message.', from_email_address, 
>> to_emails)
>>
>> Collin
>>
>> On Wednesday, January 21, 2015 at 11:29:51 PM UTC-5, suabiut wrote:
>>>
>>> Thanks,
>>> I am trying to send email to the users that their email address is 
>>> stored in the database on the auth_user table. can someone please point me 
>>> to the right direction.
>>>
>>> Cheers,
>>>
>>>
>>> On Thu, Jan 22, 2015 at 3:03 PM, Collin Anderson <cmawe...@gmail.com> 
>>> wrote:
>>>
>>>> Hi,
>>>>
>>>> Yes, this is possible. Something like:
>>>>
>>>> from django.core.mail import send_mail
>>>>
>>>> def authorized_leave(request):
>>>> form = MyForm()
>>>> if request.method == 'POST':
>>>> form = MyForm(request.POST)
>>>> if form.is_valid():
>>>> obj = form.save()
>>>> send_mail('Subject here', 'Here is the message.', '
>>>> fr...@example.com', ['t...@example.com'])
>>>> return redirect('/done/')
>>>> return render(request, 'template.html', {form: 'form'})
>>>>
>>>> Collin
>>>>
>>>>
>>>> On Monday, January 19, 2015 at 10:02:45 PM UTC-5, suabiut wrote:
>>>>>
>>>>> Hi,
>>>>> I am trying to send an email to several users once a form is submit. I 
>>>>> have done the view.py to update the database once the form is submitted 
>>>>> and 
>>>>> is working fine. what i want to accomplish when the form is submitted is 
>>>>> to 
>>>>> update the database and at the same time send out email when a user click 
>>>>> on the Authorized leave button.
>>>>>
>>>>> here is the step i want to do:
>>>>>
>>>>>  [image: Inline image 1]
>>>>>
>>>>> 1) user click on the check box and this form below appears
>>>>>
>>>>>
>>>>> [image: Inline image 2]
>>>>>  2) the user then fill up the form and click on authorized leave 
>>>>> button. the form will stored the information into the database. which i 
>>>>> have already done it. what i wanted to do next is to also send a emails 
>>>>> when the authorized leave button is click. is it possible to send emails 
>>>>> and also save data to database when the authorized leave button is click. 
>>>>> i 
>>>>> want to send email to the *Test User* which have his email address 
>>>>> store in the database. 
>>>>>
>>>>> template.html
>>>>> {%csrf_token%}
>>>>> 
>>>>> {{form.as_table}}
>>>>> 
>>>>> 
>>>>>   
>>>>>
>>>>>
>>>>> 
>>>>>
>>>>> please point me to the right direction.
>>>>>
>>>>> Cheers,   
>>>>>
>>>>>   -- 
>>>> You received this message because you are subscribed to the Google 
>>>> Groups "Django users" group.
>>>> To unsubscribe from this group and stop receiving emails from it, send 
>>>> an email to django-users...@googlegroups.com.
>>>> To post to this group, send email to django...@googlegroups.com.
>>>> Visit th

Re: programming error in group by clause

2015-01-27 Thread Collin Anderson
Hi,

What database are you using?

If you can reproduce this in a simple project, feel free to open a ticket 
about it.

Thanks,
Collin

On Sunday, January 25, 2015 at 12:51:31 AM UTC-5, satya wrote:
>
> Need some help on fixing the following error. I recently moved to 1.8alpha 
> version from an older version django-e9d1f11 and I started seeing this 
> error. Looks like the way group by is constructed has changed.
>
> Here is the model that I have.
>
> class everydaycost(models.Model):
> cost = models.DecimalField(max_digits=20, decimal_places=2)
> rev = models.DecimalField(max_digits=20, decimal_places=2)
> ts = models.DateField(db_index=True)
>
> I am trying to get roi (rev/cost) for each day of week.
>
> $ python manage.py shell
> Python 2.7.5 (default, Mar  9 2014, 22:15:05)
> [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> (InteractiveConsole)
> >>>
> >>> from testgroupby.models import *
> >>> from django.db.models import Q, Count, Min, Sum, Func, FloatField
> >>> qs = everydaycost.objects.all()
> >>> qs = qs.extra(select={'dow': "TO_CHAR(ts, 'D')"})
> >>> qs = qs.values('dow')
> >>> qs = qs.annotate(sum_cost=Sum('cost'))
> >>> qs = qs.annotate(sum_rev=Sum('rev'))
> >>> qs = qs.annotate(roi=Func(A='CAST(Sum("rev") as numeric)', 
> B='CAST(Sum("cost") as numeric)',
> ... template='ROUND(COALESCE(%(A)s / NULLIF(%(B)s,0), 0), 
> 2)', output_field=FloatField()))
> >>> print qs
> DEBUG(0.002) SELECT (TO_CHAR(ts, 'D')) AS "dow", 
> SUM("testgroupby_everydaycost"."cost") AS "sum_cost", 
> SUM("testgroupby_everydaycost"."rev") AS "sum_rev", 
> ROUND(COALESCE(CAST(Sum("rev") as numeric) / NULLIF(CAST(Sum("cost") as 
> numeric),0), 0), 2) AS "roi" FROM "testgroupby_everydaycost" GROUP BY 
> (TO_CHAR(ts, 'D')), ROUND(COALESCE(CAST(Sum("rev") as numeric) / 
> NULLIF(CAST(Sum("cost") as numeric),0), 0), 2) LIMIT 21; args=()
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/Downloads/Django-1.8a1/django/db/models/query.py", line 139, in 
> __repr__
> data = list(self[:REPR_OUTPUT_SIZE + 1])
>   File "/Downloads/Django-1.8a1/django/db/models/query.py", line 163, in 
> __iter__
> self._fetch_all()
>   File "/Downloads/Django-1.8a1/django/db/models/query.py", line 955, in 
> _fetch_all
> self._result_cache = list(self.iterator())
>   File "/Downloads/Django-1.8a1/django/db/models/query.py", line 1075, in 
> iterator
> for row in self.query.get_compiler(self.db).results_iter():
>   File "/Downloads/Django-1.8a1/django/db/models/sql/compiler.py", line 
> 780, in results_iter
> results = self.execute_sql(MULTI)
>   File "/Downloads/Django-1.8a1/django/db/models/sql/compiler.py", line 
> 826, in execute_sql
> cursor.execute(sql, params)
>   File "/Downloads/Django-1.8a1/django/db/backends/utils.py", line 80, in 
> execute
> return super(CursorDebugWrapper, self).execute(sql, params)
>   File "/Downloads/Django-1.8a1/django/db/backends/utils.py", line 65, in 
> execute
> return self.cursor.execute(sql, params)
>   File "/Downloads/Django-1.8a1/django/db/utils.py", line 95, in __exit__
> six.reraise(dj_exc_type, dj_exc_value, traceback)
>   File "/Downloads/Django-1.8a1/django/db/backends/utils.py", line 65, in 
> execute
> return self.cursor.execute(sql, params)
> ProgrammingError: aggregate functions are not allowed in GROUP BY
> LINE 1: ... GROUP BY (TO_CHAR(ts, 'D')), ROUND(COALESCE(CAST(Sum("rev")...
>  ^
>
> >>> print qs.query
> SELECT (TO_CHAR(ts, 'D')) AS "dow", SUM("testgroupby_everydaycost"."cost") 
> AS "sum_cost", SUM("testgroupby_everydaycost"."rev") AS "sum_rev", 
> ROUND(COALESCE(CAST(Sum("rev") as numeric) / NULLIF(CAST(Sum("cost") as 
> numeric),0), 0), 2) AS "roi" FROM "testgroupby_everydaycost" GROUP BY 
> (TO_CHAR(ts, 'D')), ROUND(COALESCE(CAST(Sum("rev") as numeric) / 
> NULLIF(CAST(Sum("cost") as numeric),0), 0), 2)
> >>>
>
>
> With earlier version, this worked fine for me.
>
>
> $ python manage.py shell
> Python 2.7.5 (default, Mar  9 2014, 22:15:05)
> [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> (InteractiveConsole)
> >>>
> >>> from testgroupby.models import *
> >>> from django.db.models import Q, Count, Min, Sum, Func, FloatField
> >>> qs = everydaycost.objects.all()
> >>> qs = qs.extra(select={'dow': "TO_CHAR(ts, 'D')"})
> >>> qs = qs.values('dow')
> >>> qs = qs.annotate(sum_cost=Sum('
> cost'))
> >>> qs = qs.annotate(sum_rev=Sum('rev'))
> >>> qs = qs.annotate(roi=Func(A='CAST(Sum("rev") as numeric)', 
> B='CAST(Sum("cost") as numeric)',
> ... template='ROUND(COALESCE(%(A)s / NULLIF(%(B)s,0), 0), 
> 2)', output_field=FloatField()))
> >>> print qs
> DEBUG(0.002) SELECT (TO_CHAR(ts, 'D')) AS "dow", 
> SUM("testgroupby_everydaycost"."cost") AS 

Re: Django: How to customize the admin form for specific model

2015-01-27 Thread Collin Anderson
Hi,

You could have the images be inline:

class CommentImageInline(models.TabularInline):
model = CommentImage
extra = 0

class CommentAdmin(models.ModelAdmin):
inlines = [CommentImageInline]

Though, you may need to use a custom widget to get the actual images to 
show up.

Collin

On Saturday, January 24, 2015 at 2:31:02 PM UTC-5, Shoaib Ijaz wrote:
>
> First of all I apologize the question title can be unrelated to my query. 
> I am also confused what I want to do because I am less familiar with django.
>
> I want to create simple comment system. The requirement is clear that user 
> can post comment with multiple images.Every comment should have reply. so I 
> created following models.
>
> #comment table class Comments(models.Model):
> parent = models.ForeignKey('self',null=True) // for comment reply
> description = models.TextField(max_length=1000, blank=False, null=False)
>
> class Meta:
> db_table = u'comments'
>
> #images tableclass CommentImages(models.Model):
> comment = models.ForeignKey(Comments)
> image = models.CharField(max_length=250, blank=False, null=False)
>
> class Meta:
> db_table = u'comments_images'
>
> I have query about admin side how can i manage these things?
>
> I want to show images list when admin view the specific comment.
>
> Admin can view replies of specific comment.
>
> Here i draw the example. [image: enter image description here]
>
> So I dont want to ask about coding. I want to know what techniques will be 
> used to change the admin view. I am using admin panel for others models too 
> so I want to change the specific model view.
>
> How can I get these things? Thank you
>

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


Re: unable to open project

2015-01-27 Thread Collin Anderson
Hi,

What happens when you try?

Collin

On Saturday, January 24, 2015 at 3:59:55 AM UTC-5, abhishek kumar wrote:
>
> I am unable to open my project again.  As i am using virtual enviroment in 
> windows.
>

-- 
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/304c2a89-001a-4b01-ab2b-3578e327766e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do you link your Django project to a domain

2015-01-27 Thread Collin Anderson
I use namecheap, but yes, domains.google.com has a nice user interface.

On Saturday, January 24, 2015 at 8:22:33 AM UTC-5, patrickbeeson wrote:
>
> You might also check out Google's recently launched domain registrar at 
> domains.google.com.
>
> On Saturday, January 24, 2015 at 2:01:43 AM UTC-5, djangocharm2020 wrote:
>>
>> pretty much have a project built but now want to purchase a domain to 
>> link it live . Do you guys have any suggestions on who i should go with 
>> like godaddy.com.
>>
>> I also need to know is there a special step or code that is needed to add 
>> to the project?
>>
>> Thanks 
>>
>

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


Re: login_required in urlpatterns TypeError 'tuple' object is not callable

2015-01-27 Thread Collin Anderson
Hi,

Something like this might work:

from home.urls import urlpatterns as home_urls


url('^home/', include(list(login_required(x) for x in home_urls)))

Collin

On Friday, January 23, 2015 at 7:09:30 PM UTC-5, Vijay Khemlani wrote:
>
> I may be mistaken, but I don't think you can decorate an entire "include" 
> call
>
> On Fri, Jan 23, 2015 at 8:51 PM, Neto  > wrote:
>
>> Hi, I'm using login_required in url patterns but it does an error:
>>
>> urls.py
>>
>> from django.conf.urls import patterns, include, url
>> from django.contrib.auth.decorators import login_required
>>
>>
>> urlpatterns = patterns('',
>> url(r'^home/', login_required(include('home.urls'))),
>>
>> )
>>
>>
>> error:
>> TypeError at /home/
>>
>> 'tuple' object is not callable
>>
>> how to fix 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...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/a0a93906-ce10-4b46-bb7a-67aa8d458a6c%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

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


Re: Dictionary in admin interface

2015-01-27 Thread Collin Anderson
Hi,

The admin doesn't really have a way to do this. You could edit KeyValuePair 
inline on Dictionary.

Why not have a "Params" model that has a ForeignKey to Request?

Collin

On Friday, January 23, 2015 at 1:32:21 PM UTC-5, Sven Mäurer wrote:
>
> I want to manage a dictionary inline over the admin interface. These are 
> my models. What I got working is of course a separated management of 
> request and dictionary. But I want to add key value pairs in the request 
> admin interface with a TabularInline. Do I have to skip the dictionary in 
> some way or what do I have to do?
>
> class Dictionary(models.Model):
> name = models.CharField(max_length=255)
> class KeyValuePair(models.Model):
> container = models.ForeignKey(Dictionary, db_index=True)
> key = models.CharField(max_length=240, db_index=True)
> value = models.CharField(max_length=240, db_index=True)
> class Request(models.Model):
> params = models.ForeignKey(Dictionary, related_name="params_map", 
> blank=True, null=True)
>
>

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


Re: How to detect (daily) User Login when using cookies?

2015-01-27 Thread Collin Anderson
Hi,

Would it make sense to simply keep a record of when the last time you've 
seen the user is?

Collin

On Friday, January 23, 2015 at 4:43:41 AM UTC-5, Tobias Dacoir wrote:
>
> I'm using django-allauth and I receive a signal when a user logs in. Now I 
> want to store each day the user logs in. However, when the user does not 
> logout he can still log in the next day thanks to the cookies. I know that 
> I can set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in settings.py. But this 
> may annoy some Users. 
>
> So is there a way to use cookies but still tell if a User has accessed the 
> site for the first time today?
>

-- 
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/ff24698c-f21d-4a28-a78e-55093d8cf15b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unable to save object with images while using FormWizard in Django 1.7 and Python 3.4

2015-01-27 Thread Collin Anderson
Hi,

Use items() instead of iteritems().

Collin

On Thursday, January 22, 2015 at 11:31:23 AM UTC-5, Frankline wrote:
>
> ​Hi all​,
> I am having a problem saving a Django form using the *FormWizard 
> * 
> while using *Django 1.7* and *Python 3.4*. Below is my code:
>
> *models.py*
>
> ...class Advert(models.Model):
> ... # Some irelevant code removed for brevity
> owner = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, 
> blank=False, null=False)
> title = models.CharField(_("Title"), max_length=120)
> description = models.TextField(_("Description"), default='')
> category = models.ForeignKey(AdCategory, db_index=True, 
> related_name='ad_category', verbose_name=_('Category'))
> status = models.IntegerField(choices=ADVERT_STATES, default=0)
> adtype = models.IntegerField(choices=ADTYPES, default=1)
> price = models.DecimalField(_('Price'), max_digits=12, decimal_places=2, 
> blank=True, default=0,
> help_text=_('Price'), 
> validators=[MinValueValidator(0)])
> ...class AdvertImage(models.Model):
>
> def generate_new_filename(instance, filename):
> IMAGE_UPLOAD_DIR = "advert_images"
> old_fname, extension = os.path.splitext(filename)
> return '%s/%s%s' % (IMAGE_UPLOAD_DIR, uuid.uuid4().hex, extension)
> 
> advert = models.ForeignKey(Advert, related_name='images')
> image = models.ImageField(upload_to=generate_new_filename, null=True, 
> blank=True)
>
>
> *forms.py*
>
> from django.forms.models import inlineformset_factoryfrom django import 
> formsfrom django.forms import ModelForm, RadioSelect, TextInput
> from .models import Advert, AdvertImage
>
> class AdvertCategoryForm(ModelForm):
>
> class Meta:
> model = Advert
> fields = ('category',)
>
> class AdvertDetailsForm(ModelForm):
>
> class Meta:
> model = Advert
> fields = ('title', 'description', 'location', 'adtype', 'price')
>
> class AdvertImageForm(ModelForm):
>
> class Meta:
> model = AdvertImage
> fields = ('image',)
>
> AdvertImageFormset = inlineformset_factory(Advert, AdvertImage, 
> fields=('image',), can_delete=False, extra=3, max_num=3)
>
>
> FORMS = [("ad_category", AdvertCategoryForm),
>  ("ad_details", AdvertDetailsForm),
>  ("ad_images", AdvertImageFormset)]
>
> TEMPLATES = {"ad_category": "adverts/advert_category_step.html",
>  "ad_details": "adverts/advert_details_step.html",
>  "ad_images": "adverts/advert_images_step.html"}
>
>
> *views.py*
>
> ...class AdvertWizard(LoginRequiredMixin, SessionWizardView):
>
> form_list = FORMS
> file_storage = 
> FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT))
>
> def get_template_names(self):
> return [TEMPLATES[self.steps.current]]
>
> ...
>
> def done(self, form_list, **kwargs):
> advert = Advert()
> """for form in form_list:for field, value in 
> form.cleaned_data.iteritems():setattr(advert, field, value)"""
>
> form_dict = {}
> for form in form_list:
> form_dict.update(form.cleaned_data)
>
> advert.owner = self.request.user
> advert.save()
> redirect(advert)
>
>
> ​The problem occurs in the done method while saving the form:
>
> ValueError at /ads/new
>
> dictionary update sequence element #0 has length 3; 2 is required
>
> Request Method:POSTRequest URL:http://localhost:8000/ads/newDjango 
> Version:1.7.1Exception Type:ValueErrorException Value:
>
> dictionary update sequence element #0 has length 3; 2 is required
>
> Exception 
> Location:/home/frank/Projects/python/django/pet_store/src/petstore/apps/adverts/views.py
>  
> in done, line 147Python Executable:
> /home/frank/.virtualenvs/petstore/bin/pythonPython Version:3.4.0
>
>- 
>
> /home/frank/Projects/python/django/pet_store/src/petstore/apps/adverts/views.py
> in done
>1. 
>   
>   form_dict.update(form.cleaned_data)
>   
>   ...
>▶ Local vars 
>
> However, when I replace the following code:
>
> form_dict = {}
> for form in form_list:
> form_dict.update(form.cleaned_data)
>
> with this one
>
> for form in form_list:
> for field, value in form.cleaned_data.iteritems():
> setattr(advert, field, value)
>
> I now get the following error:
>
> AttributeError at /ads/new
>
> 'dict' object has no attribute 'iteritems'
>
> Request Method:POSTRequest URL:http://localhost:8000/ads/newDjango 
> Version:1.7.1Exception Type:AttributeErrorException Value:
>
> 'dict' object has no attribute 'iteritems'
>
> Exception 
> Location:/home/frank/Projects/python/django/pet_store/src/petstore/apps/adverts/views.py
>  
> in done, line 140Python Executable:
> 

Re: sending email

2015-01-22 Thread Collin Anderson
Hi,

Just query the users you want.

to_emails = [u.email for u in User.objects.filter(username__in=['person1', 
'person2', 'person3'])]
send_mail('Subject here', 'Here is the message.', from_email_address, 
to_emails)

Collin

On Wednesday, January 21, 2015 at 11:29:51 PM UTC-5, suabiut wrote:
>
> Thanks,
> I am trying to send email to the users that their email address is stored 
> in the database on the auth_user table. can someone please point me to the 
> right direction.
>
> Cheers,
>
>
> On Thu, Jan 22, 2015 at 3:03 PM, Collin Anderson <cmawe...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> Yes, this is possible. Something like:
>>
>> from django.core.mail import send_mail
>>
>> def authorized_leave(request):
>> form = MyForm()
>> if request.method == 'POST':
>> form = MyForm(request.POST)
>> if form.is_valid():
>> obj = form.save()
>> send_mail('Subject here', 'Here is the message.', '
>> fr...@example.com ', ['t...@example.com '])
>> return redirect('/done/')
>> return render(request, 'template.html', {form: 'form'})
>>
>> Collin
>>
>>
>> On Monday, January 19, 2015 at 10:02:45 PM UTC-5, suabiut wrote:
>>>
>>> Hi,
>>> I am trying to send an email to several users once a form is submit. I 
>>> have done the view.py to update the database once the form is submitted and 
>>> is working fine. what i want to accomplish when the form is submitted is to 
>>> update the database and at the same time send out email when a user click 
>>> on the Authorized leave button.
>>>
>>> here is the step i want to do:
>>>
>>>  [image: Inline image 1]
>>>
>>> 1) user click on the check box and this form below appears
>>>
>>>
>>> [image: Inline image 2]
>>>  2) the user then fill up the form and click on authorized leave button. 
>>> the form will stored the information into the database. which i have 
>>> already done it. what i wanted to do next is to also send a emails when the 
>>> authorized leave button is click. is it possible to send emails and also 
>>> save data to database when the authorized leave button is click. i want to 
>>> send email to the *Test User* which have his email address store in the 
>>> database. 
>>>
>>> template.html
>>> {%csrf_token%}
>>> 
>>> {{form.as_table}}
>>> 
>>> 
>>>   
>>>
>>>
>>> 
>>>
>>> please point me to the right direction.
>>>
>>> Cheers,   
>>>
>>>   -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/3df19a0c-2afc-4e17-b527-83d38a639611%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/3df19a0c-2afc-4e17-b527-83d38a639611%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
>
>  

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


Re: makemigrations complains about a ForeignKey not being Unique

2015-01-22 Thread Collin Anderson
Hi,

I think you might want to use a common abstract base class. You want a 
completely separate database table for the two models, right?

Collin

On Wednesday, January 21, 2015 at 10:17:08 PM UTC-5, Samuel Jean wrote:
>
> Hi there, 
>
> Does anybody know of a way to trick Django 1.7 (or the proper way, if 
> any) to modify the property of an inherited field so that it has unique 
> property on the children only. 
>
> Consider this abstract model : 
>
> class UniqueObjectModel(models.Model): 
>  uuid = models.CharField(max_length=36, default=uuid4) 
>  pool = models.ForeignKey('Pool', related_name='+', to_field='uuid') 
>  ... 
>
>  class Meta: 
>  abstract = True 
>  unique_together = (('uuid', 'pool'),) 
>
> I would like the Pool model to inherit from UniqueObjectModel *but* have 
> its uuid field unique. 
>
> class Pool(UniqueObjectModel): 
>  def __init__(self, *args, **kwargs): 
>  super(Pool, self).__init__(*args, **kwargs) 
>  self._meta.get_field('pool').to = 'self' 
>  self._meta.get_field('uuid')._unique = True 
>
> However, Django still complains about Pool.uuid field not being unique. 
>
> $ python manage.py makemigrations myapp 
>
> CommandError: System check identified some issues: 
>
> ERRORS: 
> myapp.Controller.pool: (fields.E311) 'Pool.uuid' must set unique=True 
> because it is referenced by a foreign key. 
>
> Any ideas? 
>
> Thanks! 
>

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


Re: Remote Authentication (out-of-the-box)

2015-01-22 Thread Collin Anderson
Hi,

RemoteUserBackend is for Apache or Windows IIS, I don't think it's what you 
want.

Do you have a local copy of the user table on hand? If so just query the 
matching username and call "django.contrib.auth.login()" on it.

Otherwise, you'll need to use a custom backend.

Collin

On Wednesday, January 21, 2015 at 8:30:10 PM UTC-5, Cristian Bustos wrote:
>
> Hello Friends,
> Here is my question, Remote Authentication (out-of-the-box) django
> I have 2 projects Django:
>
>1. Users Api Django app (Django framework rest - token authentication) 
>- Server
>2. Django app (I need to authenticate users and consume APIs) - Client
>
> I can authenticate user, only use requests-python, but i need do remote 
> authentication with django
>
> This is my code:
> settings.py
>
> AUTHENTICATION_BACKENDS = ( 
> 'django.contrib.auth.backends.RemoteUserBackend', )
>
> MIDDLEWARE_CLASSES = ( '...', 
> 'django.contrib.auth.middleware.AuthenticationMiddleware', 
> 'django.contrib.auth.middleware.RemoteUserMiddleware',
>  '...', )
>
>
> view.py
> -
> class LoginRCS(View):
> template_name = 'userprofiles/login.html'
>
> def get(self, request, *args, **kwargs):
> return render(request, self.template_name )
>
> def post(self, request, *args, **kwargs):
> # inputBp and inputPassword come from login form
> if 'inputBp' in request.POST and 'inputPassword' in request.POST:
> inputBp = request.POST['inputBp']
> inputPassword = request.POST['inputPassword']
>
> # URL to get token from api user
> URL_API = 'http://localhost:7000/api/token/'
> payload = {'username': inputBp, 'password': inputPassword}
> headers = {'content-type': 'application/json'}
> r = requests.post(URL_API, data=json.dumps(payload), 
> headers=headers)
>
> if r.status_code == requests.codes.ok:
> # I have a token
> data = json.loads(r.text)
> token_auth = 'token ' + data['token']
>
> URL_CHECK_USER = '
> http://127.0.0.1:7000/api/users/?username='+inputBp 
> 
> payload_login = {'username': inputBp, 'password': 
> inputPassword}
> headers_login = {
> 'content-type': 'application/json',
> 'Authorization': token_auth }
> r_user = requests.get(URL_CHECK_USER, 
> data=json.dumps(payload_login), headers=headers_login)
>
> if r_user.status_code == request.codes.ok:
> # I have a user info (unsername, first_name, 
> last_name, email)
> data_user = json.loads(r_user.text)
>
> #
> # here need authentication
> # 
> # user = authenticate(username=my_user, password=my_bp)
>
> else:
> print 'Error'
> return render(request, self.template_name)
>
> thanks in advance,
> CB
>
>

-- 
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/c3b9d581-01a3-47fa-86f9-b776e9116867%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: block php requests

2015-01-22 Thread Collin Anderson
Hi,

I had broken link emails enabled for a while. Over time, my nginx.conf 
config grew into this:

location /_vti_inf.html { return 404; }
location /crossdomain.xml { return 404; }
location ~/cache/eb91756ae6745d22433f80be4ec59445$ { return 404; } # 
some sort of plugin?
location ~\.php$ { return 444; }
location ~\.aspx?$ { return 444; }
location /account/submit/add-blog { return 444; }
location /blogs/my_page/add { return 444; }
location /my_blogs { return 444; }
location /YaBB { return 444; }
location /signup { return 444; }
location /register { return 444; }
location /user/register { return 444; }
location /member/register { return 444; }
location /forum/member/register { return 444; }
location /tools/quicklogin.one { return 444; }
location /mt.js { return 444; }
location ~\[PLM=0\] { return 444; }

I eventually just turned of the 404 emails and was able to delete all of 
that config :)

Actually, if you put an  (or do a similar 
request with ajax) on your 404 page, that would filter out a lot of spam.

Collin

On Wednesday, January 21, 2015 at 3:32:15 AM UTC-5, hinnack wrote:
>
> Hi,
> thanks for your reply.
> Blocking all requests in Apache seems to be the best way. Can you give an 
> example how to do that?
> As / is mapped to the wsgi app ( 
> https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/modwsgi/ )
> and a new files section does not the trick:
>
>  #PHP protection
>
> order allow,deny
>
> deny from all
>
> satisfy all
>
> 
>
>
> Am Dienstag, 20. Januar 2015 12:55:40 UTC+1 schrieb hinnack:
>>
>> Hi,
>>
>> I get a lot of intrusion checks on my website - especially for PHP 
>> (wordpress, joomla, …).
>> Today they all raise a 404 errors in python-django - so if you have 
>> emails enabled for 404 errors…
>>
>> What is the best way to block those requests in a standard apache 
>> deployment?
>> ( https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/modwsgi/ )
>>
>> regards
>>
>> Hinnack
>>
>

-- 
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/c79c99b7-ff19-4785-b6fb-d12786876e5a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Strange Behavior from the Django Admin (following tutorial on a shared server)

2015-01-22 Thread Collin Anderson
Hi,

What's likely happening is that django or passenger is crashing. Is there 
any log available?

Collin

On Wednesday, January 21, 2015 at 2:13:45 AM UTC-5, Ed Volz wrote:
>
> Hi all,
>
> New to Django so I was following along with the tutorial and can get to 
> the point of logging into the Administration portal (the main page works as 
> well).  Django is running with passenger in a virtualenv (python 2.7) on a 
> shared host.  I immediately receive a ERR_EMPTY_RESPONSE   when I click 
> log in, regardless of whether or not the credentials are correct.  The db 
> records a session on a correct log in even though the ERR_EMPTY_RESPONSE 
> remains.  I've confirmed the user is both is_active and is_staff using the 
> shell.  
>
> What's puzzling me is that the log in page loads the css files from the 
> STATIC_URL just fine, but there's nothing once served up the form is 
> submitted.  Any help would be appreciated.
>
> settings.py file 
>
> passenger_wsgi.py file:
> #!/usr/bin/env python2.7
> import sys,os
> # Tell Passenger to run our virtualenv python
> INTERP = "/home//djangoenv/bin/python"
> if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
> # Set up paths and environment variables
> sys.path.append(os.getcwd())
> os.environ['DJANGO_SETTINGS_MODULE'] = 'mynewsite.settings'
> # Set the application
> import django.core.handlers.wsgi
> # Use paste to display errors
> from paste.exceptions.errormiddleware import ErrorMiddleware
> from django.core.wsgi import get_wsgi_application
> application = get_wsgi_application()
> application = ErrorMiddleware(application, debug=True)
>
>
>

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


Re: Is Django suitable for this purpose?

2015-01-22 Thread Collin Anderson
Hi,

As others have mentioned, it's totally possible. Regardless of using Django 
or not, the integration could easily be the hardest part, and that's where 
the "up to a minute delay" could come in.

Collin

On Tuesday, January 20, 2015 at 4:52:33 PM UTC-5, Mike Taylor wrote:
>
> I want to have an appointment booking option built into a website for a 
> clinic.
>
> The feature needs to integrate with the software that runs their office ( 
> http://www.atlaschirosys.com/)
>
> In order to be fully useful, it would need to be virtually instantaneous 
> in filling the requested appointment spot.  A time lag of more than a 
> couple minutes would not be acceptable.
>
> So, is this even possible and is Django the best tool for building it?
>
> Thank you for ANY input.
>

-- 
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/56883c53-8ca7-4b33-b2dc-a09daa9192b5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Binding model data to a formset without POST

2015-01-22 Thread Collin Anderson
Hi,

Interesting. I've never heard of someone wanting to show validation errors 
on the initial data when the page first loads.

I have however wanted to manually bind data to a form before. Last time I 
checked it's not super trivial, because you could for instance have a 
SplitDateTimeWidget which actually expects _two_ keys in the bound data.

If you're just doing basic fields, that should work. If you're doing 
anything more complicated, it might make sense to run the validation more 
by hand. If you could call field.clean() on the less raw data you could 
skip widgets and prefixes all together.

Collin

On Tuesday, January 20, 2015 at 8:06:06 AM UTC-5, Rob Groves wrote:
>
> Hi All,
> I am new to Django and am enjoying it very much.  Excellent documentation, 
> tutorials, and general environment to work in.  Good job Django developers!
>
> I have a question on binding data to a ModelFormset.  I have looked 
> extensively and not seen this particular issue covered before.
>
> I have a ModelFormset that I send to a template for custom rendering so I 
> can present the fields in a controlled tabular format.  The ultimate goal 
> is to use CSS to create a red bounding box around any fields with 
> validation errors and to set the "title" attribute of those input fields so 
> that the user can see what errors were generated  by hovering over the red 
> bounded field.  This presents a nice clean interface when there are 
> errors.  It all works great, with one annoyance if the model data starts 
> out with values that will generate validation errors (i.e. missing required 
> data).  
>
> I initially call the view with a GET, which creates the forms and 
> populates the form fields.  Since the data is not bound to forms at this 
> point, I can't validate and set the errors.  In order to validate the 
> fields and set the table error borders, I have to submit the form using 
> POST to bind the data, validate the form and generate the errors which 
> ultimately set an error_class for styling the table.  This means that I 
> have to "save" the from from my form page to get the table style I want.
>
> What I really want is to instantiate a ModelFormset, setting the instance, 
> but then to bind the data present in the instance and set errors by sending 
> is_valid() to the formset before rendering (i.e. on initial page rendering 
> with the GET, so no POST data).  It seemed to me that there should simply 
> be a bind_instance() function for all ModelFormsets that contain an 
> instance.  I looked and didn't find that.  Eventually, I just decided to 
> bind the data myself manually using the following helper function:
>
> # helper functions
> def bind_formset(formset):
> bindData={}
> # add management form data
> bindData[formset.get_default_prefix()+"-TOTAL_FORMS"]=str(formset.
> management_form['TOTAL_FORMS'].value())
> bindData[formset.get_default_prefix()+"-INITIAL_FORMS"]=str(formset.
> management_form['INITIAL_FORMS'].value())
> bindData[formset.get_default_prefix()+"-MIN_NUM_FORMS"]=str(formset.
> management_form['MIN_NUM_FORMS'].value())
> bindData[formset.get_default_prefix()+"-MAX_NUM_FORMS"]=str(formset.
> management_form['MAX_NUM_FORMS'].value())
> for form in formset:
> if form.instance:
> for fieldName,fieldValue in form.fields.iteritems():
> try:
> bindData[form.add_prefix(fieldName)]=getattr(form.
> instance,fieldName)
> except:
> # this is an added field, not derived from the model
> pass
> newFormset=formset.__class__(bindData,instance=formset.instance,
>   queryset=formset.queryset, error_class=
> formset.error_class)
> return newFormset
>
> This works!  My question... Is this a reasonable approach?  Or did I just 
> miss the obvious way of doing this?
>
> Thanks for any help!
>

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


Re: OneToOne field versus model inheritance

2015-01-22 Thread Collin Anderson
Hi,

Django doesn't really provide a way to create a subclass from an already 
existing object in the admin. It's actually pretty hard to do even in the 
code. So for that reason I'd recommend the non subclass with the 
OneToOneField.

Actually, if I were doing it, this is what I would do:

class User(AbstractBaseUser):
is_client = models.BooleanField(default=False)
is_member = models.BooleanField(default=False)
description = models.CharField(verbose_name=_('first name'), max_length=
255, blank=True)
# include both client and member fields here and have them be blank=True

Collin

On Tuesday, January 20, 2015 at 7:52:38 AM UTC-5, Paul Royik wrote:
>
> I have three models: Person, Client, Member
> Person is a base model, Client and Member are profiles for Person.
>
> class Person(AbstractBaseUser, PermissionsMixin):
> email = models.EmailField(
> verbose_name=_('email address'),
> max_length=255,
> unique=True,
> )
>
>
> class Client(User): #or maybe models.Model and explicit OneToField 
> first_name = models.CharField(verbose_name=_('first name'), 
> max_length=30)
> last_name = models.CharField(verbose_name=_('last name'), 
> max_length=30)
>
> class Member(User): #or maybe models.Model and explicit OneToField 
> description = models.CharField(verbose_name=_('first name'), 
> max_length=255)
># other stuff
>
>
> So, what I want?
> 1. In admin, when we add client or member, I want to fill field email 
> (fields from base class) as if it was in derived class. For example, in 
> admin list_display = ('email', 'first_name'). Not select boxes for user.
> 2. Person class can be instantiated separately and the "attached" to the 
> created profiel. Like person=Person(email="te...@gmail.com "), 
> client = Client(person=person,first_name="test"...). Especially, this 
> should work in forms. When user (person) is authenticated I want to give 
> ability to fill in profile (client) form and attach person to this form.
> 3. One person can have both accounts. If I delete client/member, 
> corresponding person should not be deleted.
>
> 3rd option actually is not necessary, but it is useful for me to know how 
> to do it.
>
> So, option 1 is perfectly solved by inheritance, Person is User, but this 
> approach fails when option 2 is implemented. Since Person and Client is 
> considered as one whole, I can't attach user, duplicate key error.
> Option 2 is resolved by extending models.Model and appending 
> person=models.OnetoOneField(Person,primary_key=True). However, admin is 
> broken (1st option), because Client don't have fields like email.
>
>
> So, what approach to take in order to solve above issues?
> Are there simple ways?
> If there are no simple ways, is there advanced way, like overriding 
> metaclass, object descriptors or writing custom OneToOne field?
>
> Any suggestions are welcomed.
>
> Thank you. 
>

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


Re: How to check appname via Django commands?

2015-01-22 Thread Collin Anderson
Hi,

I don't think the project name is stored in the database.

You can sometimes access the project name this way:

settings.SETTINGS_MODULE.split('.')[0]

Collin

On Tuesday, January 20, 2015 at 6:33:38 AM UTC-5, Sugita Shinsuke wrote:
>
> Hello Vijay
>
> Thank you for replying.
>
> But, I want to know the project name of django not app name.
>
>
> 2015年1月17日土曜日 23時18分46秒 UTC+9 Vijay Khemlani:
>>
>> What problem are you having exactly?
>>
>> Also I'm not sure what do you mean by "hierarchy" of the project folders, 
>> do you mean the order the apps appear in the INSTALLED_APPS setting?
>>
>> On Sat, Jan 17, 2015 at 6:38 AM, Sugita Shinsuke  
>> wrote:
>>
>>> Hi there.
>>>
>>> I use Django 1.6 version.
>>>
>>> The database of Django store the information of application.
>>> So, I know that if I  change the hierarchy of the Django project 
>>> folders, some trouble occurs.
>>> That is why, I'd like to check the name of my application.
>>>
>>> I think some of Django commands  like manage.py command can check the 
>>> application name in the database of Django project.
>>> Or, if you know other Django command. Could you tell me it?
>>>
>>> I would appreciate it if you would give me some advice.
>>>
>>>  -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to django-users...@googlegroups.com.
>>> To post to this group, send email to django...@googlegroups.com.
>>> Visit this group at http://groups.google.com/group/django-users.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/4ea222eb-1fdd-44af-97c7-3f5bb05a13ef%40googlegroups.com
>>>  
>>> 
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>
>>

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


Re: sending email

2015-01-21 Thread Collin Anderson
Hi,

Yes, this is possible. Something like:

from django.core.mail import send_mail

def authorized_leave(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
obj = form.save()
send_mail('Subject here', 'Here is the message.', 
'f...@example.com', ['t...@example.com'])
return redirect('/done/')
return render(request, 'template.html', {form: 'form'})

Collin

On Monday, January 19, 2015 at 10:02:45 PM UTC-5, suabiut wrote:
>
> Hi,
> I am trying to send an email to several users once a form is submit. I 
> have done the view.py to update the database once the form is submitted and 
> is working fine. what i want to accomplish when the form is submitted is to 
> update the database and at the same time send out email when a user click 
> on the Authorized leave button.
>
> here is the step i want to do:
>
>  [image: Inline image 1]
>
> 1) user click on the check box and this form below appears
>
>
> [image: Inline image 2]
>  2) the user then fill up the form and click on authorized leave button. 
> the form will stored the information into the database. which i have 
> already done it. what i wanted to do next is to also send a emails when the 
> authorized leave button is click. is it possible to send emails and also 
> save data to database when the authorized leave button is click. i want to 
> send email to the *Test User* which have his email address store in the 
> database. 
>
> template.html
> {%csrf_token%}
> 
> {{form.as_table}}
> 
> 
>   
>
>
> 
>
> please point me to the right direction.
>
> Cheers,   
>
>  

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


Re: post_save signal not working in Django 1.7

2015-01-21 Thread Collin Anderson
Hi,

Does the object in post_save have a pk/id?

Are you using transactions?

Collin

On Monday, January 19, 2015 at 1:22:37 PM UTC-5, Luis Matoso wrote:
>
> Something similar is happening with me too: on a post_save of model it 
> isn't created yet on database, so several 
> error are raised by functions which expect that it is already on DB.
>
> When the post_save handler ends, the object is saved normally.
>
>
> On Friday, January 16, 2015 at 4:14:09 PM UTC-2, Zach LeRoy wrote:
>>
>> I have a block of code that works fine in Django 1.6.10 but does not work 
>> at all in Django 1.7.3.  I would expect my log statement to print every 
>> time a Django User is created and this is the behavior in 1.6.10:
>>
>> import logging
>>
>> from django.contrib.auth.models import User
>> from django.db import models
>> from django.db.models.signals import post_save
>> from django.dispatch import receiver
>>
>> log = logging.getLogger(__name__)
>>
>>
>> class UserProfile(models.Model):
>> uuid = models.CharField(max_length=36)
>> user = models.OneToOneField(User)
>>
>>
>> @receiver(post_save, sender=User)
>> def create_user_profile(sender, instance, created, **kwargs):
>> """
>> When a new user is created, add a UserProfile
>> """
>> log.debug('received post save signal: {}'.format(instance))
>> if created:
>> UserProfile.objects.create(user=instance)
>>
>

-- 
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/f29ac31a-46ee-4b04-8058-d0acac2a5547%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Flood of ''Invalid HTTP_HOST header" mails

2015-01-21 Thread Collin Anderson
Hi,

So django is rejecting hosts even though they are listed in ALLOWED_HOSTS? 
Are you using apache/mod_wsgi by chance? It could be loading the settings 
for the wrong website. I assume you are reloading the server in between 
changes to the file.

Collin

On Monday, January 19, 2015 at 1:18:11 PM UTC-5, andi-h wrote:
>
> -BEGIN PGP SIGNED MESSAGE- 
> Hash: SHA1 
>
> Hi folks, 
>
> after upgrading my project to Django 1.7 it seems my host validation 
> got a bit out of control. I have tried these possibilities, but my web 
> server continues to send lots of mail about invalid HTTP_HOST headers: 
>
> ALLOWED_HOSTS = [ ".example.com" ] # domain name changed ;) 
> ALLOWED_HOSTS = [ "example.com", "www.example.com" ] 
>
> But in each case I get the mails about "www.example.com". Has anybody 
> else encountered this? 
>
> CU Andi 
> - -- 
> Andreas Pritschet 
> Phone:   +49 151 11728439 
> Homepage:http://www.pritschet.me 
> GPG Pub Key: http://goo.gl/4mOsM 
> -BEGIN PGP SIGNATURE- 
> Version: GnuPG v1 
>
> iQIcBAEBAgAGBQJUvUojAAoJEO0gsAalef15wqIP/3BBybnA6ZhBiIw33gnXa/TX 
> vYJrqcLv6mFQ4s7UmR4wxdTo+IfjZhhEx0p4qEqxOArPahdObAoO8KQEoFSanO3f 
> VVCq7EBSS84g26/NrVfudyERgjxPbLvVL9L7vUbSxNuT5HYBW0IXqWOXUhkq8VsK 
> gGGZkbQft8IH3jK28FNnNAJ+6PVY9yL2NDgB475Y6IlLqJHaXZYLl46U9ZbdTrF4 
> apJUmoaorZ1ul5Ga1Xkj8c97RSfyQwK2EH6IQ7Vb2U7Ad/5sDsVKC/Kx6hxt2fbR 
> ZkWPqVXAs7SbZIwAyeUggVEhz6n0XKzAYk7lsbNOzitwAWIXuzqk+5Hu/anDsTmt 
> lS144lIyhuIKNPgwv02eNg4wH5hytXwK+kf1Z/4H+LcNu5szxMtREb2/PBvm/nQC 
> zoJYZV1+sTmSjKKOb8DoX5i+dVdhgbQzvu/XBIJBLbUn4NSQiAlEKnArBeD2H01Z 
> K1u37aIITOgcFqigDnLQEfIfzl+nng/O22W9RISPEOMyjE+9wcmgYXiKAt1RY2C5 
> LjJQwhIkb94Aqzv288ip2131NxZq/eoGO8neQNBRRM4BoYbeP9gDT9D+BF8bnkQL 
> FO5emHWj7oLdtcUteyMKKgdP/ryrwHiAQ2MBUIMVfPmmmCD2PN1M8v6nmPV0mbCH 
> dQ6GeHlr/6Gh3rpoNFb/ 
> =L0Pv 
> -END PGP SIGNATURE- 
>

-- 
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/c6f9d495-54fb-4155-8527-dfbde8bc1dc0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Desperately need Django help!

2015-01-21 Thread Collin Anderson
Hi,

A new CSRF token gets generated after you log in, so you'll need to ask 
django for the new one, or simply ready the new value from document.cookie.

Collin

On Monday, January 19, 2015 at 3:08:34 AM UTC-5, Neil Asnani wrote:
>
> Hi, I am trying to build a single page, restful application to track 
> expenses that allows users to sign up, log in, and edit / delete / filter 
> expenses, all on a single page. I am very new to Django, and all other web 
> technologies and this app is making my head spin. I have been working on 
> this for the past week now and have made progress but I am getting errors 
> left and right and do not know how to resolve them. I am also having 
> difficulty finding and following the tutorials online. I am however not new 
> to programming and once I get past this initial road block should pick 
> things up quickly.
>
> The code is here: https://github.com/tested22/Expense-tracker1 I am 
> currently getting a csrf token error when I merged the log in and sign up 
> pages onto home.html, though I have the csrf token tags in the forms.
>
> Could someone please spend some time with me via Skype or Google hangouts 
> to explain Django and help me troubleshoot my application? I would be so 
> thankful and we could work out a form of payment.
>

-- 
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/bdb01abf-9523-4509-8793-17e6f7ffc614%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Canvas OAuth2 From Django View

2015-01-21 Thread Collin Anderson
Hi Henry,

You need to send some kind of response back to the browser and the user. 
Maybe a message? or a maybe redirect to another page?

def final_step(request):
code = request.GET['code']
r = requests.post('https:///login/oauth2/token', {
'code': code, 'client_id': 'etc'}
access_code = r.json()['access_code']
return HttpResponse('Successfully Logged in! Here's your access_code: %s' 
% access_code)

Collin

On Sunday, January 18, 2015 at 7:01:12 PM UTC-5, Henry Versemann wrote:
>
> Collin, thanks for the help. My django application as it is already has 
> the "requests" library installed within it and I have already registered it 
> with the API which I'm trying to authenticate to currently using that API's 
> oauth2 web application flow, which is a three step process (see the oauth2 
> tab for the  Canvas API). I'm able so far to send a redirect-uri to the 
> Canvas Oauth2 api and have it respond back to me with all of the other 
> information I need to get my final access token from then. My application 
> currently uses Python 2.7.8 and Django 1.7 and the piece of the process 
> that I'm having the problem with is sending the final POST request back to 
> the Canvas Oauth2 flow API. The response that up to now I've tried to 
> return back from my django view  has been an HttpResponse which apparently 
> does not allow the sending of a POST request. I've also taken a look at all 
> of the shortcut functions that django offers as options to return back from 
> django views, and none of them appear at least not obviously to offer any 
> options for sending POST requests. Your response below seems to show how I 
> might get the access token back from the final POST request which I need to 
> make to the Canvas Oauth2 flow. Can you show me how to do that POST, 
> and what I need my view to return, to avoid getting and error which says 
> that my view did  not return a valid HttpResponse but instead returned 
> "None" like I've gotten up until now?
> Thanks again for the help.
>
> Henry 
>
> On Saturday, January 17, 2015 at 7:33:40 AM UTC-6, Collin Anderson wrote:
>
>> Hi,
>>
>> Use urllib/urllib2 or requests to POST to other websites. Python can do 
>> it natively.
>>
>> try:  # Python 3
>> from urllib import request as urllib_request
>> except ImportError:  # Python 2
>> import urllib2 as urllib_request
>> from django.utils.http import urlencode
>>
>> def my_view(request):
>> response = urllib_request.urlopen('https://endpoint/', urlencode({
>> 'mytoken': '12345'}))
>> data = response.read()
>> # etc
>>
>> https://docs.python.org/3/library/urllib.request.html
>> https://docs.python.org/2/library/urllib2.html
>>
>> or install requests, which is friendlier:
>> http://docs.python-requests.org/en/latest/
>>
>> Collin
>>
>> On Thursday, January 15, 2015 at 11:51:45 AM UTC-5, Henry Versemann wrote:
>>>
>>> First let me say that I haven't done a lot of stuff with either Python 
>>> or Django, but I think I understand most of the basics. 
>>> I am trying to get an access token back from the OAuth2 Web Application 
>>> Flow of the Canvas' LMS API ( 
>>> https://canvas.instructure.com/doc/api/file.oauth.html ). 
>>> I have successfully sent the request in step 1 of the flow, and 
>>> received back and extracted out of the response all of the data needed for 
>>> step 3, which came back in step 2 of the flow.
>>> So now in step 3 of the flow my problem is how to send a POST of the 
>>> request needed, as described in step 3 of the flow, from a Django View.
>>> I've not found anything definitive saying that I absolutely can't do 
>>> a POST of a request, from a Django View, and have seen some  items which 
>>> seem to indicate that I can do a POST from a view, but none of them seem to 
>>> have detailed code examples or explanations of how to do it if it is 
>>> possible. 
>>> So far I've tried several ways of sending the POST within a 
>>> returned HttpResponse and have not been successful, and if I understand 
>>> things correctly HttpResponse doesn't allow it. 
>>> I have also looked at all of the other Django Shortcut Functions 
>>> documentation, and none of them seem to offer any obvious way of POSTing a 
>>> request either. 
>>> Can someone please point me to a good example of how to do it if it is 
>>> possible, and if it is not maybe point me to one or more examples of how I 
>>> might be able to successfully go through the Canvas OAuth2 Web Application 
>>> Flow using some other

Re: Queryset .count() breaks when counting distinct values generated by .extra()

2015-01-21 Thread Collin Anderson
Hi,

I don't use extra() a lot, but it could be that count() clears out extra. 
This doesn't exactly answer your question, but you may want to try your 
query on the 1.8 alpha using the new available expressions. You might be 
able to do this without needing extra() at all in 1.8.

Collin

On Sunday, January 18, 2015 at 3:24:49 PM UTC-5, Mattias Linnap wrote:
>
> Hi all,
>
> I think I've found a strange case where QuerySet.count() does not match 
> len(queryset), and the behaviour is certainly unexpected.
> But I'm not sure whether this is a bug, some mistake on my part, or a 
> known limitation of combining .extra(), .distinct() and .count().
> I am aware of the default ordering interfering with .distinct(), and 
> already add .order_by() to get rid of it.
>
> I have a model called RadioSignal, with an integer field "rssi". I'm 
> interested in finding out how many distinct values for "rssi / 10" there 
> are (-10, -20, -30, etc).
>
> Here is a commented "./manage.py shell" record:
>
> >>> RadioSignal.objects.count()
> 523 
> >>> RadioSignal.objects.order_by().values('rssi').distinct().count() 
> 49
> >>> connection.queries[-1]['sql']
> 'SELECT COUNT(DISTINCT "maps_radiosignal"."rssi") FROM "maps_radiosignal"'
>
> Looks okay so far. But I'm interested in each distinct tens of RSSI 
> values, not every single value. I can compute these with .extra():
>
> >>> len(RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct())
> 6
> >>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct()
> [{'tens': -8}, {'tens': -4}, {'tens': -5}, {'tens': -9}, {'tens': -6}, 
> {'tens': -7}]
> >>> connection.queries[-1]['sql']
> 'SELECT DISTINCT (rssi / 10) AS "tens" FROM "maps_radiosignal" LIMIT 21'
>
> Also looks good so far. But running len() on a queryset is unnecessary if 
> I only need the count.
>
> >>> RadioSignal.objects.order_by().extra({'tens': 'rssi / 
> 10'}).values('tens').distinct().count()
> 523
> >>> connection.queries[-1]['sql']
> 'SELECT COUNT(DISTINCT "maps_radiosignal"."id") FROM "maps_radiosignal"'
>
> Uhoh. Somehow .count() keeps the .distinct() part, but replaces the 
> .extra() and .values() parts with counting primary keys?
>
> I tried it with values('tens'), values_list('tens'), and 
> values_list('tens', flat=True), as well no change.
> So far I've tested Django 1.6 with Python 2.7 and PostgreSQL 9.3, and 
> Django 1.7 with Python 3.4 and PostgreSQL 9.1, all seem to behave the same.
>
> I can work around this, since the possible resulting querysets are pretty 
> small, and evaluating them with len() isn't too slow. But I'm wondering if 
> it's a bug in Django, or something else I've missed?
>
> Mattias
>
>
>

-- 
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/1b2f6dae-712f-4cb3-b8d3-26560198efaa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Help a newb with authentication and registration

2015-01-19 Thread Collin Anderson
Hi,

Here's a nice tutorial:
http://musings.tinbrain.net/blog/2014/sep/21/registration-django-easy-way/

Collin

On Saturday, January 17, 2015 at 1:20:56 PM UTC-5, Ben Gorman wrote:
>
> I've spent the past few weeks trying to set up a custom (but not 
> unreasonable) user registration and authentication flow using allauth for 
> my site.
>
> - email instead of username
> - a (not necessarily unique) display name
> - email verification required
>
> (more details and a skeleton project here 
> 
> )
>
> I'm very lost on how to accomplish this.  I've already paid someone $150 
> through Odesk.com to help me, and although they got it working they didn't 
> explain anything and left me very much in the dark.  
>
> So, I'm looking for people's advice on how I can write and understand the 
> registration/authentication system that I need.  For example, do I need to 
> write my own custom user model or does allauth handle everything I need? 
>  How do I handle superusers?  Do I need to make my own "accounts" app?  Are 
> there good tutorials on using allauth (I couldn't find many)? etc. 
>  Basically I'll take any advice.
>
> Also, if anyone's willing to give me some personal tutoring/help on this 
> topic I'd be very appreciative and am willing to pay.
>
> Thanks
>

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


Re: How to make generic variables available in settings and contexts?

2015-01-19 Thread Collin Anderson
Hi All,

Also, check out assignment_tags if you haven't seen them.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags

Collin

On Sunday, January 18, 2015 at 8:09:58 AM UTC-5, James Schneider wrote:
>
> If you need it in all of (or a large majority of) your templates, stick 
> with the context processor you originally posted, just replace the 
> Category.objects.get() call with the custom manager call. Your templates 
> would then have access to {{ MAIN_CATEGORY }}. And with a context 
> processor, that literally means every template, including login forms, 
> password resets, etc. which may or may not be acceptable.
>
> If you don't necessarily need it in all templates, but you are using 
> class-based views, you can write a custom mixin that overrides 
> get_context_data() to add in the MAIN_CATEGORY variable for your templates, 
> but only if you are not using the aforementioned context processor to 
> populate it (otherwise you are doubling the work to set the same variable).
>
> Templates are the only tricky part here. Everywhere else you can call your 
> custom manager method directly.
>
> -James
> On Jan 18, 2015 4:47 AM, "ThomasTheDjangoFan" <
> stefan.eich...@googlemail.com > wrote:
>
>> Hi James,
>>
>> thanks a lot for pointing me to the models.Mangager option. Now this is 
>> really interesting. I will definetly check out how caching works.
>>
>> Now the question is:
>> How do I now access the CategoryManager.get_main_category() in my 
>> template.html? I guess I have to pass it over to context within the view?
>>
>>
>> Am Sonntag, 18. Januar 2015 12:28:30 UTC+1 schrieb James Schneider:
>>>
>>> If I understand you right, you want to set MAIN_CATEGORY as a "global" 
>>> variable/setting containing a Category object with an ID of 1. Is that 
>>> right? If so...
>>>
>>> Rather than populating a "global" variable, I would instead create a 
>>> custom model manager for the Category model:
>>>
>>> https://docs.djangoproject.com/en/1.7/topics/db/managers/
>>> #custom-managers
>>>
>>>  It would be a pretty simple override just to add an extra method:
>>>
>>> class CategoryManager(models.Manager):
>>> def get_main_category(self):
>>> return Category.objects.get(pk=1)
>>>
>>> class Category(models.Model):
>>> <...other fields...>
>>> objects = CategoryManager()
>>>
>>>
>>> Then, anywhere you needed the value that would be accessed via 
>>> MAIN_CATEGORY, you would instead use 'main_category = 
>>> Category.objects.get_main_category()'.
>>>
>>> If you ever need to change the category that is returned, the only place 
>>> you'll need to update the code/PK is in the manager method definition. Much 
>>> more flexible than a simple variable in settings.py.
>>>
>>> Realize that the example above is quite a naive/simplistic 
>>> implementation, and can benefit from other optimizations (such as a basic 
>>> caching mechanism in the CategoryManager in the event it is called multiple 
>>> times during a request to avoid multiple queries for the same data, among 
>>> others). Check out https://github.com/django/django/blob/master/django/
>>> contrib/auth/backends.py#L41 for how Django handles caching for 
>>> permission checks (which are often called multiple times per request). 
>>>
>>> To avoid the dependency on a specific key/PK, you may want to consider 
>>> adding a boolean field to Category called 'is_main' that defaults to False. 
>>> Then set the field to True for the single category you want to be the main 
>>> one. Then your manager query would look like 
>>> Category.objects.get(is_main=True). 
>>> Just make sure you only have one category with is_main set to True (if you 
>>> change your mind on which category will be the main category, set all of 
>>> the Categories to False, and then reset the new main category to True). If 
>>> you are confident that it will never change, though, you'll probably be 
>>> fine.
>>>
>>> -James
>>>
>>>
>>> On Jan 18, 2015 2:26 AM, "ThomasTheDjangoFan" >> googlemail.com> wrote:
>>>
 Ladies and gentleman,

 I am new to Django and would really love to have a solution for this:

 My goal is to share generated settings between my views/models and 
 templates, without repeating myself.

 Right now I have following code, where the problem appears:

 #MY_CONTEXT_PROCESSOR.PY
 from django.conf import settings

 def setDataToContext (request):
 """
 Send settings to context of tempalte
 """

 #GENERATED STUFF
 #Prepare common Objects
 main_category = Category.objects.get(id=1)

 return {
 'settings': settings, # Global Django Settings
 'MAIN_CATEGORY': main_category, # Make category available in 
 template - Question: How do I make this available in views/models as 
 settings.MAIN_CATEGORY?
 }


 The main question is:

 *How can I make 

Re: formset - how to set a from error from formset.clean?

2015-01-19 Thread Collin Anderson
Hi,

You might be able to do something like:

self.forms[3].add_error('field_name', 'error message')

https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.add_error

Collin

On Saturday, January 17, 2015 at 10:46:27 PM UTC-5, Richard Brockie wrote:
>
> Hi everyone,
>
> In a formset I can use the .clean() method to validate data across the 
> formset. The formset.clean() method is run after all the form.clean() 
> methods - this makes sense. Raising a formset ValidationError alerts the 
> user to the problem with formset.non_form_errors.
>
> I would like to also set an error condition on one of more of the 
> individual forms as a result of this formset validation failure to help 
> identify the location of the problems (my formsets can be quite long and 
> this will help guide the eye). I've spent quite a lot of time looking for 
> such an example with no success. Is there a way I can do this?
>
> Here's some pseudo-code to outline what I want to do:
>
> call MyFormSet(BaseFormSet):
> def clean(self):
> super(MyFormSet, self).clean()
>
> # validation code goes here...
>
> if some_validation_error:
> raise ValidationError(...)# creates the formset error 
> message
>
> create_error_in_identified_forms(somehow)#  I want to 
> know how to do this bit
>
> Thanks & best wishes!
> R.
>

-- 
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/ac19922b-a623-4083-9b86-e1ab4bf5892d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Uniqueness of "."

2015-01-19 Thread Collin Anderson
Hi,

Yes, looking at the code, it appears that there's nothing preventing you 
from creating clashing custom permissions.

Ideally, the unique_together should be on ('content_type__app_name', 
'codename') if that's even possible.

Collin

On Friday, January 16, 2015 at 1:37:02 PM UTC-5, Torsten Bronger wrote:
>
> Hallöchen! 
>
> According to 
> <
> https://docs.djangoproject.com/en/1.7/ref/contrib/auth/#django.contrib.auth.models.User.has_perm>,
>  
>
> the permission is defined with ".". 
> However, the unique_together option says (('content_type', 
> 'codename'),).  So, in an app "foo", one could define a permission 
> codename "edit_bar" in two different models, and foo.edit_bar would 
> not be unique. 
>
> Does this mean I must take care myself that such name clashs don't 
> occur? 
>
> Tschö, 
> Torsten. 
>
> -- 
> Torsten BrongerJabber ID: torsten...@jabber.rwth-aachen.de 
>  
>   or http://bronger-jmp.appspot.com 
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To 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/3252bcae-12a9-4db3-a297-28e61ce12c21%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: post_save signal not working in Django 1.7

2015-01-19 Thread Collin Anderson
Hi,

Are you using AUTH_USER_MODEL?

I assume your logging is set up correctly?

Here's a snippet from one of my projects if you want to try out some 
similar code:

def user_save_handler(sender, **kwargs):
user = kwargs['instance']
try:
user.userprofile
except UserProfile.DoesNotExist:
user_profile = UserProfile(user=user)
user_profile.__dict__.update(user.__dict__)
user_profile.save()
post_save.connect(user_save_handler, sender=User)

Collin

On Friday, January 16, 2015 at 1:14:09 PM UTC-5, Zach LeRoy wrote:
>
> I have a block of code that works fine in Django 1.6.10 but does not work 
> at all in Django 1.7.3.  I would expect my log statement to print every 
> time a Django User is created and this is the behavior in 1.6.10:
>
> import logging
>
> from django.contrib.auth.models import User
> from django.db import models
> from django.db.models.signals import post_save
> from django.dispatch import receiver
>
> log = logging.getLogger(__name__)
>
>
> class UserProfile(models.Model):
> uuid = models.CharField(max_length=36)
> user = models.OneToOneField(User)
>
>
> @receiver(post_save, sender=User)
> def create_user_profile(sender, instance, created, **kwargs):
> """
> When a new user is created, add a UserProfile
> """
> log.debug('received post save signal: {}'.format(instance))
> if created:
> UserProfile.objects.create(user=instance)
>

-- 
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/7815f84e-9042-4ef1-ac76-e160fefe5782%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Admin UI Bug - 1.7.3

2015-01-18 Thread Collin Anderson
Hi,

Rename your __unicode__ to __str__. Python 3 doesn't know what 
"__unicode__" is. :)

You say this works fine:
>>> from ccdgen.models import DvBoolean,DvAny, Common, Project
>>> pcts = DvBoolean.objects.all()
>>> for p in pcts:
...   print(p.prj_name.prj_name)

But django is expecting this also to work:
>>> pcts = DvBoolean.objects.all()
>>> for p in pcts:
...   print(p.prj_name)

Collin

On Sunday, 18 January 2015 12:31:06 UTC-5, Timothy W. Cook wrote:
>
>
> On Sat, Jan 17, 2015 at 11:49 AM, Collin Anderson <cmawe...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> Did you also switch to Python 3?
>>
>
> ​Yes. 
>
> Well, I didn't switch. I have been using Python 3 for quite some time.  
> Even before it was officially supported. 
> ​
>  
>
>> It doesn't seem to be using your __unicode__ method at all.
>> If you query one of these Projects in manage.py shell, do they show the 
>> project name?
>>
>
> ​As I said before, my views that use AJAX to return data from queries 
> still work just as before.  But yes, in the manage.py shell I can import 
> the models and print the names.
>
> >>> from ccdgen.models import DvBoolean,DvAny, Common, Project
> >>> pcts = DvBoolean.objects.all()
> >>> for p in pcts:
> ...   print(p.prj_name.prj_name)
>  
> caBIG
> caBIG
> caBIG
> caBIG
> caBIG
> caBIG
> caBIG
>
> ... 
>
>
>
>  
>
>> Are you sure that the __unicode__ method is actually attached to your 
>> model?
>>
>>
> I am not exactly sure what you mean by that question; attached?​Here 
> is the code: ​
>
> class Project(models.Model):
> """
> Every item created in CCDGEN must be assigned to a Project when 
> created. All items (except CCD) may be
> reused in multiple CCDs. However, this does not change the original 
> Project.
> The Allowed Groups field contains each of the User Groups allowed to 
> see each item with this Project name.
> The User Group, Open, is assigned to every user. So if you assign the 
> Open group as one of the allowed groups,
> all CCDGEN users will see this item.
> """
> pgroup = models.ForeignKey(Group, verbose_name='Primary Group', 
> related_name='primarygroup', null=True)
> prj_name = models.CharField(_("project name"), max_length=110, 
> unique=True, db_index=True, help_text=_('Enter the name of your project.'))
> description = models.TextField(_("project description"), blank=True, 
> help_text=_('Enter a description or explaination of an acronym of the 
> project.'))
> rm_version = models.ForeignKey(RMversion, verbose_name=_('rm 
> version'), related_name='%(class)s_related', help_text=_('Choose the 
> version of the MLHIM Reference Model you are using.'))
> allowed_groups = models.ManyToManyField(Group, verbose_name=_('allowed 
> groups'), related_name='%(class)s_related', help_text=_('Choose the groups 
> that are allowed to work in this project.'))
>
> def __unicode__(self):
> return self.prj_name
>
>
> class Meta:
> verbose_name = _("Project")
> verbose_name_plural = _("Projects")
> ordering = ['prj_name']
>
>
>  
>
>> Also, FYI, to_field="prj_name" means you can't easily change the name of 
>> the project.
>>
>>
> ​Yes, Once created the name cannot be changed, and once an item is 
> assigned to a project the attached items are immutable. 
>
> Thanks,
> Tim
>
>
>  
>
>> Collin
>>
>> On Friday, January 16, 2015 at 3:14:55 PM UTC-5, Timothy W. Cook wrote:
>>>
>>> I should also mention that I have some AJAX calls for the same 
>>> information and they still work fine.  So I am quite certain it is in the 
>>> Admin templates or the Admin properties definitions. 
>>>
>>> On Fri, Jan 16, 2015 at 5:56 PM, Timothy W. Cook <t...@mlhim.org> wrote:
>>>
>>>> Is this a bug or did I miss something in the release notes?  
>>>>
>>>> ​Moving from 1.6.4 to 1.7.3  the listing in the Admin UI is not 
>>>> resolving a related field now.  There are not any model changes involved. 
>>>>
>>>> Attached are two screen shots named for the versions.
>>>>
>>>> I haven't changed the admin code either.  For the screen shots the 
>>>> admin code is:
>>>>
>>>> ​class DvBooleanAdmin(admin.ModelAdmin):
>>>> list_filter = ['prj_name__rm_version__version_id','prj_name',]
>>>&g

Re: Django Admin UI Bug - 1.7.3

2015-01-17 Thread Collin Anderson
Hi,

Did you also switch to Python 3?
It doesn't seem to be using your __unicode__ method at all.
If you query one of these Projects in manage.py shell, do they show the 
project name?
Are you sure that the __unicode__ method is actually attached to your model?

Also, FYI, to_field="prj_name" means you can't easily change the name of 
the project.

Collin

On Friday, January 16, 2015 at 3:14:55 PM UTC-5, Timothy W. Cook wrote:
>
> I should also mention that I have some AJAX calls for the same information 
> and they still work fine.  So I am quite certain it is in the Admin 
> templates or the Admin properties definitions. 
>
> On Fri, Jan 16, 2015 at 5:56 PM, Timothy W. Cook  > wrote:
>
>> Is this a bug or did I miss something in the release notes?  
>>
>> ​Moving from 1.6.4 to 1.7.3  the listing in the Admin UI is not resolving 
>> a related field now.  There are not any model changes involved. 
>>
>> Attached are two screen shots named for the versions.
>>
>> I haven't changed the admin code either.  For the screen shots the admin 
>> code is:
>>
>> ​class DvBooleanAdmin(admin.ModelAdmin):
>> list_filter = ['prj_name__rm_version__version_id','prj_name',]
>> search_fields = ['data_name','ct_id']
>> ordering = ['prj_name','data_name']
>> actions = [make_published, unpublish, copy_dt, republish]
>> readonly_fields = 
>> ['published','schema_code','r_code','xqr_code','xqw_code',]
>> def get_form(self, request, obj=None, **kwargs):
>> try:
>> if obj.published:
>> self.readonly_fields = 
>> ['prj_name','published','lang','schema_code','data_name','valid_trues','valid_falses','description','sem_attr','resource_uri','asserts','xqr_code','xqw_code',]
>> except (AttributeError, TypeError) as e:
>> self.readonly_fields = 
>> ['published','schema_code','r_code','xqr_code','xqw_code',]
>> return super(DvBooleanAdmin, self).get_form(request, obj, 
>> **kwargs)
>>
>> fieldsets = (
>> (None, {'classes':('wide',),
>>   
>>  
>> 'fields':('published','prj_name','data_name','lang','valid_trues','valid_falses')}),
>> ("Additional Information ", {'classes':('wide',),
>>   
>>  'fields':('description','sem_attr','resource_uri','asserts',)}),
>> ("PCT Code (read-only)", {'classes':('collapse',),
>>   
>>  'fields':('schema_code','r_code','xqr_code','xqw_code',)}),
>>
>> )
>> list_display = ('data_name','prj_name','published',)
>> admin.site.register(DvBoolean, DvBooleanAdmin)
>>
>> ​In the model for the displayed admin:
>> ​prj_name = models.ForeignKey(Project, verbose_name=_("Project 
>> Name"), to_field="prj_name", help_text=_('Choose the name of your 
>> Project.'))
>>
>> ​and the related field in Project is:
>> prj_name = models.CharField(_("project name"), max_length=110, 
>> unique=True, db_index=True, help_text=_('Enter the name of your project.'))
>>
>> ...
>>
>> def __unicode__(self):
>> return self.prj_name
>> ​
>>
>>
>> ​Any ideas?​
>>
>> Should I file a bug report? 
>>
>> ​Thanks,
>> Tim
>> ​
>>
>>
>>
>>  
>>
>> 
>> Timothy Cook
>> LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
>> MLHIM http://www.mlhim.org
>>
>>  
>
>
> -- 
>
> 
> Timothy Cook
> LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
> MLHIM http://www.mlhim.org
>
> 

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


Re: Canvas OAuth2 From Django View

2015-01-17 Thread Collin Anderson
Hi,

Use urllib/urllib2 or requests to POST to other websites. Python can do it 
natively.

try:  # Python 3
from urllib import request as urllib_request
except ImportError:  # Python 2
import urllib2 as urllib_request
from django.utils.http import urlencode

def my_view(request):
response = urllib_request.urlopen('https://endpoint/', urlencode({
'mytoken': '12345'}))
data = response.read()
# etc

https://docs.python.org/3/library/urllib.request.html
https://docs.python.org/2/library/urllib2.html

or install requests, which is friendlier:
http://docs.python-requests.org/en/latest/

Collin

On Thursday, January 15, 2015 at 11:51:45 AM UTC-5, Henry Versemann wrote:
>
> First let me say that I haven't done a lot of stuff with either Python or 
> Django, but I think I understand most of the basics. 
> I am trying to get an access token back from the OAuth2 Web Application 
> Flow of the Canvas' LMS API ( 
> https://canvas.instructure.com/doc/api/file.oauth.html ). 
> I have successfully sent the request in step 1 of the flow, and 
> received back and extracted out of the response all of the data needed for 
> step 3, which came back in step 2 of the flow.
> So now in step 3 of the flow my problem is how to send a POST of the 
> request needed, as described in step 3 of the flow, from a Django View.
> I've not found anything definitive saying that I absolutely can't do 
> a POST of a request, from a Django View, and have seen some  items which 
> seem to indicate that I can do a POST from a view, but none of them seem to 
> have detailed code examples or explanations of how to do it if it is 
> possible. 
> So far I've tried several ways of sending the POST within a 
> returned HttpResponse and have not been successful, and if I understand 
> things correctly HttpResponse doesn't allow it. 
> I have also looked at all of the other Django Shortcut Functions 
> documentation, and none of them seem to offer any obvious way of POSTing a 
> request either. 
> Can someone please point me to a good example of how to do it if it is 
> possible, and if it is not maybe point me to one or more examples of how I 
> might be able to successfully go through the Canvas OAuth2 Web Application 
> Flow using some other module or package, that I can integrate into my 
> Django application?
> Thanks for the help.
>

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


Re: Integration with Legacy DB

2015-01-17 Thread Collin Anderson
Hi,

It should be possible to re-write you select statement using the Django 
ORM, but there's not an automatic way to convert it. There's also raw() 
which might take the statement as is.
https://docs.djangoproject.com/en/dev/topics/db/sql/

Collin

On Wednesday, January 14, 2015 at 11:05:08 AM UTC-5, fred wrote:
>
>  Although I have not tried it, the docs are pretty clear about how to 
> sync a django model to an existing legacy DB (sqlserver08 in this case).
>
>  
>
> But is there a way to sync to a select statement with multi-table joins 
> without first creating a View?
>
>  
>
> I know that creating a view would be easiest, but I’ve got some 
> policy/security issues in my organization that require jumping through 
> additional hoops and am hoping there is some Django “magic” to solve this.
>
>  
>
> Thanks,
>
>  
>
> Fred.
>  

-- 
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/0621324f-f7bc-4ed5-9b3b-3f5869d9c5f9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


  1   2   3   4   5   6   7   >