Re: Authentication when usernames are not unique

2015-01-19 Thread James Schneider
BTW, I reread you're last note. The references to AbstractBaseUser were
meant for inheritance, meaning that your custom user would inherit all of
the same properties and not need to redefine the wheel. You can't inherit
from AbstractUser though because you are modifying the username field.

-James
On Jan 19, 2015 11:32 PM, "James Schneider"  wrote:

> "A pallet of authentication systems..."
>
> Yep, you work for an educational entity, as do I. :-D
>
> You can pursue the LegacyUser model as your custom user model. That would
> make your LegacyUser objects the 'local' Django users that have been
> referenced. Not sure about the name though, might indicate that there are
> CurrentUsers floating about the system.
>
> Another option is to rename LegacyUser to something like AppUser, and then
> add an extra user_type field to the model for filtering/identification.
>
> Or if you only have one type of user, you probably don't need to worry
> about it.
>
> Keep us in the loop, I'd be interested in a high-level solution.
>
> -James
>  On Jan 19, 2015 10:54 PM, "Erik Cederstrand" 
> wrote:
>
>> Hi guys,
>>
>> Thanks for a lot of useful answers! My schools use a palette of
>> authentication systems; regular hashed password check with a hash I have
>> access to, LDAP auth and WAYF (a Danish educational SSO solution using
>> Shibboleth). Those are the least of my worries right now, though.
>>
>> I'll have a look at the AbstractBaseUser and friends. Ideally, I'd like
>> to expand on my existing LegacyUser model and avoid creating separate
>> Django users that shadow the LegacyUser, as I do a lot of synchronization
>> of LegacyUsers with the legacy system. I'll see how it goes and post a
>> solution if I get that far.
>>
>> Erik
>>
>> > Den 19/01/2015 kl. 23.24 skrev James Schneider > >:
>> >
>> > For a pure authentication scenario where permission checks never go
>> beyond user.is_authenticated(), that's probably true. If all the OP is
>> doing is displaying data, they may be able to get away with manually
>> associating the campus and user within the session after, and displaying
>> data based on those session keys. Basically you would end up with a boolean
>> layer of protection for each resource, because all you know is the
>> validated username and campus pair. That may work just fine.
>> >
>> > However, if you need any sort of authorization (permission checking)
>> within the app using Django's permission system, you'll probably need a
>> local copy of the user using a custom user model in the database to perform
>> checks against. It sounds like the OP may need that. Otherwise you are also
>> looking at rolling a custom authorization backend as well.
>> >
>> > If they are LDAP services, you can look at django-ldap, which works
>> quite nicely, including group membership restrictions. It also does the
>> overriding of the authentication backend for you. Not sure how it would
>> work with multiple LDAP servers for various campuses though. That would
>> need some research.
>> >
>> > TL;DR; There are a lot of ways to slice this problem, and a primary
>> strategy driver will be the available authentication backends at each
>> campus. Hopefully they are all the same.
>> >
>> > -James
>> >
>> >
>> > On Mon, Jan 19, 2015 at 2:06 PM, Stephen J. Butler <
>> stephen.but...@gmail.com> wrote:
>> > Shibboleth 2.0 lets you setup a discovery service (or portal would
>> > perhaps be a better term) letting the user select which ID Provider
>> > (IdP) they will authenticate to. All you have to do on the Service
>> > Provider (SP) side is specify the discovery URL and what IdPs you
>> > allow. Nothing needs to be done in your Django app except support
>> > Shibboleth.
>> >
>> > Of course, this is all predicated on there being a competent
>> > Shibboleth setup at your institutions.
>> >
>> > --
>> > You received this message because you are subscribed to the Google
>> Groups "Django users" group.
>> > To unsubscribe from this group and stop receiving emails from it, send
>> an email to django-users+unsubscr...@googlegroups.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/CAD4ANxVp4C2QcxAcY6Xui1bc6Z-hcV--sfOSEy%3DmcaW_w%2BpGHw%40mail.gmail.com
>> .
>> > For more options, visit https://groups.google.com/d/optout.
>> >
>> >
>> > --
>> > You received this message because you are subscribed to the Google
>> Groups "Django users" group.
>> > To unsubscribe from this group and stop receiving emails from it, send
>> an email to django-users+unsubscr...@googlegroups.com.
>> > To post to this group, send email to django-users@googlegroups.com.
>> > Visit this group at http://groups.google.com/group/django-users.
>> > To view this discussion on the web visit
>> 

Re: Authentication when usernames are not unique

2015-01-19 Thread James Schneider
"A pallet of authentication systems..."

Yep, you work for an educational entity, as do I. :-D

You can pursue the LegacyUser model as your custom user model. That would
make your LegacyUser objects the 'local' Django users that have been
referenced. Not sure about the name though, might indicate that there are
CurrentUsers floating about the system.

Another option is to rename LegacyUser to something like AppUser, and then
add an extra user_type field to the model for filtering/identification.

Or if you only have one type of user, you probably don't need to worry
about it.

Keep us in the loop, I'd be interested in a high-level solution.

-James
 On Jan 19, 2015 10:54 PM, "Erik Cederstrand" 
wrote:

> Hi guys,
>
> Thanks for a lot of useful answers! My schools use a palette of
> authentication systems; regular hashed password check with a hash I have
> access to, LDAP auth and WAYF (a Danish educational SSO solution using
> Shibboleth). Those are the least of my worries right now, though.
>
> I'll have a look at the AbstractBaseUser and friends. Ideally, I'd like to
> expand on my existing LegacyUser model and avoid creating separate Django
> users that shadow the LegacyUser, as I do a lot of synchronization of
> LegacyUsers with the legacy system. I'll see how it goes and post a
> solution if I get that far.
>
> Erik
>
> > Den 19/01/2015 kl. 23.24 skrev James Schneider  >:
> >
> > For a pure authentication scenario where permission checks never go
> beyond user.is_authenticated(), that's probably true. If all the OP is
> doing is displaying data, they may be able to get away with manually
> associating the campus and user within the session after, and displaying
> data based on those session keys. Basically you would end up with a boolean
> layer of protection for each resource, because all you know is the
> validated username and campus pair. That may work just fine.
> >
> > However, if you need any sort of authorization (permission checking)
> within the app using Django's permission system, you'll probably need a
> local copy of the user using a custom user model in the database to perform
> checks against. It sounds like the OP may need that. Otherwise you are also
> looking at rolling a custom authorization backend as well.
> >
> > If they are LDAP services, you can look at django-ldap, which works
> quite nicely, including group membership restrictions. It also does the
> overriding of the authentication backend for you. Not sure how it would
> work with multiple LDAP servers for various campuses though. That would
> need some research.
> >
> > TL;DR; There are a lot of ways to slice this problem, and a primary
> strategy driver will be the available authentication backends at each
> campus. Hopefully they are all the same.
> >
> > -James
> >
> >
> > On Mon, Jan 19, 2015 at 2:06 PM, Stephen J. Butler <
> stephen.but...@gmail.com> wrote:
> > Shibboleth 2.0 lets you setup a discovery service (or portal would
> > perhaps be a better term) letting the user select which ID Provider
> > (IdP) they will authenticate to. All you have to do on the Service
> > Provider (SP) side is specify the discovery URL and what IdPs you
> > allow. Nothing needs to be done in your Django app except support
> > Shibboleth.
> >
> > Of course, this is all predicated on there being a competent
> > Shibboleth setup at your institutions.
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "Django users" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users+unsubscr...@googlegroups.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/CAD4ANxVp4C2QcxAcY6Xui1bc6Z-hcV--sfOSEy%3DmcaW_w%2BpGHw%40mail.gmail.com
> .
> > For more options, visit https://groups.google.com/d/optout.
> >
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "Django users" group.
> > To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users+unsubscr...@googlegroups.com.
> > To post to this group, send email to django-users@googlegroups.com.
> > Visit this group at http://groups.google.com/group/django-users.
> > To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXW3NoDaTTpaiL2qtD69vkjmSEFfGSeM9-Dk00YMAG6NQ%40mail.gmail.com
> .
> > For more options, visit https://groups.google.com/d/optout.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit 

Re: Authentication when usernames are not unique

2015-01-19 Thread Erik Cederstrand
Hi guys,

Thanks for a lot of useful answers! My schools use a palette of authentication 
systems; regular hashed password check with a hash I have access to, LDAP auth 
and WAYF (a Danish educational SSO solution using Shibboleth). Those are the 
least of my worries right now, though.

I'll have a look at the AbstractBaseUser and friends. Ideally, I'd like to 
expand on my existing LegacyUser model and avoid creating separate Django users 
that shadow the LegacyUser, as I do a lot of synchronization of LegacyUsers 
with the legacy system. I'll see how it goes and post a solution if I get that 
far.

Erik

> Den 19/01/2015 kl. 23.24 skrev James Schneider :
> 
> For a pure authentication scenario where permission checks never go beyond 
> user.is_authenticated(), that's probably true. If all the OP is doing is 
> displaying data, they may be able to get away with manually associating the 
> campus and user within the session after, and displaying data based on those 
> session keys. Basically you would end up with a boolean layer of protection 
> for each resource, because all you know is the validated username and campus 
> pair. That may work just fine.
> 
> However, if you need any sort of authorization (permission checking) within 
> the app using Django's permission system, you'll probably need a local copy 
> of the user using a custom user model in the database to perform checks 
> against. It sounds like the OP may need that. Otherwise you are also looking 
> at rolling a custom authorization backend as well.
> 
> If they are LDAP services, you can look at django-ldap, which works quite 
> nicely, including group membership restrictions. It also does the overriding 
> of the authentication backend for you. Not sure how it would work with 
> multiple LDAP servers for various campuses though. That would need some 
> research.
> 
> TL;DR; There are a lot of ways to slice this problem, and a primary strategy 
> driver will be the available authentication backends at each campus. 
> Hopefully they are all the same.
> 
> -James
> 
> 
> On Mon, Jan 19, 2015 at 2:06 PM, Stephen J. Butler  
> wrote:
> Shibboleth 2.0 lets you setup a discovery service (or portal would
> perhaps be a better term) letting the user select which ID Provider
> (IdP) they will authenticate to. All you have to do on the Service
> Provider (SP) side is specify the discovery URL and what IdPs you
> allow. Nothing needs to be done in your Django app except support
> Shibboleth.
> 
> Of course, this is all predicated on there being a competent
> Shibboleth setup at your institutions.
> 
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.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/CAD4ANxVp4C2QcxAcY6Xui1bc6Z-hcV--sfOSEy%3DmcaW_w%2BpGHw%40mail.gmail.com.
> For more options, visit https://groups.google.com/d/optout.
> 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXW3NoDaTTpaiL2qtD69vkjmSEFfGSeM9-Dk00YMAG6NQ%40mail.gmail.com.
> For more options, visit https://groups.google.com/d/optout.

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


Re: Authenticate users with both username and email

2015-01-19 Thread Abraham Varricatt
Damn. That's one heck of an explanation James! And very detailed to boot!

As a programmer, the OP's approach to login a user with either 
username/email with ONLY the default auth system seemed flawed (or 
incomplete, at best) to me. You've not just validated my opinion, but given 
me a wonder explanation to dig into. Thanks a lot! :)

Learning more django,
Abraham V.


On Monday, January 19, 2015 at 4:03:35 PM UTC+5:30, James Schneider wrote:
>
> I guess I'm not clear on what you are trying to achieve. There are a 
> couple of scenarios to consider.
>
> As it stands with the default contrib.auth authentication backend, sending 
> both the username and email address entered by the user will only work IF 
> the user registered/was created using their email address as their 
> username, meaning that user.username is either their username (a string 
> that isn't their email), or an email address, regardless of what user.email 
> returns. The default contrib.auth authentication backend only looks at 
> user.username.
>
> What I suspect you want is to be able to use either user.username OR 
> user.email as the identifying tokens for the user in order to authenticate 
> them. For that, you'll need to roll at least a partial custom 
> authentication backend, in addition to the changes for the forms, etc. that 
> you've already laid out. 
>
> From 
> https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend
> :
>
> "If you wish to provide custom behavior for only part of the backend API, 
> you can take advantage of Python inheritance and subclass *ModelBackend* 
> instead of implementing the complete API in a custom backend."
>
> Specifically, you'll need to override the authenticate() method of the 
> authentication backend.
>
> I've done this, it's actually pretty easy. See:
>
>
> https://github.com/django/django/blob/master/django/contrib/auth/backends.py#L11
>
> In this case, you should also roll a custom user model as well to ensure 
> that both user.username and user.email are unique columns. If you use the 
> email address as an identifying token, it will need to be unique among all 
> users, which is not true/enforced for the built-in contrib.auth User model. 
> You will also need to override the custom User manager for your new 
> CustomUser, probably with and override for get_by_natural_key(token) so 
> that the user can be retrieved in the backend authenticate() method. The 
> key change in get_by_natural_key() being the filter for the user object 
> being changed to something like User.objects.get(Q(username=token) | 
> Q(email=token)).
>
> (If you haven't seen the Q() notation, check 
> https://docs.djangoproject.com/en/1.7/ref/models/queries/#q-objects)
>
> The custom user you probably want is somewhat similar to the example given 
> in the docs:
>
>
> https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#a-full-example
>
> You'll need to add a 'username' field back in (remember to make it unique) 
> along with several other tweaks to be able to use either a username or 
> email field. An alternative would be a custom user class inheriting from 
> AbstractBaseUser and copying in the goodies you need from AbstractUser 
> (which is probably everything except the username and email fields, which 
> you'll be defining as unique). Be sure to include the Permission mixins 
> that AbstractUser has if you intend to use the built-in permission system 
> with your CustomUser.
>
> Sorry about the lengthy message, there are a bunch of ways to tackle this, 
> but ultimately I think you'll be rolling your own user and at least part of 
> the authentication system, not to mention having to customize the user 
> forms. The user will be slightly tricky, as there is no clear inheritance 
> path that will make it easy AFAICT, but the auth backend should be just a 
> class with a single authenticate() function if you inherit from 
> ModelBackend. Be sure to either include your custom backend in 
> AUTHENTICATION_BACKENDS, or possibly even replacing it if you go with the 
> Q() query I specified earlier (since an auth request using an email would 
> generate two authentication queries if both backends are used, and the 
> username field is checked twice).
>
> TL;DR; Overriding the user forms is probably not enough, you'll need a 
> custom user and custom authentication backend.
>
> Not sure if I made the situation better or worse, but HTH...
>
> Obviously, YMMV, I haven't tried this myself, but I have done a fair bit 
> of overriding for a custom object-based permission system, which touches 
> many of the same structures above.
>
> -James
>
>
>
>
>
>
> On Mon, Jan 19, 2015 at 1:26 AM, Abraham Varricatt <
> abraham@googlemail.com > wrote:
>
>> Ignoring the malformed code, will the call to authenticate() even work 
>> without username? According to the docs,
>>
>> https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.authenticate
>>
>> It 

Any reliable django stripe payments library

2015-01-19 Thread Chen Xu
Hi Everyone,
Is there any reliable django stripe payments library that does not require
to run a python manage.py syncdb? The reason I am asking is I am uaing
SQLAlchemy instead of its builtin ORM.

Thanks



-- 
⚡ Chen Xu ⚡

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


sending email

2015-01-19 Thread sum abiut
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/CAPCf-y4CG_XVK%2Bi9G2xVNY3qNRG52TuNZwF-4g9i4jQ60%3D8OtQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
Thank you Daniel, I didn't know this! I am going to lookup how to use 
session. Thanks!

On Monday, 19 January 2015 17:13:10 UTC+8, Daniel Roseman wrote:
>
> On Monday, 19 January 2015 07:28:14 UTC, Cheng Guo wrote:
>>
>> Hello,
>>
>> I am new to Django and I have run into an issue with views.py.  I 
>> understand that there is a function behind each view. For a view that I am 
>> currently writing, it accepts a file upload from user and stores the file 
>> on the server. To do that, I need to:
>>
>> 1. check the file extension is correct
>> 2. generate a SHA-1 id for the file based on its content
>> 3. write the file to disk
>> 4. save information about the file to database
>>
>> (oh, I also created two global variables as well)
>>
>>
> Others have pointed out ways to split this up, but I wanted to pick up on 
> the last sentence. You really really should not be setting global variables 
> in your view, especially in response to user input. Global variables are 
> shared by all requests in a process, and you can't guarantee either that 
> all requests will be from the same user, or even that the same user will 
> hit the same process in subsequent requests. Don't do this: if you need to 
> store state between requests, use the db or the session.
> --
> DR.
>

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


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
Hello James:

Thank you very much for spending the time reading and answering this 
question, really appreciated!

I complete understand your suggestion of overriding the "save" method in 
the "UploadFile" to generate the id before saving. Thank you for pointing 
this out.

On the other hand, I read that it is not recommended to store files in 
database. So I decide to only store upload files on disk and save their 
file path and generated id in the database. So here is my model:

class UploadFile(models.Model):
upload_date = models.DateTimeField('timestamp', auto_now_add=True)
original_file_name = models.CharField(max_length=200)
file_id = models.CharField(max_length=40, primary_key=True)
file_path = models.CharField(max_length=500)
owner = models.ForeignKey(User)


I could use your method to override the save method, but the problem I face 
is that to generate the id, I need to pass the "UploadedFile" object to the 
 model, like this:

class UploadFile(models.Model):

def generate_id(self, uploaded_file):
 import hashlib
 hasher = hashlib.sha1()

 for chunk in uploaded_file.chunks():
 hasher.update(chunk)
 
 self.file_id = hasher.hexdigest()

def save(self, upload_file):<--- this is not gonna work since 
'save' only takes (self) as a parameter
self.generate_id(upload_file)
super(UploadFile, self).save(*args, **kwargs)

So I have two ways to solve this:

1. generate the id in the view, and simply pass it to the UploadFile's 
constructor, then call save
2. create a variable in UploadFile:

class UploadFile(models.Model):
...
self.file = None

 def generate_id(self, uploaded_file):
 import hashlib
 hasher = hashlib.sha1()

 for chunk in uploaded_file.chunks():
 hasher.update(chunk)
 
 self.file_id = hasher.hexdigest()

def save(self):
self.generate_id(self.file)
super(UploadFile, self).save(*args, **kwargs)

in my view:
  
 def upload_view(request):
 file = request.FILES['file']
 upload_file = UploadFile(...)
 upload_file.file = file
 upload_file.save()

Do you think this is a good solution?

On Monday, 19 January 2015 17:07:12 UTC+8, James Schneider wrote:
>
> I wouldn't decorate them as class methods. You would want to call them 
> from the objects themselves. For the save_to_disk() method, I was actually 
> referring to the Django save() method (
> https://docs.djangoproject.com/en/1.7/topics/db/models/#overriding-predefined-model-methods
> ).
>
> As you have it now, it wouldn't work since you would need to call 
> UploadFile.generate_id(), but you don't have an available argument to pass 
> in the UploadFile object to get the ID for. 
>
> If you remove the decorator, you would call it on the object itself:
> class UploadFile(models.Model):
>
> def generate_id(self):
> # pseudocode to do stuff to generate ID using self
> # import hashlib
> # self.file_hash = hashlib.sha1(self.file, 'rb') 
> # return the ID or None if it fails
> # return self.file_hash or None
>
> # override the model save method to generate the hash ID, then save 
> for real
> def save(self):
> self.generate_id()
> super(UploadFile, self).save(*args, **kwargs)
>
> You probably don't need to change your view logic at all in this case 
> (unless you have code that generates the hash and attaches it to the 
> object, then remove it and let the object handle that itself). Basically, 
> when your UploadFile object is saved, it will call the save() method on the 
> object, which in turn will generate the ID based on the file, attach it to 
> the object, and then save the object to the database.
>
> Note that this will run the hashing mechanism every time the object is 
> saved, whether the file it points at changes or not. If this isn't what you 
> want, I would add an extra checks in generate_id() to account for all of 
> the scenarios where you wan the hash to update (every time the object is 
> saved vs. only when the file changes vs. only generated once even with a 
> file change, etc.). 
>
> In a typical scenario where the hash is run every time the object is 
> saved, the object itself would create the hash. This way you can save the 
> object from any view (or from the shell), and it would always generate a 
> new hash automagically (new meaning recalculated, may end up the same as 
> the previous value). 
>
> TL;DR; The hash shouldn't be calculated external to the file that is 
> attached to the object, it should be calculated by the object itself.
>
> Hope that helps and makes sense...
>
> -James
>
>
> On Jan 19, 2015 12:37 AM, "Cheng Guo"  
> wrote:
>
>> So in my case, I need to generate a unique id for the file and save it to 
>> disk.
>>
>> I have a model called UploadFile, 

Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
Hello James:

Thank you very much for spending the time reading and answering this 
question, really appreciated!

I complete understand your suggestion of overriding the "save" method in 
the "UploadFile" to generate the id before saving. Thank you for pointing 
this out.

On the other hand, I read that it is not recommended to store files in 
database. So I decide to only store upload files on disk and save their 
file path and generated id in the database. So here is my model:

class UploadFile(models.Model):
upload_date = models.DateTimeField('timestamp', auto_now_add=True)
original_file_name = models.CharField(max_length=200)
file_id = models.CharField(max_length=40, primary_key=True)
file_path = models.CharField(max_length=500)
owner = models.ForeignKey(User)


I could use your method to override the save method, but the problem I face 
is that to generate the id, I need to pass the "UploadedFile" object to the 
 modal, like this:

class UploadFile(models.Model):

def generate_id(self, uploaded_file):
 import hashlib
 hasher = hashlib.sha1()

 for chunk in uploaded_file.chunks():
 hasher.update(chunk)
 
 self.file_id = hasher.hexdigest()

def save(self, upload_file):<--- this is not gonna work since 
'save' only takes (self) as a parameter
self.generate_id(upload_file)
super(UploadFile, self).save(*args, **kwargs)

So I have two ways to solve this:

1. generate the id in the view, and simply pass it to the UploadFile's 
constructor, then call save
2. create a class variable in UploadFile:

class UploadFile(models.Model):
...
self.file = None

in my view:
  
 def upload_view(request):
 file = request.FILES['file']
 upload_file = UploadFile(...)
 upload_file.file = file
 upload_file.save()

Do you think this is a good solution?


On Monday, 19 January 2015 17:07:12 UTC+8, James Schneider wrote:
>
> I wouldn't decorate them as class methods. You would want to call them 
> from the objects themselves. For the save_to_disk() method, I was actually 
> referring to the Django save() method (
> https://docs.djangoproject.com/en/1.7/topics/db/models/#overriding-predefined-model-methods
> ).
>
> As you have it now, it wouldn't work since you would need to call 
> UploadFile.generate_id(), but you don't have an available argument to pass 
> in the UploadFile object to get the ID for. 
>
> If you remove the decorator, you would call it on the object itself:
> class UploadFile(models.Model):
>
> def generate_id(self):
> # pseudocode to do stuff to generate ID using self
> # import hashlib
> # self.file_hash = hashlib.sha1(self.file, 'rb') 
> # return the ID or None if it fails
> # return self.file_hash or None
>
> # override the model save method to generate the hash ID, then save 
> for real
> def save(self):
> self.generate_id()
> super(UploadFile, self).save(*args, **kwargs)
>
> You probably don't need to change your view logic at all in this case 
> (unless you have code that generates the hash and attaches it to the 
> object, then remove it and let the object handle that itself). Basically, 
> when your UploadFile object is saved, it will call the save() method on the 
> object, which in turn will generate the ID based on the file, attach it to 
> the object, and then save the object to the database.
>
> Note that this will run the hashing mechanism every time the object is 
> saved, whether the file it points at changes or not. If this isn't what you 
> want, I would add an extra checks in generate_id() to account for all of 
> the scenarios where you wan the hash to update (every time the object is 
> saved vs. only when the file changes vs. only generated once even with a 
> file change, etc.). 
>
> In a typical scenario where the hash is run every time the object is 
> saved, the object itself would create the hash. This way you can save the 
> object from any view (or from the shell), and it would always generate a 
> new hash automagically (new meaning recalculated, may end up the same as 
> the previous value). 
>
> TL;DR; The hash shouldn't be calculated external to the file that is 
> attached to the object, it should be calculated by the object itself.
>
> Hope that helps and makes sense...
>
> -James
>
>
> On Jan 19, 2015 12:37 AM, "Cheng Guo"  
> wrote:
>
>> So in my case, I need to generate a unique id for the file and save it to 
>> disk.
>>
>> I have a model called UploadFile, so you recommend to add two class 
>> methods to the UploadFile model, like the following?
>>
>> class UploadFile(models.Model):
>> @classmethod
>> def generate_id():
>> pass
>>
>> @classmethod
>> def save_to_disk():
>> pass
>>
>>
>> On Monday, 19 January 2015 16:12:28 UTC+8, daniel.franca wrote:
>>>
>>> If the operations are model 

Re: filter

2015-01-19 Thread sum abiut
Thanks very much for all the help I am getting from you guys. your help is
very much appreciated.

cheers,


On Mon, Jan 19, 2015 at 8:32 PM, Abraham Varricatt <
abraham.varric...@googlemail.com> wrote:

> In addition to the other answers, I will suggest that you re-think your
> view logic - you haven't handled the case where your IF block fails.
> Remember, Django expects every view function to return a HttpResponse
> object. Assume that someone's request isn't authorized (yet) or even
> rejected. What do you want them to see? It's good user experience to at
> least show an error message instead of throwing them back to the home-page.
>
> -Abraham V.
>
>
> On Friday, January 16, 2015 at 5:11:10 AM UTC+5:30, suabiut wrote:
>>
>>
>>
>> Hi,
>> I am trying to two column and display some result if two conditions are
>> meet but i am getting this error:
>>
>> The view eLeave.views.FMKD1_leave_to_authorize didn't return an HttpResponse 
>> object. It returned None instead.
>>
>>
>> I can seems to figure out the issue, here is my view.py file
>>
>> def FMKD1_leave_to_authorize(request):
>> new_leave 
>> =newleave.objects.filter(department_head_authorization="Approved"
>> )
>> a = newleave.objects.filter(department="FMKD")
>> if new_leave=="True"and a =="True":
>> return render_to_response('FMKD1_display_approve_leave.html',
>> locals())
>>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/0a995400-c49c-455e-86ee-2dc89f56c963%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/CAPCf-y4WGYjCwa1d-Nwx4PUXLTA1V1%3DXApZNX26AHatC5bewoQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Authentication when usernames are not unique

2015-01-19 Thread James Schneider
For a pure authentication scenario where permission checks never go beyond
user.is_authenticated(), that's probably true. If all the OP is doing is
displaying data, they may be able to get away with manually associating the
campus and user within the session after, and displaying data based on
those session keys. Basically you would end up with a boolean layer of
protection for each resource, because all you know is the validated
username and campus pair. That may work just fine.

However, if you need any sort of authorization (permission checking) within
the app using Django's permission system, you'll probably need a local copy
of the user using a custom user model in the database to perform checks
against. It sounds like the OP may need that. Otherwise you are also
looking at rolling a custom authorization backend as well.

If they are LDAP services, you can look at django-ldap, which works quite
nicely, including group membership restrictions. It also does the
overriding of the authentication backend for you. Not sure how it would
work with multiple LDAP servers for various campuses though. That would
need some research.

TL;DR; There are a lot of ways to slice this problem, and a primary
strategy driver will be the available authentication backends at each
campus. Hopefully they are all the same.

-James


On Mon, Jan 19, 2015 at 2:06 PM, Stephen J. Butler  wrote:

> Shibboleth 2.0 lets you setup a discovery service (or portal would
> perhaps be a better term) letting the user select which ID Provider
> (IdP) they will authenticate to. All you have to do on the Service
> Provider (SP) side is specify the discovery URL and what IdPs you
> allow. Nothing needs to be done in your Django app except support
> Shibboleth.
>
> Of course, this is all predicated on there being a competent
> Shibboleth setup at your institutions.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/CAD4ANxVp4C2QcxAcY6Xui1bc6Z-hcV--sfOSEy%3DmcaW_w%2BpGHw%40mail.gmail.com
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Why do the IDs in many to many join tables change when there is no change.

2015-01-19 Thread jonas hagstedt
First off: this sounds like a bug, please log an issue on Github with as 
much info as possible (router, serializer and model etc. if you can)

I would recommend not using `SelfPublishModel` in this scenario, instead 
publish the event manually.
If you do it manually you lose out on having it publish when you save via 
admin (but you do get more control over when the publish occur, and you 
could of course add an action to admin to do this).

Two ways you can publish the model:

Using `publish_data` you could go about it this way


from swampdragon.pubsub_providers.data_publisher import publish_data

def publish_event(event):
serializer = EventSerializer(instance=event)
channel = 'public_events'
publish_data(channel, serializer.serialize())


The "drawback" of this is that you have to know the actual channel you are 
publishing to, and you wouldn't be able to use the `DataMapper` in 
JavaScript since it doesn't know if this set of data was a create, delete 
or an update action (publish_data was made with the intent to publish 
dictionaries rather than models).

If you use the `DataMapper` in JS, or have lots of subscribers on various 
channels all relating to the same model, or don't know the channel name, 
then use `publish_model` instead (this is probably the most recommended 
way).

`publish_model` will find the channels for you, but requires to know the 
action (was it an update, was it a delete or was it created?)

 from swampdragon.pubsub_providers.model_publisher import publish_model

def publish_event(event):
action = 'created'  # you can use created, updated, deleted
publish_model(event, EventSerializer, action)


So if you have a view where you create/update events you can simply add 
this (assuming CBV) to your view:

class EventCreateView(CreateView):
model = Event

def form_valid(form):
event = form.save()
publish_event(event)
return HttpResponseRedirect(self.get_success_url())

You could easily modify `publish_event` to take the action as a parameter





On Monday, January 19, 2015 at 2:57:16 PM UTC+1, Shazwi Suwandi wrote:
>
> I'm using Swampdragon to provide real time updates to the system since I 
> don't want users to keep refreshing their page to get them. I used the
> *ModelPublisherRouter* which causes me to get any updates to a particular 
> model. 
>
> I currently have an Events model with the following attributes:
> class Event(SelfPublishModel, models.Model):
> serializer_class = EventSerializer
> name = models.CharField(max_length=250)
> description = models.CharField(max_length=250)
> location = models.CharField(max_length=250)
> privacy = models.CharField(max_length=250)
> startDate = models.DateField()
> endDate = models.DateField()
> allDay = models.BooleanField(default=False)
> noOfAttendees = models.IntegerField(default=0)
> noOfNonAttendees = models.IntegerField(default=0)
> noOfInvitees = models.IntegerField(default=0)
> eventOwner = models.ForeignKey(User, related_name='eventsOwned')
> eventInvitees = models.ManyToManyField(User, 
> related_name='eventInvitees')
> eventAttendees = models.ManyToManyField(User, 
> related_name='eventAttendees')
> eventNonAttendees = models.ManyToManyField(User, 
> related_name='eventNonAttendees')
>
> As you can see, there are three many to many relationships with the User 
> table. If I edit an event's name and description without doing any 
> changes to eventInvitees, eventAttendees or eventNonAttendees, I was 
> expecting just one "publish" from Swampdragon since there is a change
> in the Events row. However, it "publishes" the update, 6 more times and I 
> suspect it is because of the rows in the join tables as it does not publish
> 6 times when I comment out these relationships. 
>
> I then checked the join tables and every time I do an update through the 
> admin UI, even if I did not add or remove users, it changes the primary key 
> of the rows, causing the publish from Swampdragon to be done. Is there any 
> way I can avoid having the IDs change?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/9bdf564e-2456-4326-b965-213b0fd5307c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Authentication when usernames are not unique

2015-01-19 Thread Stephen J. Butler
Shibboleth 2.0 lets you setup a discovery service (or portal would
perhaps be a better term) letting the user select which ID Provider
(IdP) they will authenticate to. All you have to do on the Service
Provider (SP) side is specify the discovery URL and what IdPs you
allow. Nothing needs to be done in your Django app except support
Shibboleth.

Of course, this is all predicated on there being a competent
Shibboleth setup at your institutions.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/CAD4ANxVp4C2QcxAcY6Xui1bc6Z-hcV--sfOSEy%3DmcaW_w%2BpGHw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Authentication when usernames are not unique

2015-01-19 Thread James Schneider
Hmm, yes, Shibboleth will require some extra trickery in multiple views
with redirects to the respective campus portal, etc. I've never done it
myself, but I believe the API is pretty well documented.

-James
On Jan 19, 2015 1:48 PM, "James Schneider"  wrote:

> That's an interesting (but understandable) requirement, which means you
> are probably in for an interesting time.
>
> Undoubtedly you'll need to roll your own authentication backend (
> https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#authentication-backends)
> and a custom user that contains the campus as one of the attributes (
> https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#substituting-a-custom-user-model
> ).
>
> As far as the user model inheritance goes, I would recommend inheriting
> from AbstractBaseUser (
> https://github.com/django/django/blob/master/django/contrib/auth/models.py#L196)
> and probably the Permission mixin in that same file if you are using the
> Django authorization system. Also take a look at the AbstractUser class for
> hints on the other bits you may need to manually specify that are not
> included in AbstractBaseUser.
>
> However, as you've aptly pointed out, the (somewhat) tricky part is that
> your authentication system requires a third piece of data that Django is
> not expecting, the campus name.
>
> When you begin overriding/implementing the various bits of the
> authentication system, you'll likely need to add an additional keyword
> argument like 'campus' or some other identifier such as:
>
> def authenticate(self, username=None, password=None, campus=None):
> # do auth things related to campus
>
>
> Then, any views, etc. that would run the contrib.auth's version of
> authenticate() would instead call your version with the extended signature
> including the campus. A quick search through the Github repo suggests that
> the only place where authenticate() is called is via the built-in form/view
> for logging in using the default authentication backend. You would have to
> override both of these constructs as part of the custom auth backend
> anyway, so you appear to be in luck. Your authentication call would look
> something like authenticate(user, pass, campus).
>
> You didn't mention anything about how each campus handles authentication
> (doesn't matter for this conversation), but your authenticate() method
> would likely contain a dictionary of methods that handle the actual
> interaction between Django and the specific campus backend, keyed via the
> campus name (you could also put this in settings.py and import it):
>
> def _auth_campus1(self, user, pass):
> # stuff for campus 1
>
> def _auth_campus2(self, user, pass):
> # stuff for campus 2
>
>
> def authenticate(self, user,pass,campus):
> AUTH_SOURCES = {
> 'campus1': _auth_campus1,
> 'campus2: _auth_campus2,
> }
>
> if campus not in AUTH_SOURCES:
> return None
>
> auth_func = AUTH_SOURCES[campus]
>
> if auth_func(user, pass):
> # check if user exists in local Django DB, otherwise create_user()
>
> # other checks
> # return user or None
>
>
>
> Once you get past the authentication portion, it looks as though the
> authorization portion should work out of the box (assuming the other bits
> are overridden properly per the docs), since you already have a user
> object, if you plan to use it at all.
>
> Be sure to have sane timeouts so that users aren't stuck waiting for
> broken campus backends, and so that processes/threads aren't stalled when
> they could be serving other users.
>
> HTH,
>
> -James
>
>
> On Mon, Jan 19, 2015 at 12:54 PM, Erik Cederstrand <
> erik+li...@cederstrand.dk> wrote:
>
>> Hello
>>
>> I'm creating a Django frontend for a legacy school system. The legacy
>> system has users, but usernames are only unique together with a school:
>>
>> class LegacyUser(models.Model):
>>school = models.ForeignKey(School)
>>username = models.CharField(max_length=40)
>>
>>class Meta:
>>unique_together = ['school', 'username']
>>
>>
>> I need to authenticate users using their school name, username and
>> password, so I can serve them data connected to the LegacyUser. The legacy
>> system provides an authentication service that I want to use to verify the
>> password.
>>
>> The Django authentication model seems to revolve around the username
>> being unique, so I can't just inherit the User model, login forms etc. How
>> do I get the School shoe-horned into the Django auth framework, and where
>> do I call the external authentication service? Some ideas how to best
>> accomplish this would be great!
>>
>>
>> Thanks,
>> Erik
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to 

Re: Authentication when usernames are not unique

2015-01-19 Thread James Schneider
That's an interesting (but understandable) requirement, which means you are
probably in for an interesting time.

Undoubtedly you'll need to roll your own authentication backend (
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#authentication-backends)
and a custom user that contains the campus as one of the attributes (
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#substituting-a-custom-user-model
).

As far as the user model inheritance goes, I would recommend inheriting
from AbstractBaseUser (
https://github.com/django/django/blob/master/django/contrib/auth/models.py#L196)
and probably the Permission mixin in that same file if you are using the
Django authorization system. Also take a look at the AbstractUser class for
hints on the other bits you may need to manually specify that are not
included in AbstractBaseUser.

However, as you've aptly pointed out, the (somewhat) tricky part is that
your authentication system requires a third piece of data that Django is
not expecting, the campus name.

When you begin overriding/implementing the various bits of the
authentication system, you'll likely need to add an additional keyword
argument like 'campus' or some other identifier such as:

def authenticate(self, username=None, password=None, campus=None):
# do auth things related to campus


Then, any views, etc. that would run the contrib.auth's version of
authenticate() would instead call your version with the extended signature
including the campus. A quick search through the Github repo suggests that
the only place where authenticate() is called is via the built-in form/view
for logging in using the default authentication backend. You would have to
override both of these constructs as part of the custom auth backend
anyway, so you appear to be in luck. Your authentication call would look
something like authenticate(user, pass, campus).

You didn't mention anything about how each campus handles authentication
(doesn't matter for this conversation), but your authenticate() method
would likely contain a dictionary of methods that handle the actual
interaction between Django and the specific campus backend, keyed via the
campus name (you could also put this in settings.py and import it):

def _auth_campus1(self, user, pass):
# stuff for campus 1

def _auth_campus2(self, user, pass):
# stuff for campus 2


def authenticate(self, user,pass,campus):
AUTH_SOURCES = {
'campus1': _auth_campus1,
'campus2: _auth_campus2,
}

if campus not in AUTH_SOURCES:
return None

auth_func = AUTH_SOURCES[campus]

if auth_func(user, pass):
# check if user exists in local Django DB, otherwise create_user()

# other checks
# return user or None



Once you get past the authentication portion, it looks as though the
authorization portion should work out of the box (assuming the other bits
are overridden properly per the docs), since you already have a user
object, if you plan to use it at all.

Be sure to have sane timeouts so that users aren't stuck waiting for broken
campus backends, and so that processes/threads aren't stalled when they
could be serving other users.

HTH,

-James


On Mon, Jan 19, 2015 at 12:54 PM, Erik Cederstrand <
erik+li...@cederstrand.dk> wrote:

> Hello
>
> I'm creating a Django frontend for a legacy school system. The legacy
> system has users, but usernames are only unique together with a school:
>
> class LegacyUser(models.Model):
>school = models.ForeignKey(School)
>username = models.CharField(max_length=40)
>
>class Meta:
>unique_together = ['school', 'username']
>
>
> I need to authenticate users using their school name, username and
> password, so I can serve them data connected to the LegacyUser. The legacy
> system provides an authentication service that I want to use to verify the
> password.
>
> The Django authentication model seems to revolve around the username being
> unique, so I can't just inherit the User model, login forms etc. How do I
> get the School shoe-horned into the Django auth framework, and where do I
> call the external authentication service? Some ideas how to best accomplish
> this would be great!
>
>
> Thanks,
> Erik
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/26BA41BB-1771-4C5C-9980-A2C49F30280C%40cederstrand.dk
> .
> 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 

Re: Authentication when usernames are not unique

2015-01-19 Thread Stephen J. Butler
Just as a case study, Shibboleth does this by having unscoped and
scoped usernames. The scoped username should be globally unique and
takes the form of "u...@school1.edu". Unscopped is not globally
unique, but unique for a particular scope (ie: "user").

It's temping to say "ahh... email address!" But in Shibboleth
terminology that would be a mistake. A single user (u...@school1.edu)
could have multiple email addresses (u...@school1.edu,
u...@dept.school1.edu, user-...@school.edu, etc). The scoped user
identifies the user independently of their emails, even though the
value might be the same.

Generally the scope part comes from the ID provider (the thing doing
the authentication and providing user attributes) and not the mail
system. So the ID provider could be an AD domain, for instance. As
long as it's unique.

On Mon, Jan 19, 2015 at 2:54 PM, Erik Cederstrand
 wrote:
> Hello
>
> I'm creating a Django frontend for a legacy school system. The legacy system 
> has users, but usernames are only unique together with a school:
>
> class LegacyUser(models.Model):
>school = models.ForeignKey(School)
>username = models.CharField(max_length=40)
>
>class Meta:
>unique_together = ['school', 'username']
>
>
> I need to authenticate users using their school name, username and password, 
> so I can serve them data connected to the LegacyUser. The legacy system 
> provides an authentication service that I want to use to verify the password.
>
> The Django authentication model seems to revolve around the username being 
> unique, so I can't just inherit the User model, login forms etc. How do I get 
> the School shoe-horned into the Django auth framework, and where do I call 
> the external authentication service? Some ideas how to best accomplish this 
> would be great!
>
>
> Thanks,
> Erik
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.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/26BA41BB-1771-4C5C-9980-A2C49F30280C%40cederstrand.dk.
> 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/CAD4ANxVXgiUeTYkX1xzMoZfsUMFmNmx8WqiqpDozWvWt7zKjrQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Authentication when usernames are not unique

2015-01-19 Thread Erik Cederstrand
Hello

I'm creating a Django frontend for a legacy school system. The legacy system 
has users, but usernames are only unique together with a school:

class LegacyUser(models.Model):
   school = models.ForeignKey(School)
   username = models.CharField(max_length=40)

   class Meta:
   unique_together = ['school', 'username']


I need to authenticate users using their school name, username and password, so 
I can serve them data connected to the LegacyUser. The legacy system provides 
an authentication service that I want to use to verify the password.

The Django authentication model seems to revolve around the username being 
unique, so I can't just inherit the User model, login forms etc. How do I get 
the School shoe-horned into the Django auth framework, and where do I call the 
external authentication service? Some ideas how to best accomplish this would 
be great!


Thanks,
Erik

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/26BA41BB-1771-4C5C-9980-A2C49F30280C%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.


Re: Lock Django DB on 9 of 10 concurrent uwsgi workers - how to?

2015-01-19 Thread Erik Cederstrand

> Den 19/01/2015 kl. 19.24 skrev Andreas Krueger :
> 
> 
> 
> What is the most elegant way to
> 
> lock the Django DB while I make a complex transaction (read, decide, write)
> 
> ... during which no other uwsgi worker should have access (or at least no 
> write access) to that table?

That's a rather strange requirement. What are you trying to achive? Elegant for 
who?

You could put your site in "maintenance mode" while the process is running, to 
be nice to users. If you mean elegant (as in simple) sysadmin-wise, simply shut 
down uwsgi and run your commands in a custom management command while uwsgi is 
stopped.

But if you can bundle all your tasks in a single DB transaction, you shouldn't 
need to shut down anything.

Erik

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/036DAEA0-9F6F-4AD3-9A3C-03D5DC14C00A%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.


Re: installation of mysqlclient

2015-01-19 Thread Erik Cederstrand

> Den 19/01/2015 kl. 20.28 skrev th.gran...@free.fr:
> Thanks but i have a problem!
> 
> when i launch the install command i get these errors
> 
> Downloading mysqlclient-1.3.4.tar.gz (77kB)
>100% || 77kB 356kB/s
>/bin/sh: 1: mysql_config: not found
>Traceback (most recent call last):
>  File "", line 20, in 
>  File "/tmp/pip-build-obp7bna6/mysqlclient/setup.py", line 17, in 
>metadata, options = get_config()
>  File "/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 47, in 
> get_config
>libs = mysql_config("libs_r")
>  File "/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 29, in 
> mysql_config
>raise EnvironmentError("%s not found" % (mysql_config.path,))
>OSError: mysql_config not found
>Complete output from command python setup.py egg_info:
>/bin/sh: 1: mysql_config: not found

mysqlclient needs mysql_config, which either isn't installed on your system or 
isn't in your PATH. If this is a Linux distro, it's probably missing the 
libmysqlclient-dev package.

Erik

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/5A250D88-352E-4748-B806-3053E06ADEBF%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.


Lock Django DB on 9 of 10 concurrent uwsgi workers - how to?

2015-01-19 Thread Andreas Krueger



What is the most elegant way to

lock the Django DB while I make a complex transaction (read, decide, write)

... during which no other uwsgi worker should have access (or at least  
no write access) to that table?


I am using Django + db.sqlite3 + uwsgi (+ nginx).

Thanks a lot!

Andreas



(see also my related question at stackoverflow   
http://stackoverflow.com/questions/28030536/lock-django-db-on-10-concurrent-uwsgi-workers-how-to  
)



--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/20150119192445.51266v26zzk6hrl9%40webmail.andreaskrueger.de.
For more options, visit https://groups.google.com/d/optout.


Re: installation of mysqlclient

2015-01-19 Thread th . granier


On Monday, January 19, 2015 at 7:55:06 PM UTC+1, th.gr...@free.fr wrote:
>
> Hello
>
> i am trying to use Dkango with Python3.4.2 and mysql
>
> i have downloaded mysqlclient-1.3.4 but i don't know how to install it. 
> it's a .whl file
>
> Can you help me please?
>
> Many thanks
>
>
Thanks but i have a problem!

when i launch the install command i get these errors

 


































*Downloading mysqlclient-1.3.4.tar.gz (77kB)100% 
|| 77kB 356kB/s /bin/sh: 1: 
mysql_config: not foundTraceback (most recent call last):  File 
"", line 20, in   File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup.py", line 17, in 
metadata, options = get_config()  File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 47, in 
get_configlibs = mysql_config("libs_r")  File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 29, in 
mysql_configraise EnvironmentError("%s not found" % 
(mysql_config.path,))OSError: mysql_config not foundComplete output 
from command python setup.py egg_info:/bin/sh: 1: mysql_config: not 
foundTraceback (most recent call last):  File "", 
line 20, in   File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup.py", line 17, in 
metadata, options = get_config()  File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 47, in 
get_configlibs = mysql_config("libs_r")  File 
"/tmp/pip-build-obp7bna6/mysqlclient/setup_posix.py", line 29, in 
mysql_configraise EnvironmentError("%s not found" % 
(mysql_config.path,))OSError: mysql_config not found
Command "python setup.py 
egg_info" failed with error code 1 in /tmp/pip-build-obp7bna6/mysqlclient*

>
>
> *T.*
>
mysql is running and i can access via phpmyadmin
how configure mysql?
Many 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/40915d9c-7838-4b7b-aca7-b86bd17326b6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: installation of mysqlclient

2015-01-19 Thread Erik Cederstrand

> Den 19/01/2015 kl. 19.55 skrev th.gran...@free.fr:
> 
> Hello
> 
> i am trying to use Dkango with Python3.4.2 and mysql
> 
> i have downloaded mysqlclient-1.3.4 but i don't know how to install it. it's 
> a .whl file
> 
> Can you help me please?

Just use pip instead. This should get you the latest version:

% pip install mysqlclient

Erik

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/C95736CF-C519-4DD8-B21B-0CE34F9E3DBB%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.


installation of mysqlclient

2015-01-19 Thread th . granier
Hello

i am trying to use Dkango with Python3.4.2 and mysql

i have downloaded mysqlclient-1.3.4 but i don't know how to install it. 
it's a .whl file

Can you help me please?

Many thanks

T.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/5a1e48bc-443a-4d6a-95d3-dcff323bfbb4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


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

2015-01-19 Thread Richard Brockie
Thank you - that looks like what I am looking for! I don't know how I
missed that.

I'm on 1.6 right now - another reason to move to 1.7 :)

R.

On Mon, Jan 19, 2015 at 9:16 AM, Collin Anderson 
wrote:

> 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 a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/Ysef5zCb7Gc/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/ac19922b-a623-4083-9b86-e1ab4bf5892d%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
R.

Richard Brockie

Real-time bicycle race results - www.ontheday.net

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/CAKv-vOWzk2gE0wD1M7-pt2jrXX4TqCzp2z-yNJEm7x7pfstWww%40mail.gmail.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 Luis Matoso
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/2aa39e20-a977-436c-9e21-586605ec7df6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: need help to configure new domain

2015-01-19 Thread zsandrusha .
Sank's for responding, but we already made all, there was no DB after
server crash or something like this.

On Sat, Jan 17, 2015 at 4:12 PM, Collin Anderson 
wrote:

> Hi,
>
> Did you figure it out? It looks like you need to configure your urls.py so
> it's connected with django-cms.
>
> Collin
>
> On Tuesday, January 13, 2015 at 9:19:09 PM UTC-5, zsandrusha wrote:
>>
>> hello i need urgent help to configure django,
>> i had site on django cms then i loose my old domaind now i need to add
>> new domain name but i see - http://joxi.ru/82QDVneI8o3amd
>> so i realy need help to configure my website with fee
>>
>  --
> 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/SZJ_HE0tFGA/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/69caabb4-0807-4412-b028-b170ee7bb402%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/CAJKjH6L6uPnHY-cG_MPZTdmTJ0ZO5cUzpK-fdp_Y2EfKCJCE1g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Flood of ''Invalid HTTP_HOST header" mails

2015-01-19 Thread Andreas Pritschet
-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/54BD4A27.5000107%40hasenkopf2000.net.
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: SECURE_PROXY_SSL_HEADER requires referer

2015-01-19 Thread Larry Martell
On Sat, Jan 17, 2015 at 10:03 AM, Larry Martell  wrote:
> We have a django app accessed via SSL (i.e. with https). When we went
> to the admin site and it was redirected to  admin/login/?next=/admin/
> because we were not logged in, the https was not carried over and the
> request failed. I added
>
> SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
>
> to my settings and then the admin redirect worked. But we have some
> clients that access the site with curl or python requests and after
> adding that all their existing code broke. They now all have to add a
> referer to all their requests for them to work.
>
> My question is, is there a way to make the admin redirect work but not
> require all the other requests to have a referer? A non redirected
> request from the browser works, and that doesn't have a referer, so
> why is it required on the curl requests?

I found this:

https://code.djangoproject.com/ticket/16870

Which I guess answers my question.

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


Re: Desperately need Django help!

2015-01-19 Thread Vijay Khemlani
For single page applications I highly recommend this tutorial, it answers
the typical questions regarding single page apps.

https://thinkster.io/brewer/angular-django-tutorial/

(assuming you are using angularJS)

On Mon, Jan 19, 2015 at 5:08 AM,  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/ae196366-8cb1-48ae-abda-7934b2200f20%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/CALn3ei22upWLB2Tfoutv9K9zFjT6AbbcEqDipEyy3x0amQTN8g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Windows path for django_crontab

2015-01-19 Thread Michael Manfre
If you don't end up using Celery, another option for a periodic action is 
to create a management command and schedule it to run with Task Scheduler 
(http://msdn.microsoft.com/en-us/library/windows/desktop/aa383614%28v=vs.85%29.aspx).

Regards,
Michael Manfre

On Sunday, January 18, 2015 at 11:12:49 PM UTC-5, sarfaraz ahmed wrote:
>
> Thanks for replies I really wish people who posted packages should mention 
> clearly about which OS it;s going to work. I ended up wasting two workdays 
> in experimenting with kronos,DJANGO-CHRONOGRAPH 
> ,
> DJANGO-CRONJOBS 
> ,DJANGO-CRON 
> .
>
> Surprisingly, DJANGO cron says that it is meant for Windows hosting where 
> user does not have access to setup the cron jobs. I tried that to... 
> nothing runs 
>
> Regards,
> Sarfaraz Ahmed
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/15c841a4-9c39-4cf0-9831-06fd24651844%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Linking to multiple dynamic images from same web page

2015-01-19 Thread Derek
Thanks Mitesh

I thought it might be along those lines.  I have tried calling plt.close() 
just before I return from the plot creation function, but still get the 
same error.

Do you perhaps have a simple code example I can try and follow?  (I am 
already using the io module for the image storage.)

Derek


On Sunday, 18 January 2015 16:05:45 UTC+2, mitesh_django wrote:
>
> Hi Derek,
>
> I face same issue few months ago, what I did is I destroyed plot object 
> completely everytime the view is called and regenerated new plot everytime. 
> You can try that. There is an issue with matplotlib memory, which basically 
> usage same plot.
>
> Another solution could be try different cStringIO to store base64 encoded 
> image data, send that as response and at browser using javascript (
> data:image/png;base64).
>
>
>
> Thanks,
> With Best Regards,
>
> Mitesh Patel
>
> Senior Product Engineer
>
> Mobile: +91-9970 8575 39
> Email: mitesh.p...@gmail.com 
> LinkedIn : http://in.linkedin.com/in/miteshpatel11
>
>
> On 18 January 2015 at 19:23, Derek  
> wrote:
>
>> I have a situation which is puzzling.
>>
>> I have a web page that, when generated embeds links that look like:
>>
>> 
>> >  
>> line 1401, in xlabel
>> l =  gca().set_xlabel(s, *args, **kwargs)
>>   File 
>> "/home/gamesbook/.virtualenvs/dev/local/lib/python2.7/site-packages/matplotlib/pyplot.py",
>>  
>> line 803, in gca
>> ax =  gcf().gca(**kwargs)
>>   File 
>> "/home/gamesbook/.virtualenvs/dev/local/lib/python2.7/site-packages/matplotlib/figure.py",
>>  
>> line 1221, in gca
>> return self.add_subplot(1, 1, 1, **kwargs)
>>   File 
>> "/home/gamesbook/.virtualenvs/dev/local/lib/python2.7/site-packages/matplotlib/figure.py",
>>  
>> line 916, in add_subplot
>> self._axstack.add(key, a)
>>   File 
>> "/home/gamesbook/.virtualenvs/dev/local/lib/python2.7/site-packages/matplotlib/figure.py",
>>  
>> line 120, in add
>> Stack.remove(self, (key, a_existing))
>>   File 
>> "/home/gamesbook/.virtualenvs/dev/local/lib/python2.7/site-packages/matplotlib/cbook.py",
>>  
>> line 1343, in remove
>> raise ValueError('Unknown element o')
>> ValueError: Unknown element o
>>
>> I have googled for this error, but it seems fairly obscure and I am not 
>> sure how it relates to my situation.
>>
>> Any insights welcome!
>>
>> Thanks
>> Derek
>>
>>  -- 
>> You received this message because you are subscribed 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/CAF1Wu3OfN9rmUKTDO%2BT%3DJan%3DF%3DLKODqQObds-tvME%3DUhL18fMw%40mail.gmail.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

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


Why do the IDs in many to many join tables change when there is no change.

2015-01-19 Thread Shazwi Suwandi
I'm using Swampdragon to provide real time updates to the system since I 
don't want users to keep refreshing their page to get them. I used the
*ModelPublisherRouter* which causes me to get any updates to a particular 
model. 

I currently have an Events model with the following attributes:
class Event(SelfPublishModel, models.Model):
serializer_class = EventSerializer
name = models.CharField(max_length=250)
description = models.CharField(max_length=250)
location = models.CharField(max_length=250)
privacy = models.CharField(max_length=250)
startDate = models.DateField()
endDate = models.DateField()
allDay = models.BooleanField(default=False)
noOfAttendees = models.IntegerField(default=0)
noOfNonAttendees = models.IntegerField(default=0)
noOfInvitees = models.IntegerField(default=0)
eventOwner = models.ForeignKey(User, related_name='eventsOwned')
eventInvitees = models.ManyToManyField(User, 
related_name='eventInvitees')
eventAttendees = models.ManyToManyField(User, 
related_name='eventAttendees')
eventNonAttendees = models.ManyToManyField(User, 
related_name='eventNonAttendees')

As you can see, there are three many to many relationships with the User 
table. If I edit an event's name and description without doing any 
changes to eventInvitees, eventAttendees or eventNonAttendees, I was 
expecting just one "publish" from Swampdragon since there is a change
in the Events row. However, it "publishes" the update, 6 more times and I 
suspect it is because of the rows in the join tables as it does not publish
6 times when I comment out these relationships. 

I then checked the join tables and every time I do an update through the 
admin UI, even if I did not add or remove users, it changes the primary key 
of the rows, causing the publish from Swampdragon to be done. Is there any 
way I can avoid having the IDs change?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/af69c846-ece7-4af4-ab0f-344a1f49f390%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: having problem with jquery ajax

2015-01-19 Thread James Schneider
Quick guess, you are visiting the site in your browser using
http://localhost:8000. I'm betting if you instead visited it using
http://127.0.0.1:8000, the AJAX query would work fine.

You have http://127.0.0.1:8000 hard coded (or being generated) everywhere.
Either change your JavaScript to use localhost, only visit the site using
the IP rather than the name, or better yet, try to eliminate any reference
to the domain or the IP in your JavaScript by using relative URL's.

-James
On Jan 19, 2015 4:33 AM, "Aussie Niki"  wrote:

> my view:
>
> def aget(request):
>
> if request.is_ajax() :
>
> json_data={}
>
> json_data['messege']= 'sorry'
>
> return HttpResponse(json.dumps(json_data),
> content_type='applicaton/json')
> my url:
>
> urlpatterns = patterns('',
>
> url(r'^$', 'post.views.home', name='home'),
> url(r'^aget/', 'post.views.aget'),
> #url(r'^admin/', include(admin.site.urls)),
> )
>
>
> my templete:
>
>  {% csrf_token %}
> 
> ajaxpo
> ajaxge
> 
>
> 
>
> 
> http://code.jquery.com/jquery-1.11.2.min.js";>
>
> 
>
> function aget(){
>
>   $.ajax({  type: 'GET',
> headers :{"Access-Control-Allow-Origin": "
> http://127.0.0.1:8000/";,
> 'Content-Type': 'application/json; charset=utf-8'},
> url : "http://127.0.0.1:8000/aget/";,
> dataType:'json',
> async: true,
> data: {
>   csrfmiddlewaretoken : '{{csrf_token}}'
> },
>
> success:function(data){
>   $('#out').html(data);
>   alart(JSON.stringify(data.messege));
> }
>   });
>
> }
>
> 
>
> in chrome network:
>
> method: option
> status: 200 ok
> type :aplication
>
> in chrome console:
>
> XMLHttpRequest cannot load
> http://127.0.0.1:8000/aget/?csrfmiddlewaretoken=4ES8c0QJnVzLCQH6dqGNmS2q8sxcetoL.
> No 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://localhost:8000' is therefore not allowed access.
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/599e8b9b-9164-4dd0-b06a-e98582b7fdd3%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/CA%2Be%2BciVw66mVei2O40cXQ%2BadXg9iiuo7i6AZS%3DV2nBnZVOhCRg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why this code does not change users firstname and lastname?

2015-01-19 Thread joulumaa
Why would it make sense to switch from different form type?
I use below form to get information that I like to save to user database?
Part of information I need ot update goes to Additional user info class, I 
would like to stay in my own form.

-Thanks

maanantai 19. tammikuuta 2015 11.26.47 UTC+2 Daniel Roseman kirjoitti:
>
> On Monday, 19 January 2015 09:22:02 UTC, joulumaa wrote:
>>
>> I have created user earlier in code with email address and password. 
>> Created users work fine.
>> Now in later phase I asked more information and would like to fill in 
>> first_name and last_name.
>> Code shows old first_name and last_name properly if set in admin view, 
>> but logged in user cannot save his information for some reason?
>>
>>   p=User.objects.get(username=request.user.username)
>> if request.method == 'POST':
>> form = AdditionalCandidateInfo(request.POST)
>> if form.is_valid():
>> p.first_name=form.cleaned_data['first_name']
>> p.last_name=form.cleaned_data['last_name']
>> p.save()
>> return HttpResponseRedirect('/')
>> else:
>> form = 
>> AdditionalCandidateInfo(initial={'first_name':p.first_name,'last_name':p.last_name})
>>
>>
>> -thanks for help
>>
>
> You should be using a ModelForm, and pass the `instance` argument when 
> instantiating the form.
>
> Also there's no point querying User: `request.user` is *already* the 
> relevant User instance.
> --
> DR.
>

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


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread AJ
*Hi,*

*What i understood is that you need two different forms on single page. and 
later on you want to map feedback form as site specific.*

*So you can do with two different ways:*

*1) define two different form action path.*






*   ...form fields...   ...form 
fields...*


*2) you have will have to provide two different buttons in template say *





And write view for it, which will identify response method 

This view is only for saving contact us

if request.method == 'POST' && 'contactus' in request.post :
contactform = contactForm(request.POST)
if contactform.is_valid():
contactform.save()
elif  request.method == 'POST' && 'feedback' in request.post :
   feedbackform = feedbackForm(request.POST)
if feedbackform.is_valid():
feedbackform.save()
else:
contactform = contactForm()
feedbackform = feedbackform()

Thanks,
Aj

On Monday, 19 January 2015 15:43:34 UTC+5:30, Tobias Dacoir wrote:
>
> I need to include two different contact forms in my app. One a general 
> contact form and another Report / Feedback form that pre-fills some data 
> depending on which site it was called from. 
> So I hit google, found django-contact-form, installed it and after 
> creating some basic templates (and rest of the configuration) I was able to 
> make use of /contact/ to present a basic form which takes in Name, Email 
> and Message. Works fine.
>
> Now I need that Report Form. The idea is to have a 'Report' Button on the 
> Website which maps to /report/$Parameter (or maybe it will just put the 
> parameter into request, not sure yet how to do this).
> However I have troubles getting my Custom Form to work. I tried to create 
> a new view that uses my custom form which just inherits from ContactForm:
>
> forms.py:
> class ReportForm(ContactForm):
> additional = forms.CharField(max_length=100, label='additional field 
> test')
> subject_template_name = "contact_form/report_form_subject.txt"
> template_name = 'contact_form/report_form.txt'
>
>
>
> views.py:
> def report(request):
> reportForm = ReportForm
> return render(request, 'play/report.html', {'form': reportForm})
>
>
>
>
> template report.html:
> {% extends 'base.html' %}
>
> {% block body_block %}
> Report Form
>   To send us a message fill out the below form.
>   {% csrf_token %}
> Name: 
> Your e-mail: 
>  additional field test: 
> Message: 
> 
>   
> {% endblock %}
>
> However it's not working at all. I can see the form displayed thanks to 
> the HTML Template, but nothing is happening when I press Submit. There is 
> no example on the website on how to subclass it :(
> http://django-contact-form.readthedocs.org/en/latest/quickstart.html
> Or should I just copy and paste the whole code from here and adapt it to 
> include additional fields: 
> https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/e87aaafb-f842-418c-9e26-6c7dd71e94a7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Desperately need Django help!

2015-01-19 Thread neil . asnani


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/ae196366-8cb1-48ae-abda-7934b2200f20%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


having problem with jquery ajax

2015-01-19 Thread Aussie Niki
my view:

def aget(request):

if request.is_ajax() :
   
json_data={}

json_data['messege']= 'sorry'

return HttpResponse(json.dumps(json_data), 
content_type='applicaton/json')
my url:

urlpatterns = patterns('',

url(r'^$', 'post.views.home', name='home'),
url(r'^aget/', 'post.views.aget'),
#url(r'^admin/', include(admin.site.urls)),
)


my templete:

 {% csrf_token %}

ajaxpo
ajaxge





http://code.jquery.com/jquery-1.11.2.min.js";>



function aget(){

  $.ajax({  type: 'GET',
headers :{"Access-Control-Allow-Origin": 
"http://127.0.0.1:8000/";,
'Content-Type': 'application/json; charset=utf-8'},
url : "http://127.0.0.1:8000/aget/";,
dataType:'json',
async: true,
data: {
  csrfmiddlewaretoken : '{{csrf_token}}'
},
  
success:function(data){
  $('#out').html(data);
  alart(JSON.stringify(data.messege));
}
  });
   
}



in chrome network:

method: option
status: 200 ok
type :aplication

in chrome console:

XMLHttpRequest cannot load 
http://127.0.0.1:8000/aget/?csrfmiddlewaretoken=4ES8c0QJnVzLCQH6dqGNmS2q8sxcetoL.
 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:8000' is therefore not allowed access.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/599e8b9b-9164-4dd0-b06a-e98582b7fdd3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Tobias Dacoir
I managed to do it! Thanks to your help.

Ok all you need to do is this:

views.py:
class ReportFormView(FormView):
form_class = ReportForm
template_name = 'contact_form/contact_form.html'

def form_valid(self, form):
form.save()
return super(ReportFormView, self).form_valid(form)

def get_form_kwargs(self):
# ContactForm instances require instantiation with an
# HttpRequest.
kwargs = super(ReportFormView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs

def get_success_url(self):
# This is in a method instead of the success_url attribute
# because doing it as an attribute would involve a
# module-level call to reverse(), creating a circular
# dependency between the URLConf (which imports this module)
# and this module (which would need to access the URLConf to
# make the reverse() call).
return reverse('contact_form_sent')



Add this to URL patterns:
  url(r'^report/', ReportFormView.as_view(), name='report_form'),



and in forms.py subclass like this:
class ReportForm(ContactForm):
additional = forms.CharField(max_length=100, label='additional field 
test')
subject_template_name = "contact_form/report_form_subject.txt"
template_name = 'contact_form/report_form.txt'

And the template, thanks to you is easy as pie:
report.html:
{% extends 'base.html' %}

{% block body_block %}
Contact Form
  To send us a message fill out the below form.
{% csrf_token %}
{{ form.as_p }}

  
{% endblock %}



Now I just need to figure out how to pre-fill.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/f0107dff-039b-446d-9f33-aa7f0cd640e6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Vijay Khemlani
OK, I read a little of the library documentation, and this is what you have
to do I think

1. subclass the ContactForm (you already have that)
2. subclass the ContactFormView from the library, at least with this:

class ReportFormView(ContactFormView):
form_class = ReportForm

3. Map this view to a path in yout urls.py

url(r'report/$', ReportFormView.as_view())

On Mon, Jan 19, 2015 at 9:13 AM, Tobias Dacoir  wrote:

> Thanks for the reply. I was wondering about the if statement about
> request.type as well, but I took the code from Stackoverflow and a
> combination of the original source code. It calls a Class.as_view() and I
> wasn't sure if I need to overwrite that as well. I didn't really want to
> write all the view code logic again as it kinda defeats the purpose of
> having a 3rd party app that does that for me.
>
> According to the official documentation I'm still unsure if I need to type
> anything in my views.py at all.
> As far as I understand this, I just need to subclass ContactForm somehow:
>
> class ContactForm(forms.Form):
> """
> The base contact form class from which all contact form classes
> should inherit.
>
> If you don't need any custom functionality, you can simply use
> this form to provide basic contact functionality; it will collect
> name, email address and message.
>
> The ``ContactForm`` view included in this application knows how to
> work with this form and can handle many types of subclasses as
> well (see below for a discussion of the important points), so in
> many cases it will be all that you need. If you'd like to use this
> form or a subclass of it from one of your own views, just do the
> following:
>
> 1. When you instantiate the form, pass the current ``HttpRequest``
>object to the constructor as the keyword argument ``request``;
>this is used internally by the base implementation, and also
>made available so that subclasses can add functionality which
>relies on inspecting the request.
>
> 2. To send the message, call the form's ``save`` method, which
>accepts the keyword argument ``fail_silently`` and defaults it
>to ``False``. This argument is passed directly to
>``send_mail``, and allows you to suppress or raise exceptions
>as needed for debugging. The ``save`` method has no return
>value.
>
> Other than that, treat it like any other form; validity checks and
> validated data are handled normally, through the ``is_valid``
> method and the ``cleaned_data`` dictionary.
>
> taken from here:
> https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/5c5e5b0a-fcb8-4928-b696-1f6c48e6e951%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/CALn3ei3kZ%3D6%2BjfhJxrxM1%2BYCr73FPthhPXmRXJO30D_34TnaMw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Tobias Dacoir
Thanks for the reply. I was wondering about the if statement about 
request.type as well, but I took the code from Stackoverflow and a 
combination of the original source code. It calls a Class.as_view() and I 
wasn't sure if I need to overwrite that as well. I didn't really want to 
write all the view code logic again as it kinda defeats the purpose of 
having a 3rd party app that does that for me.

According to the official documentation I'm still unsure if I need to type 
anything in my views.py at all.
As far as I understand this, I just need to subclass ContactForm somehow:

class ContactForm(forms.Form):
"""
The base contact form class from which all contact form classes
should inherit.

If you don't need any custom functionality, you can simply use
this form to provide basic contact functionality; it will collect
name, email address and message.

The ``ContactForm`` view included in this application knows how to
work with this form and can handle many types of subclasses as
well (see below for a discussion of the important points), so in
many cases it will be all that you need. If you'd like to use this
form or a subclass of it from one of your own views, just do the
following:

1. When you instantiate the form, pass the current ``HttpRequest``
   object to the constructor as the keyword argument ``request``;
   this is used internally by the base implementation, and also
   made available so that subclasses can add functionality which
   relies on inspecting the request.

2. To send the message, call the form's ``save`` method, which
   accepts the keyword argument ``fail_silently`` and defaults it
   to ``False``. This argument is passed directly to
   ``send_mail``, and allows you to suppress or raise exceptions
   as needed for debugging. The ``save`` method has no return
   value.

Other than that, treat it like any other form; validity checks and
validated data are handled normally, through the ``is_valid``
method and the ``cleaned_data`` dictionary.

taken from here: 
https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/5c5e5b0a-fcb8-4928-b696-1f6c48e6e951%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Tobias Dacoir
According to the official documentation I'm still unsure if I need to type 
anything in my views.py at all. 
As far as I understand this, I just need to subclass ContactForm somehow:

class ContactForm(forms.Form): """ The base contact form class from which all 
contact form classes should inherit. If you don't need any custom 
functionality, you can simply use this form to provide basic contact 
functionality; it will collect name, email address and message. The 
``ContactForm`` view included in this application knows how to work with this 
form and can handle many types of subclasses as well (see below for a 
discussion of the important points), so in many cases it will be all that you 
need. If you'd like to use this form or a subclass of it from one of your own 
views, just do the following: 1. When you instantiate the form, pass the 
current ``HttpRequest`` object to the constructor as the keyword argument 
``request``; this is used internally by the base implementation, and also made 
available so that subclasses can add functionality which relies on inspecting 
the request. 2. To send the message, call the form's ``save`` method, which 
accepts the keyword argument ``fail_silently`` and defaults it to ``False``. 
This argument is passed directly to ``send_mail``, and allows you to suppress 
or raise exceptions as needed for debugging. The ``save`` method has no return 
value. Other than that, treat it like any other form; validity checks and 
validated data are handled normally, through the ``is_valid`` method and the 
``cleaned_data`` dictionary.

taken from here: 
https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/19bfb8e0-9981-4659-b050-e4cb6e47025d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Tobias Dacoir
Thanks for the reply. I was wondering about the if statement about 
request.type as well, but I took the code from Stackoverflow and a 
combination of the original source code. It calls a Class.as_view() and I 
wasn't sure if I need to overwrite that as well. I didn't really want to 
write all the view code logic again as it kinda defeats the purpose of 
having a 3rd party app that does that for 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/ff62ddad-8c05-49c7-97c1-6108f1550e88%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Vijay Khemlani
Right now the "reportForm" variable is pointing to the RequestForm class,
not to an object, so you need to do it like this

reportForm = ReportForm()# Take note of the parenthesis

In your template, your form tag need an action attribute (well, it's not
mandatory but it is highly advised). In this case if you want the same view
to process your form you just need to use ".".



With those changes you should be able to render the form as usual:

{{ form.as_p }}

Also I'm not sure what do you mean when you say thet nothing is happening
when you pres the Submit button. As you have it right now it just calls the
same view ("report") that you wrote. Since the view does not have different
rules for GET and POST requests it just renders the same page again.

On Mon, Jan 19, 2015 at 7:13 AM, Tobias Dacoir  wrote:

> I need to include two different contact forms in my app. One a general
> contact form and another Report / Feedback form that pre-fills some data
> depending on which site it was called from.
> So I hit google, found django-contact-form, installed it and after
> creating some basic templates (and rest of the configuration) I was able to
> make use of /contact/ to present a basic form which takes in Name, Email
> and Message. Works fine.
>
> Now I need that Report Form. The idea is to have a 'Report' Button on the
> Website which maps to /report/$Parameter (or maybe it will just put the
> parameter into request, not sure yet how to do this).
> However I have troubles getting my Custom Form to work. I tried to create
> a new view that uses my custom form which just inherits from ContactForm:
>
> forms.py:
> class ReportForm(ContactForm):
> additional = forms.CharField(max_length=100, label='additional field
> test')
> subject_template_name = "contact_form/report_form_subject.txt"
> template_name = 'contact_form/report_form.txt'
>
>
>
> views.py:
> def report(request):
> reportForm = ReportForm
> return render(request, 'play/report.html', {'form': reportForm})
>
>
>
>
> template report.html:
> {% extends 'base.html' %}
>
> {% block body_block %}
> Report Form
>   To send us a message fill out the below form.
>   {% csrf_token %}
> Name: 
> Your e-mail: 
>  additional field test: 
> Message: 
> 
>   
> {% endblock %}
>
> However it's not working at all. I can see the form displayed thanks to
> the HTML Template, but nothing is happening when I press Submit. There is
> no example on the website on how to subclass it :(
> http://django-contact-form.readthedocs.org/en/latest/quickstart.html
> Or should I just copy and paste the whole code from here and adapt it to
> include additional fields:
> https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default
>
>
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/e72e813c-d78b-433f-8444-e76a4129c862%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/CALn3ei2Cu%3DJRZCeZAZ_%3DN6Hy%2B47FAErTAjZHzMNWcEo9nZMqug%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Authenticate users with both username and email

2015-01-19 Thread James Schneider
I guess I'm not clear on what you are trying to achieve. There are a couple
of scenarios to consider.

As it stands with the default contrib.auth authentication backend, sending
both the username and email address entered by the user will only work IF
the user registered/was created using their email address as their
username, meaning that user.username is either their username (a string
that isn't their email), or an email address, regardless of what user.email
returns. The default contrib.auth authentication backend only looks at
user.username.

What I suspect you want is to be able to use either user.username OR
user.email as the identifying tokens for the user in order to authenticate
them. For that, you'll need to roll at least a partial custom
authentication backend, in addition to the changes for the forms, etc. that
you've already laid out.

From
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#writing-an-authentication-backend
:

"If you wish to provide custom behavior for only part of the backend API,
you can take advantage of Python inheritance and subclass *ModelBackend*
instead of implementing the complete API in a custom backend."

Specifically, you'll need to override the authenticate() method of the
authentication backend.

I've done this, it's actually pretty easy. See:

https://github.com/django/django/blob/master/django/contrib/auth/backends.py#L11

In this case, you should also roll a custom user model as well to ensure
that both user.username and user.email are unique columns. If you use the
email address as an identifying token, it will need to be unique among all
users, which is not true/enforced for the built-in contrib.auth User model.
You will also need to override the custom User manager for your new
CustomUser, probably with and override for get_by_natural_key(token) so
that the user can be retrieved in the backend authenticate() method. The
key change in get_by_natural_key() being the filter for the user object
being changed to something like User.objects.get(Q(username=token) |
Q(email=token)).

(If you haven't seen the Q() notation, check
https://docs.djangoproject.com/en/1.7/ref/models/queries/#q-objects)

The custom user you probably want is somewhat similar to the example given
in the docs:

https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#a-full-example

You'll need to add a 'username' field back in (remember to make it unique)
along with several other tweaks to be able to use either a username or
email field. An alternative would be a custom user class inheriting from
AbstractBaseUser and copying in the goodies you need from AbstractUser
(which is probably everything except the username and email fields, which
you'll be defining as unique). Be sure to include the Permission mixins
that AbstractUser has if you intend to use the built-in permission system
with your CustomUser.

Sorry about the lengthy message, there are a bunch of ways to tackle this,
but ultimately I think you'll be rolling your own user and at least part of
the authentication system, not to mention having to customize the user
forms. The user will be slightly tricky, as there is no clear inheritance
path that will make it easy AFAICT, but the auth backend should be just a
class with a single authenticate() function if you inherit from
ModelBackend. Be sure to either include your custom backend in
AUTHENTICATION_BACKENDS, or possibly even replacing it if you go with the
Q() query I specified earlier (since an auth request using an email would
generate two authentication queries if both backends are used, and the
username field is checked twice).

TL;DR; Overriding the user forms is probably not enough, you'll need a
custom user and custom authentication backend.

Not sure if I made the situation better or worse, but HTH...

Obviously, YMMV, I haven't tried this myself, but I have done a fair bit of
overriding for a custom object-based permission system, which touches many
of the same structures above.

-James






On Mon, Jan 19, 2015 at 1:26 AM, Abraham Varricatt <
abraham.varric...@googlemail.com> wrote:

> Ignoring the malformed code, will the call to authenticate() even work
> without username? According to the docs,
>
> https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.authenticate
>
> It takes credentials in the form of keyword arguments, for the default
>> configuration this is username and password, and it returns a User
>> 
>> object if the password is valid for the given username.
>>
>>
> If someone wanted to change the default behavior, I would expect them to
> at least override the function. OP doesn't seem to have done this, so it
> shouldn't even work. (Please correct me if I'm missing something)
>
> -Abraham V.
>
> On Friday, January 16, 2015 at 2:37:13 AM UTC+5:30, Matt Cooper wrote:
>>
>> Your if block in views.py is not well-formed. I haven't 

How to subclass django-contact-form to create custom contact form?

2015-01-19 Thread Tobias Dacoir
I need to include two different contact forms in my app. One a general 
contact form and another Report / Feedback form that pre-fills some data 
depending on which site it was called from. 
So I hit google, found django-contact-form, installed it and after creating 
some basic templates (and rest of the configuration) I was able to make use 
of /contact/ to present a basic form which takes in Name, Email and 
Message. Works fine.

Now I need that Report Form. The idea is to have a 'Report' Button on the 
Website which maps to /report/$Parameter (or maybe it will just put the 
parameter into request, not sure yet how to do this).
However I have troubles getting my Custom Form to work. I tried to create a 
new view that uses my custom form which just inherits from ContactForm:

forms.py:
class ReportForm(ContactForm):
additional = forms.CharField(max_length=100, label='additional field 
test')
subject_template_name = "contact_form/report_form_subject.txt"
template_name = 'contact_form/report_form.txt'



views.py:
def report(request):
reportForm = ReportForm
return render(request, 'play/report.html', {'form': reportForm})




template report.html:
{% extends 'base.html' %}

{% block body_block %}
Report Form
  To send us a message fill out the below form.
  {% csrf_token %}
Name: 
Your e-mail: 
 additional field test: 
Message: 

  
{% endblock %}

However it's not working at all. I can see the form displayed thanks to the 
HTML Template, but nothing is happening when I press Submit. There is no 
example on the website on how to subclass it :(
http://django-contact-form.readthedocs.org/en/latest/quickstart.html
Or should I just copy and paste the whole code from here and adapt it to 
include additional fields: 
https://bitbucket.org/ubernostrum/django-contact-form/src/4b7d2fa20c1d01568fb7c4c800155378e176923b/contact_form/forms.py?at=default



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/e72e813c-d78b-433f-8444-e76a4129c862%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: filter

2015-01-19 Thread Abraham Varricatt
In addition to the other answers, I will suggest that you re-think your 
view logic - you haven't handled the case where your IF block fails. 
Remember, Django expects every view function to return a HttpResponse 
object. Assume that someone's request isn't authorized (yet) or even 
rejected. What do you want them to see? It's good user experience to at 
least show an error message instead of throwing them back to the home-page.

-Abraham V.


On Friday, January 16, 2015 at 5:11:10 AM UTC+5:30, suabiut wrote:
>
>
>
> Hi,
> I am trying to two column and display some result if two conditions are 
> meet but i am getting this error: 
>
> The view eLeave.views.FMKD1_leave_to_authorize didn't return an HttpResponse 
> object. It returned None instead.
>
>
> I can seems to figure out the issue, here is my view.py file
>
> def FMKD1_leave_to_authorize(request):
> new_leave 
> =newleave.objects.filter(department_head_authorization="Approved" )
> a = newleave.objects.filter(department="FMKD")
> if new_leave=="True"and a =="True":
> return render_to_response('FMKD1_display_approve_leave.html', 
> locals())
>  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/0a995400-c49c-455e-86ee-2dc89f56c963%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Authenticate users with both username and email

2015-01-19 Thread Abraham Varricatt
Ignoring the malformed code, will the call to authenticate() even work 
without username? According to the docs,
https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.authenticate

It takes credentials in the form of keyword arguments, for the default 
> configuration this is username and password, and it returns a User 
> 
>  
> object if the password is valid for the given username.
>
>
If someone wanted to change the default behavior, I would expect them to at 
least override the function. OP doesn't seem to have done this, so it 
shouldn't even work. (Please correct me if I'm missing something)

-Abraham V.

On Friday, January 16, 2015 at 2:37:13 AM UTC+5:30, Matt Cooper wrote:
>
> Your if block in views.py is not well-formed. I haven't tested this but 
> I'd write it more like this:
>
> # try username
> user = auth.authenticate(username=username, password=password)
> if user is not None:
> auth.login(request, user)
> return HttpResponseRedirect('/')
> # fall-through to email
> user = auth.authenticate(email=username, password=password)
> if user is not None:
> auth.login(request, user)
> return HttpResponseRedirect('/')
> # ok, neither one worked
> return HttpResponseRedirect('/accounts/invalid_login')
>
>
> On Wednesday, January 14, 2015 at 10:07:29 PM UTC-8, Kakar Nyori wrote:
>
>> I have extendted the *UserCreationForm* with email and other fields, so 
>> that I could authenticate a user with both its username and email.
>>
>> forms.py:
>>
>>> class UserCreationForm(UserCreationForm):
>>> class Meta:
>>> model = User
>>> fields = ('first_name', 'last_name', 'username', 'email',)
>>
>>
>>  
>> views.py:
>>
>> def auth_view(request):
>>> username = request.POST.get('username','')
>>> password = request.POST.get('password','')
>>> user = auth.authenticate(username=username, password=password)
>>> if user is not None:
>>> auth.login(request, user)
>>> return HttpResponseRedirect('/')
>>> elif:
>>> user = auth.authenticate(email=username, password=password)
>>> if user is not None:
>>> auth.login(request, user)
>>> return HttpResponseRedirect('/')
>>> else:
>>> return HttpResponseRedirect('/accounts/invalid_login')
>>
>>
>> html:
>>
>> 
>>> {%csrf_token%}
>>> Email or Username:
>>> 
>>> Password:
>>> 
>>> 
>>> 
>>
>>
>>
>> In the views I tried giving both the *username* and *email *as input 
>> from the form as *name*, and check to see if username and password 
>> authenticate. If not then check whether email and password authenticate. 
>> But its not working. How do I solve this problem? Please kindly 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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c7e27779-311b-43f4-b66d-d3548becdc26%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why this code does not change users firstname and lastname?

2015-01-19 Thread Daniel Roseman
On Monday, 19 January 2015 09:22:02 UTC, joulumaa wrote:
>
> I have created user earlier in code with email address and password. 
> Created users work fine.
> Now in later phase I asked more information and would like to fill in 
> first_name and last_name.
> Code shows old first_name and last_name properly if set in admin view, but 
> logged in user cannot save his information for some reason?
>
>   p=User.objects.get(username=request.user.username)
> if request.method == 'POST':
> form = AdditionalCandidateInfo(request.POST)
> if form.is_valid():
> p.first_name=form.cleaned_data['first_name']
> p.last_name=form.cleaned_data['last_name']
> p.save()
> return HttpResponseRedirect('/')
> else:
> form = 
> AdditionalCandidateInfo(initial={'first_name':p.first_name,'last_name':p.last_name})
>
>
> -thanks for help
>

You should be using a ModelForm, and pass the `instance` argument when 
instantiating the form.

Also there's no point querying User: `request.user` is *already* the 
relevant User instance.
--
DR.

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


Why this code does not change users firstname and lastname?

2015-01-19 Thread joulumaa
I have created user earlier in code with email address and password. 
Created users work fine.
Now in later phase I asked more information and would like to fill in 
first_name and last_name.
Code shows old first_name and last_name properly if set in admin view, but 
logged in user cannot save his information for some reason?

  p=User.objects.get(username=request.user.username)
if request.method == 'POST':
form = AdditionalCandidateInfo(request.POST)
if form.is_valid():
p.first_name=form.cleaned_data['first_name']
p.last_name=form.cleaned_data['last_name']
p.save()
return HttpResponseRedirect('/')
else:
form = 
AdditionalCandidateInfo(initial={'first_name':p.first_name,'last_name':p.last_name})
   

-thanks for 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/13b71151-9f2a-4371-be02-4ba57d451dc3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Daniel Roseman
On Monday, 19 January 2015 07:28:14 UTC, Cheng Guo wrote:
>
> Hello,
>
> I am new to Django and I have run into an issue with views.py.  I 
> understand that there is a function behind each view. For a view that I am 
> currently writing, it accepts a file upload from user and stores the file 
> on the server. To do that, I need to:
>
> 1. check the file extension is correct
> 2. generate a SHA-1 id for the file based on its content
> 3. write the file to disk
> 4. save information about the file to database
>
> (oh, I also created two global variables as well)
>
>
Others have pointed out ways to split this up, but I wanted to pick up on 
the last sentence. You really really should not be setting global variables 
in your view, especially in response to user input. Global variables are 
shared by all requests in a process, and you can't guarantee either that 
all requests will be from the same user, or even that the same user will 
hit the same process in subsequent requests. Don't do this: if you need to 
store state between requests, use the db or the session.
--
DR.

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


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread James Schneider
I wouldn't decorate them as class methods. You would want to call them from
the objects themselves. For the save_to_disk() method, I was actually
referring to the Django save() method (
https://docs.djangoproject.com/en/1.7/topics/db/models/#overriding-predefined-model-methods
).

As you have it now, it wouldn't work since you would need to call
UploadFile.generate_id(), but you don't have an available argument to pass
in the UploadFile object to get the ID for.

If you remove the decorator, you would call it on the object itself:
class UploadFile(models.Model):

def generate_id(self):
# pseudocode to do stuff to generate ID using self
# import hashlib
# self.file_hash = hashlib.sha1(self.file, 'rb')
# return the ID or None if it fails
# return self.file_hash or None

# override the model save method to generate the hash ID, then save for
real
def save(self):
self.generate_id()
super(UploadFile, self).save(*args, **kwargs)

You probably don't need to change your view logic at all in this case
(unless you have code that generates the hash and attaches it to the
object, then remove it and let the object handle that itself). Basically,
when your UploadFile object is saved, it will call the save() method on the
object, which in turn will generate the ID based on the file, attach it to
the object, and then save the object to the database.

Note that this will run the hashing mechanism every time the object is
saved, whether the file it points at changes or not. If this isn't what you
want, I would add an extra checks in generate_id() to account for all of
the scenarios where you wan the hash to update (every time the object is
saved vs. only when the file changes vs. only generated once even with a
file change, etc.).

In a typical scenario where the hash is run every time the object is saved,
the object itself would create the hash. This way you can save the object
from any view (or from the shell), and it would always generate a new hash
automagically (new meaning recalculated, may end up the same as the
previous value).

TL;DR; The hash shouldn't be calculated external to the file that is
attached to the object, it should be calculated by the object itself.

Hope that helps and makes sense...

-James


On Jan 19, 2015 12:37 AM, "Cheng Guo"  wrote:

> So in my case, I need to generate a unique id for the file and save it to
> disk.
>
> I have a model called UploadFile, so you recommend to add two class
> methods to the UploadFile model, like the following?
>
> class UploadFile(models.Model):
> @classmethod
> def generate_id():
> pass
>
> @classmethod
> def save_to_disk():
> pass
>
>
> On Monday, 19 January 2015 16:12:28 UTC+8, daniel.franca wrote:
>>
>> If the operations are model related, why don't move some of those
>> functions to models.py.
>> On Mon 19 Jan 2015 at 08:46 Mike Dewhirst  wrote:
>>
>>> On 19/01/2015 6:28 PM, Cheng Guo wrote:
>>> > Hello,
>>> >
>>> > I am new to Django and I have run into an issue with views.py.  I
>>> > understand that there is a function behind each view. For a view that I
>>> > am currently writing, it accepts a file upload from user and stores the
>>> > file on the server. To do that, I need to:
>>> >
>>> > 1. check the file extension is correct
>>> > 2. generate a SHA-1 id for the file based on its content
>>> > 3. write the file to disk
>>> > 4. save information about the file to database
>>> >
>>> > (oh, I also created two global variables as well)
>>> >
>>> > As you can see, if more features are added, the list goes on. It makes
>>> > this function very long. As the number of views grow, the views.py file
>>> > will become bloated. I wonder what would be the ideal way to deal with
>>> this?
>>> >
>>> > Something that I can think of but not sure if it is correct:
>>> >
>>> > - divide the long function up into smaller functions
>>> > - store these smaller functions in a different .py file
>>>
>>> Absolutely correct. But first create a views directory (complete with
>>> __init__.py file therein) to completely replace your views.py file.
>>>
>>> Then any number of files can contain your views ...
>>>
>>> from app.views.this import That
>>>
>>> ... where this.py has a class That
>>>
>>>
>>> >
>>> > Let me know your approach, 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/bf9f6ff3-a35a

Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
So in my case, I need to generate a unique id for the file and save it to 
disk.

I have a model called UploadFile, so you recommend to add two class methods 
to the UploadFile model, like the following?

class UploadFile(models.Model):
@classmethod
def generate_id():
pass

@classmethod
def save_to_disk():
pass


On Monday, 19 January 2015 16:12:28 UTC+8, daniel.franca wrote:
>
> If the operations are model related, why don't move some of those 
> functions to models.py.
> On Mon 19 Jan 2015 at 08:46 Mike Dewhirst  > wrote:
>
>> On 19/01/2015 6:28 PM, Cheng Guo wrote:
>> > Hello,
>> >
>> > I am new to Django and I have run into an issue with views.py.  I
>> > understand that there is a function behind each view. For a view that I
>> > am currently writing, it accepts a file upload from user and stores the
>> > file on the server. To do that, I need to:
>> >
>> > 1. check the file extension is correct
>> > 2. generate a SHA-1 id for the file based on its content
>> > 3. write the file to disk
>> > 4. save information about the file to database
>> >
>> > (oh, I also created two global variables as well)
>> >
>> > As you can see, if more features are added, the list goes on. It makes
>> > this function very long. As the number of views grow, the views.py file
>> > will become bloated. I wonder what would be the ideal way to deal with 
>> this?
>> >
>> > Something that I can think of but not sure if it is correct:
>> >
>> > - divide the long function up into smaller functions
>> > - store these smaller functions in a different .py file
>>
>> Absolutely correct. But first create a views directory (complete with
>> __init__.py file therein) to completely replace your views.py file.
>>
>> Then any number of files can contain your views ...
>>
>> from app.views.this import That
>>
>> ... where this.py has a class That
>>
>>
>> >
>> > Let me know your approach, 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/bf9f6ff3-
>> a35a-4f00-8537-c6fd66d07f8d%40googlegroups.com
>> > > a35a-4f00-8537-c6fd66d07f8d%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...@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/54BCB642.8040201%40dewhirst.com.au.
>> 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/80aef78c-9cec-4e50-be11-bc506d019b8c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread James Schneider
I second moving some (or most) of the functionality to models.py. For
instance, calculating the SHA value should be done as part of the model's
save() function, not done in the view.

Convention dictates that the only code that is placed in the view itself
should be logic related to prepping the templates for rendering/displaying
things, such as setting variables in the template context.

Any operations related to 'business logic' such as data manipulation (ie
save behavior) as it relates to specific objects should be handled by the
object/model itself. Ideally, the model instance should be smart enough to
save itself (or perform some other action) on its own without any input
from the view, assuming the necessary values for the operation are provided
from some other source.

Obviously this is only a convention and not a rule, but it will likely
serve you better in the long run. In general, views tend to be quite short.
My class-based views just have a couple of class-level attributes set, if
anything at all (although they rely heavily on inherited behavior from
parent class views, which are much more complicated).

-James
On Jan 19, 2015 12:11 AM, "Daniel França"  wrote:

> If the operations are model related, why don't move some of those
> functions to models.py.
> On Mon 19 Jan 2015 at 08:46 Mike Dewhirst  wrote:
>
>> On 19/01/2015 6:28 PM, Cheng Guo wrote:
>> > Hello,
>> >
>> > I am new to Django and I have run into an issue with views.py.  I
>> > understand that there is a function behind each view. For a view that I
>> > am currently writing, it accepts a file upload from user and stores the
>> > file on the server. To do that, I need to:
>> >
>> > 1. check the file extension is correct
>> > 2. generate a SHA-1 id for the file based on its content
>> > 3. write the file to disk
>> > 4. save information about the file to database
>> >
>> > (oh, I also created two global variables as well)
>> >
>> > As you can see, if more features are added, the list goes on. It makes
>> > this function very long. As the number of views grow, the views.py file
>> > will become bloated. I wonder what would be the ideal way to deal with
>> this?
>> >
>> > Something that I can think of but not sure if it is correct:
>> >
>> > - divide the long function up into smaller functions
>> > - store these smaller functions in a different .py file
>>
>> Absolutely correct. But first create a views directory (complete with
>> __init__.py file therein) to completely replace your views.py file.
>>
>> Then any number of files can contain your views ...
>>
>> from app.views.this import That
>>
>> ... where this.py has a class That
>>
>>
>> >
>> > Let me know your approach, 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/bf9f6ff3-
>> a35a-4f00-8537-c6fd66d07f8d%40googlegroups.com
>> > > a35a-4f00-8537-c6fd66d07f8d%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/54BCB642.8040201%40dewhirst.com.au.
>> 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/CACPst9JZnMGK8vS00G1oqwEVt9qbf3TnTsdoJCwdy-mN02qEPw%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are 

Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
Great, thanks!

On Monday, 19 January 2015 15:46:40 UTC+8, Mike Dewhirst wrote:
>
> On 19/01/2015 6:28 PM, Cheng Guo wrote: 
> > Hello, 
> > 
> > I am new to Django and I have run into an issue with views.py.  I 
> > understand that there is a function behind each view. For a view that I 
> > am currently writing, it accepts a file upload from user and stores the 
> > file on the server. To do that, I need to: 
> > 
> > 1. check the file extension is correct 
> > 2. generate a SHA-1 id for the file based on its content 
> > 3. write the file to disk 
> > 4. save information about the file to database 
> > 
> > (oh, I also created two global variables as well) 
> > 
> > As you can see, if more features are added, the list goes on. It makes 
> > this function very long. As the number of views grow, the views.py file 
> > will become bloated. I wonder what would be the ideal way to deal with 
> this? 
> > 
> > Something that I can think of but not sure if it is correct: 
> > 
> > - divide the long function up into smaller functions 
> > - store these smaller functions in a different .py file 
>
> Absolutely correct. But first create a views directory (complete with 
> __init__.py file therein) to completely replace your views.py file. 
>
> Then any number of files can contain your views ... 
>
> from app.views.this import That 
>
> ... where this.py has a class That 
>
>
> > 
> > Let me know your approach, 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/bf9f6ff3-a35a-4f00-8537-c6fd66d07f8d%40googlegroups.com
>  
> > <
> https://groups.google.com/d/msgid/django-users/bf9f6ff3-a35a-4f00-8537-c6fd66d07f8d%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/6e8cf6a4-1967-495b-bfa4-95f9880b0457%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Cheng Guo
Great, 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/3065c69f-2930-43bc-9d12-e8b36a9a63c4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Newbie question: How to avoid a very long view function?

2015-01-19 Thread Daniel França
If the operations are model related, why don't move some of those functions
to models.py.
On Mon 19 Jan 2015 at 08:46 Mike Dewhirst  wrote:

> On 19/01/2015 6:28 PM, Cheng Guo wrote:
> > Hello,
> >
> > I am new to Django and I have run into an issue with views.py.  I
> > understand that there is a function behind each view. For a view that I
> > am currently writing, it accepts a file upload from user and stores the
> > file on the server. To do that, I need to:
> >
> > 1. check the file extension is correct
> > 2. generate a SHA-1 id for the file based on its content
> > 3. write the file to disk
> > 4. save information about the file to database
> >
> > (oh, I also created two global variables as well)
> >
> > As you can see, if more features are added, the list goes on. It makes
> > this function very long. As the number of views grow, the views.py file
> > will become bloated. I wonder what would be the ideal way to deal with
> this?
> >
> > Something that I can think of but not sure if it is correct:
> >
> > - divide the long function up into smaller functions
> > - store these smaller functions in a different .py file
>
> Absolutely correct. But first create a views directory (complete with
> __init__.py file therein) to completely replace your views.py file.
>
> Then any number of files can contain your views ...
>
> from app.views.this import That
>
> ... where this.py has a class That
>
>
> >
> > Let me know your approach, 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/bf9f6ff3-
> a35a-4f00-8537-c6fd66d07f8d%40googlegroups.com
> >  a35a-4f00-8537-c6fd66d07f8d%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/54BCB642.8040201%40dewhirst.com.au.
> 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/CACPst9JZnMGK8vS00G1oqwEVt9qbf3TnTsdoJCwdy-mN02qEPw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.