Re: Multiple levels of user in django application

2014-11-30 Thread Anju SB




I am basically a PHP programmer, and  I have been assigned modify existing 
django application.  Now I want to create a login for  all the 5 levels of 
users and their functionalities are differentiated based on the  roles. 
 Customization of admin page for adding new user and map it with the 
corresponding user details. 

I have attached the models that I want to map with the django user.   I 
want a best solution for mapping the users with different group members 
using this django application.  



 


On Saturday, 29 November 2014 22:50:25 UTC+5:30, Scot Hacker wrote:
>
> On Saturday, November 29, 2014 8:49:25 AM UTC-8, Anju SB wrote:
>>
>>
>> Thank your for your reply.  Actually I created another model that 
>> aggregates all the values from each group table.  but after analyzing I 
>> feel its a worst method and performance is also very low.So model re-design 
>> is the only way to sort out this issue and need  help for redesigning the 
>> models.  Because I want to add users and map these users to group details 
>> from the admin page.  I am very confused state and I don't know how to 
>> re-design and optimize the queries.   
>>
>>>
>>>  
> Django makes it easy to have multiple profile types with different sets of 
> custom fields, and various permissions levels (roles). The admin does a 
> good job of letting you add users to groups. I think you're going to have 
> to spell out your problem/goals with more detail - we're not clear on 
> exactly what's not working for you.  It might help (you and us) if you 
> sketched out your desired model relationships with a charting tool or 
> graphics program, or even as ascii art. 
>
> ./s
>

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


Re: how add path to open()

2014-11-30 Thread Dariusz Mysior
Yes this is it :)

thanks :)

W dniu niedziela, 30 listopada 2014 20:24:44 UTC+1 użytkownik Collin 
Anderson napisał:
>
> Hi,
>
> I think you want something like this. (Just make sure a login name doesn't 
> have '..' in it :).
>
> filehandler = open('users/' + login, "wb")
>
> Collin
>
>
> On Saturday, November 29, 2014 2:35:31 PM UTC-5, Dariusz Mysior wrote:
>>
>> I join to topic with my problem
>>
>> I want to create new file with login and password in new file and I can 
>> do it with code below, but I don't know how save this new files in one 
>> folder users
>> def rejestracja(login, haslo): save=None login_tmp=login haslo_tmp=haslo 
>> save={login_tmp:haslo_tmp}
>>
>>  filehandler=open(login,"wb")
>> pickle.dump(save,filehandler)
>> filehandler.close()
>> filehandler=open(login,"rb")
>> file=pickle.load(filehandler)
>> filehandler.close()
>> print file
>> raw_input("\n\nWcisnij [ENTER]: ")
>>
>>
>>

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


Re: Generic Views and Django.contrib.auth

2014-11-30 Thread Rootz
Hi can this work with url reversing namespaced urls?
thanks

On Thursday, October 16, 2014 11:54:45 AM UTC-5, Vijay Khemlani wrote:
>
> If you are usign class based generic views you can use the decorators in 
> the URL config of your app, for example
>
> urlpatterns = patterns('',
> (r'^about/', login_required(AboutView.as_view())),
> )
>
>
> On Thu, Oct 16, 2014 at 12:49 PM, Rootz > 
> wrote:
>
>> Can I use both Generic View and the Django.contrib.auth features (such as 
>> login_required decorator and other auth interface tool)? And if it is not 
>> possible to integrate auth into Generic Views then can you recommend 
>> alternative way of making the two work together? Adding to this I am using 
>> Django 1.7v and python 3.4v. 
>>
>> 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...@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/09fe215a-4572-418c-959f-567e9ab05b0b%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/688a1152-690e-41a9-91e1-72cf0f21b631%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: template url reverse and namespacing is driving me crazy

2014-11-30 Thread Kelvin Wong
Change all instances of this in your templates

{% url 'greet' greeter.pk %}

To this

{% url 'greeter:greet' greeter.pk %}.

Since you are now using the 'greeter' namespace. Also, the other one is 

{% url 'greeter:list' %} and not {% url 'list' %} because you are using the 
'greeter' namespace.

K

On Sunday, November 30, 2014 11:51:17 AM UTC-8, pjotr wrote:
>
> Alright, I'm already crazy, so the subject is a bit of a lie. But 
> nevermind.
>
> I think I like namespacing, it is really nice. But there is something not 
> that clear in the documentation of Django, and how to make usage of 
> namespace, in a consistent way. Lets take it by example.
>
> I'm using this pretty amazing app "greeter" that was written by a 
> superuser from a country far away from my own. It is a pretty simple app, 
> that has two url mappings:
>
> url(r'^list/$', HelloWorldList.as_view(), name='list'),
> url(r'^greet/(?P\d+)/$', HelloWorldGreet.as_view(), name='greet'),
>
>
> The template of HelloWorldList view is using the template tag url like this: 
> {% url 'greet' greeter.pk %}.
>
> After that I hook up the application in my project by including it in my 
> project urls.py:
>
> url(r'^greeter/', include('greeter.urls')),
>
>
> Everything works well, I felt like a Django guru integrating the hello 
> world app to my own project. I can access /greeter/list and clicking on the 
> greetings works well.
>
> Later that night I go to bed, feeling confident, kissing my wife goodnight 
> with a smile on my face. I wake up warm, sweaty, with my heart beating. I 
> run to my laptop, just realized I forgot to namespace the greet app, 
> because I just realized I am using the list name in another place in my 
> project, and I don't have any automated tests, so I better namespace it 
> quickly.
>
> So, I change my project url mapping to this:
>
> url(r'^greeter/', include('greeter.urls', namespace='greeter')),
>
>
> Boom crash. Visiting the /greeter/list/ page gives me:
>
>
> Reverse for 'greet' with arguments '()' and keyword arguments '{pk:1}' not 
> found. 0 pattern(s) tried: []
>
>
> I start to doubt the author of the 'greeter' app, that he didn't prepare his 
> app for being used in other projects, where the project might need 
> namespacing to avoid conflicts.
>
>
> Digging into Django documentation, I don't really find any argument for the 
> author of the 'greeter' app to be sloppy and not caring of details.
>
>
> Someone who can enlighten me why django doesn't try to default to the current 
> app when resolving namespaces? Or can someone enlighten me how I can help out 
> the author of the 'greeting' app, so it really is reusable in other projects?
>
>

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


Re: Simple Login Problem

2014-11-30 Thread Rootz
Apparently caching was enable. Now that I know I disable caching and now it 
is working now..
thanks :)

On Sunday, November 30, 2014 1:32:27 PM UTC-5, Collin Anderson wrote:
>
> Hi,
>
> If you type your password wrong, user will be None, and your code will 
> then redirect to the "register" page.
>
> If you press "back" after a successful login, the CSRF token will be out 
> of date and the form won't work.
>
> Are you caching any pages?
>
> Collin
>
> On Friday, November 28, 2014 12:55:35 AM UTC-5, Rootz wrote:
>>
>> I have a django app but I having problems with my login views and logout 
>> views. I do not have a html template designated to handle user login/logout 
>> view.
>> Django project is configured as follows:
>>
>> INSTALLED_APPS 
>> 
>>  setting:
>>
>>1. 'django.contrib.auth' contains the core of the authentication 
>>framework, and its default models.
>>2. 'django.contrib.contenttypes' is the Django *content type system* 
>>, 
>>which allows permissions to be associated with models you create.
>>3. 'django.contrib.sessions',
>>
>>  MIDDLEWARE_CLASSES 
>> 
>>  setting:
>>
>>1. SessionMiddleware 
>>
>> 
>> manages *sessions* 
>> across 
>>requests.
>>2. AuthenticationMiddleware 
>>
>> 
>>  associates 
>>users with requests using sessions.
>>3. csrf.CsrfViewMiddleware 
>>
>>
>> Using Django Template Language and Template inheritance. The login form 
>> is on the base template on other templates extends from this base template.
>>
>> All my login attempts result in some of the views rendering the user info 
>> (username to welcome user back) while other views rendering the page as if 
>> the user is an anonymous user. If I try to login in again I get an error 
>> page stating that there is a missing csrf token or incorrect. Adding to 
>> this I have identified many instances where I have tried to logout and it 
>> does not seem to log me out because it is still showing the last user login 
>> info. For my base template I have hard coded the form (meaning not using 
>> Django Form class).
>>
>> Can You identify the possible fault in how i am implementing the login 
>> and logout views?
>>
>>  
>>  Here is a copy of my login and logout views
>>
>> def members_login(request):
>>
>> if request.method == 'POST':
>> password = request.POST['password']
>> username = request.POST['username']
>> user = authenticate(username=username,password=password)
>>
>> if user is not None:
>> if user.is_active:
>> login(request,user)
>> return redirect('members:index')
>> else:
>> #inactive users required to re-register
>> return redirect('members:index')
>> else:
>> #no account required to register to create one
>> return redirect('members:register')
>> 
>> else:
>> #test if login is a regular get request then redirect
>> return HttpResponseRedirect(reverse('members:index'))
>>
>>
>> def members_logout(request):
>> logout(request)
>> return redirect('members:index')
>>
>>

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


Re: defining an app stub using AppConfig?

2014-11-30 Thread Eric Abrahamsen
Collin Anderson  writes:

> Hi Eric,
>
> I'm not sure, but is this what you want?
>
> models = apps.get_app_config(setting.NEWSLETTER_APP).models_module
>
> Collin

Thanks Collin. I think that would do what I want, but in the end I
decided the easier way to go would be to fork the app, then experiment
with switching code in the app itself, rather than switching apps in my
Django project. Whether or not that will actually turn out to be simpler...

> On Tuesday, November 25, 2014 1:50:40 AM UTC-5, Eric Abrahamsen wrote:
>
> I'm messing around with testing many Github forks of the emencia 
> newsletter app, looking for one I like. In the meantime (and as
> I'm 
> likely to continue switching around for a while), I'd like not to
> have 
> to commit code that points at the different names of the different
> apps: 
> they all have the same models and database structure, the only
> thing 
> that changes is the top-level name of the module. 
> 
> I looked at the code for contrib/comments, and have some questions
> about 
> using AppConfig. 
> 
> What I'd like to do is have a setting in settings.py that reads: 
> 
> NEWSLETTER_APP='maja_newsletter' 
> 
> Or what have you. This would change semi-regularly as I test. 
> 
> Then I'd have a top-level file called newslettermodule.py, with 
> something like this in it: 
> 
> from django.conf import settings 
> from django.apps import apps 
> 
> module = apps.get_app_config(settings.NEWSLETTER_APP.rpartition
> (".")[2]).module 
> 
> 
> Here's where I'm having trouble. Is there any way that I can
> basically 
> dump all the models from what would be module.models into this
> file? 
> Playing with this in the shell, when I try to import actual models
> from 
> module.models I get an "No module named module.models", even
> though 
> eval'ing "module.models" directly gives me: 
> 
>  
> 
> Clearly this is just a misunderstanding on my part about how
> Python 
> modules work. 
> 
> Is there anything I can do? Looking at the code in
> contrib/comments I 
> suspect not -- if there were, it would have been done there. 
> 
> Anyway, thanks for any light shed on how AppConfig can be used in
> this 
> situation... 
> 
> Eric 

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


Re: simplifying double decorators?

2014-11-30 Thread Richard Brockie
Hi,

Thanks for the responses.

@Arnold:

The way I see this working is that @login_required decorator prompts the
user to login if they are not already. If there is a valid user who fails
the test, they login correctly, but are redirected to the homepage.

Without the @login_required, there is no prompt to login. I'm anticipating
these pages being bookmarked and would like the user to be taken directly
to the expected page after a successful login.

@Collin:

Thanks for the suggestion - that works!. New to me is the ...)(view)
syntax. Do I understand correctly that I could add another line following
the same structure and reversal of order? Eg:

@decorator1(kwarg1='testing')
@decorator2(kwarg2='something')
@decorator3
def my_view...

becomes:

def triple_decorator(view):
view = decorator3()(view)
view = decorator2(kwarg1='something')(view)
return decorator1(kwarg2='testing')(view)

@triple_decorator()
def my_view...


Thanks very much!

R.


On Sun, Nov 30, 2014 at 11:48 AM, Arnold Krille 
wrote:

> On Sun, 30 Nov 2014 10:30:29 -0800 Richard Brockie
>  wrote:
> > I'm running into the situation where I have several views with the
> > same set of decorators:
> > @login_required()
> > @user_passes_test(some_test_function, login_url='/',
> > redirect_field_name=None)
> > def some_view(request):
> > # some code
> > return render(request, 'some_template.html', locals())
> >
> > How would I go about combining the two (or more) decorators into a
> > single decorator that can be used instead and retain the
> > functionality?
>
> Well, if the user has to pass a test, you have to have a user first.
> And unless the AnonymousUser passes your permissions tests, the
> combination of "@login_required" and "@user_passes_test" is a
> redundancy… At least it was in my old project I worked for where we
> replaced these duplicates and used only the permissions tests and it
> worked great. No user -> no permissions to check for. (Actually it was
> no user -> no company & no roles -> no permissions.)
>
> Have fun,
>
> Arnold
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.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/20141130204816.48a79081%40xingu.arnoldarts.de
> .
> 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-vOUECDw1k5MHj%3D63QFuoovzxEG2GmNBexkOfyaM62VTorg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


template url reverse and namespacing is driving me crazy

2014-11-30 Thread pjotr
Alright, I'm already crazy, so the subject is a bit of a lie. But nevermind.

I think I like namespacing, it is really nice. But there is something not 
that clear in the documentation of Django, and how to make usage of 
namespace, in a consistent way. Lets take it by example.

I'm using this pretty amazing app "greeter" that was written by a superuser 
from a country far away from my own. It is a pretty simple app, that has 
two url mappings:

url(r'^list/$', HelloWorldList.as_view(), name='list'),
url(r'^greet/(?P\d+)/$', HelloWorldGreet.as_view(), name='greet'),


The template of HelloWorldList view is using the template tag url like this: {% 
url 'greet' greeter.pk %}.

After that I hook up the application in my project by including it in my 
project urls.py:

url(r'^greeter/', include('greeter.urls')),


Everything works well, I felt like a Django guru integrating the hello 
world app to my own project. I can access /greeter/list and clicking on the 
greetings works well.

Later that night I go to bed, feeling confident, kissing my wife goodnight 
with a smile on my face. I wake up warm, sweaty, with my heart beating. I 
run to my laptop, just realized I forgot to namespace the greet app, 
because I just realized I am using the list name in another place in my 
project, and I don't have any automated tests, so I better namespace it 
quickly.

So, I change my project url mapping to this:

url(r'^greeter/', include('greeter.urls', namespace='greeter')),


Boom crash. Visiting the /greeter/list/ page gives me:


Reverse for 'greet' with arguments '()' and keyword arguments '{pk:1}' not 
found. 0 pattern(s) tried: []


I start to doubt the author of the 'greeter' app, that he didn't prepare his 
app for being used in other projects, where the project might need namespacing 
to avoid conflicts.


Digging into Django documentation, I don't really find any argument for the 
author of the 'greeter' app to be sloppy and not caring of details.


Someone who can enlighten me why django doesn't try to default to the current 
app when resolving namespaces? Or can someone enlighten me how I can help out 
the author of the 'greeting' app, so it really is reusable in other projects?

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


Re: simplifying double decorators?

2014-11-30 Thread Arnold Krille
On Sun, 30 Nov 2014 10:30:29 -0800 Richard Brockie
 wrote:
> I'm running into the situation where I have several views with the
> same set of decorators:
> @login_required()
> @user_passes_test(some_test_function, login_url='/',
> redirect_field_name=None)
> def some_view(request):
> # some code
> return render(request, 'some_template.html', locals())
> 
> How would I go about combining the two (or more) decorators into a
> single decorator that can be used instead and retain the
> functionality?

Well, if the user has to pass a test, you have to have a user first.
And unless the AnonymousUser passes your permissions tests, the
combination of "@login_required" and "@user_passes_test" is a
redundancy… At least it was in my old project I worked for where we
replaced these duplicates and used only the permissions tests and it
worked great. No user -> no permissions to check for. (Actually it was
no user -> no company & no roles -> no permissions.)

Have fun,

Arnold

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


signature.asc
Description: PGP signature


Re: simplifying double decorators?

2014-11-30 Thread Collin Anderson
Hi,

def my_double_decorator(view):
view = user_passes_test(some_test_function, login_url='/', 
redirect_field_name=None)(view)
return login_required()(view)

Collin


On Sunday, November 30, 2014 1:31:12 PM UTC-5, Richard Brockie wrote:
>
> Hi,
>
> I'm running into the situation where I have several views with the same 
> set of decorators:
>
> @login_required()
> @user_passes_test(some_test_function, login_url='/', 
> redirect_field_name=None)
> def some_view(request):
> # some code
> return render(request, 'some_template.html', locals())
>
> How would I go about combining the two (or more) decorators into a single 
> decorator that can be used instead and retain the functionality?
>
> IE: this:
>
> @login_required()
> @user_passes_test(some_test_function, login_url='/', 
> redirect_field_name=None)
> def some_view...
>
> becomes abstracted to something like this:
>
> @my_custom_decorator_with_redirects()
> def some_view...
>
>
> -- 
> R.
>
> Richard Brockie
>
> 
>  

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


Re: how add path to open()

2014-11-30 Thread Collin Anderson
Hi,

I think you want something like this. (Just make sure a login name doesn't 
have '..' in it :).

filehandler = open('users/' + login, "wb")

Collin


On Saturday, November 29, 2014 2:35:31 PM UTC-5, Dariusz Mysior wrote:
>
> I join to topic with my problem
>
> I want to create new file with login and password in new file and I can do 
> it with code below, but I don't know how save this new files in one folder 
> users
> def rejestracja(login, haslo): save=None login_tmp=login haslo_tmp=haslo 
> save={login_tmp:haslo_tmp}
>
>  filehandler=open(login,"wb")
> pickle.dump(save,filehandler)
> filehandler.close()
> filehandler=open(login,"rb")
> file=pickle.load(filehandler)
> filehandler.close()
> print file
> raw_input("\n\nWcisnij [ENTER]: ")
>
>
>

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


Re: Problem with queryset filtering with Django’s new Prefetch option

2014-11-30 Thread Collin Anderson
Hi,

Try this:

chapters = Chapter.objects.filter(course=course).prefetch_related(
Prefetch('status_chapter', 
queryset=LessonStatus.objects.filter(student=request.user).select_related('lesson')),
)

Otherwise, maybe the to_attr will help.

Collin



On Saturday, November 29, 2014 8:21:03 AM UTC-5, Tobias Abdon wrote:
>
> I am trying to use prefetch_related’s new Prefetch option to further 
> filter a database query. Using debug toolbar I can see that 
> prefetch_related is doing its job in making only three DB queries. However, 
> I am positive that the queryset filter I’m passing in is not working. Even 
> though I’m using the option, all of the records are being retrieved in the 
> query.
>
> The goal of the below code is to show a list of Chapters. For each 
> chapter, show its lessons. For each lesson, show the logged in user’s 
> status (complete/incomplete).
>
> Models
> class Chapter(models.Model):
> status = models.IntegerField(choices=STATUS_CHOICES, default=1)
> name = models.CharField(max_length=100)
> slug = AutoSlugField(populate_from='name')
> desc = models.TextField()
>
> class Lesson(models.Model):
> name = models.CharField(max_length=100)
> chapter = models.ForeignKey(Chapter, related_name=‘les_chapter’)
>
> class LessonStatus(models.Model):
> status = models.IntegerField(choices=STATUS_CHOICES, default=1)
> lesson = models.ForeignKey(Lesson, related_name="status_lesson")
> student = models.ForeignKey(User)
> chapter = models.ForeignKey(Chapter, related_name=“status_chapter")
>
>
> View
> def chapter_list(request, course_slug):
>
> course = Course.objects.get(slug=course_slug)
>
> chapters = Chapter.objects.filter(course=course).prefetch_related(
> Prefetch('status_chapter__lesson__chapter', 
> queryset=LessonStatus.objects.filter(student=request.user)),
> )
>
> return TemplateResponse(request,
> 'course/chapter_list_parent.html',
> {'chapters': chapters, 'course': course,}
> )
>
>
> Template
> 
> {% for ch in chapters %}
> {{ ch.name }}
> {% for le in ch.status_chapter.all %}
> lesson status: {{ le.status }}
> lesson name: {{ le.lesson.name }}
> {% endfor %}
> {% endfor %}
> 
>
> When I run this code the LessonStatus is not being filtered by 
> student=request.user. Instead, it is simply getting all LessonStatus 
> records, including those that are for other users. 
>
> Can anyone see if there's something wrong with the above code? Or any 
> ideas how to troubleshoot? There are no errors generated.
>

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


Re: Constructing query

2014-11-30 Thread Collin Anderson
Hi,

This might work:

Tag.objects.filter(name__startswith='A').exclude(company=None).order_by(
'name').all()

Collin


On Friday, November 28, 2014 9:08:42 AM UTC-5, termopro wrote:
>
> I have 2 models:
> Companies and Tags.
>
> A company may have several tags associated with it, so Tag contains 
> many-to-many relation to Company.
>
> If i'd like to get Tags starting with "A" i'd write:
> tags = Tag.objects.filter(name__startswith='A').order_by('name').all()
>
> But how do i get the list of tags (beginning with letter 'A') which are 
> associated with at least 1 company ?
>
> In sql it would be something like:
>
> SELECT * FROM
> tag
> WHERE
> name LIKE 'A%' AND id IN (SELECT tag_id FROM tag_organization)
>
>
> *?*
>

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


Re: Test client to a redirect requiring a login doesn't set redirect_chain properly? [2nd follow-up]

2014-11-30 Thread Collin Anderson
Hi,

As of django 1.7, the admin will redirect to a separate login page 
(whatever url reverse('admin:login') returns).

https://github.com/django/django/commit/be0ad62994a340ad54a0b328771931932a45a899

You could use a middleware to do an earlier, more straightforward require 
login.

Collin


On Friday, November 28, 2014 7:46:05 AM UTC-5, Tim Chase wrote:
>
> On 2014-11-27 20:32, Tim Chase wrote: 
> > As a bit of follow-up information, if I use runserver and browse to 
> > the view, it redirects me to /admin/common/region/add/ but it 
> > displays as the login screen.  Am I missing why this wouldn't do a 
> > redirect to my named login URL? 
>
> A careful reading of [1] suggests that the admin provides its own 
> login page via the login_template setting: "Path to a custom template 
> that will be used by the admin site login view."  It apparently 
> renders this at the URL of the destination page rather than 
> redirecting to the regular (contrib.auth or some named auth-URL) and 
> providing a "next={{original_url}}" 
>
> Is there any way to get the admin to just use the contrib.auth login 
> page that I already have in place? 
>
> -tkc 
>
> [1] 
>
> https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.AdminSite.login_template
>  
>
>
>
>

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


Re: PDF not saving on Django using open()

2014-11-30 Thread Collin Anderson
Hi,

merger.write("document-output.pdf")
response.write(merger)
return response

This might work:

merger.write(response)
return response

Though, it would be more memory efficient to write it to a temporary file 
and then either redirect to that url or stream out the temporary file.

Collin


On Friday, November 28, 2014 5:06:14 AM UTC-5, George Rogers wrote:
>
> trying to save files on static after pdfcrowd provides the file. I've 
> tried adding the path to be specific it doesn't work.
>
> from PyPDF2 import PdfFileMerger, PdfFileReaderfrom django.template import 
> RequestContextfrom django.shortcuts import render_to_response, 
> get_object_or_404
> import pdfcrowdfrom django.http import HttpResponsefrom wildling.models 
> import *from django.shortcuts import redirect
> def home(request, template_name='brochures_form.html'):
> context = RequestContext(request)
> if request.method == 'POST':
> context['name'] = name = request.POST.get('name','')
> context['adults'] = adults = request.POST.get('adult','')
> context['children'] = children = request.POST.get('child','')
> context['infant'] = infant = request.POST.get('infant','')
> context['start_date'] = start_date = request.POST.get('start-date','')
> context['end_date'] = end_date = request.POST.get('end_date','')
> context['country'] = country = request.POST.get('country','')
> context['destination'] = destination = 
> request.POST.get('destination','')
> context['price'] = price = request.POST.get('price','')
> context['background_photo'] = background_photo = 
> request.POST.get('background-photo','')
> context['from_user'] = from_user = request.POST.get('from','')
> context['iteniary'] = iteniary = request.POST.get('iteniary','')
> context['days'] = days = request.POST.get('days','')
> context['destination'] = destination = 
> request.POST.get('destination','')
> context['property_name'] = property_name = 
> request.POST.get('property','')
> context['content'] = content = request.POST.get('content','')
> context['iteniary'] = iteniary = request.POST.get('iteniary','')
>
> #destinations and countries background photo created by not set
> brochure = Brochures(name=name, ref_id="xxx", adults=adults, 
> children=children, infant=infant,
> price=price, content=content, iteneary=iteniary)
> brochure.save()
>
> request.session['br_id'] = brochure.id
> return redirect('http://wilderness.maasaimara.com/generate/')
>
> return render_to_response(template_name, context, )
>
>
> def generate_pdf(request, br_id, num):
> context = RequestContext(request)
> list_of_pages = ["http://127.0.0.1:8000/page"+x+"/"; for x in 
> list("123456")]
> pdfs = ["page"+x+".pdf" for x in list("123456")]
> merger = PdfFileMerger()
> client = pdfcrowd.Client("samuel254", "86e62657536d264e8217478d56abd72e")
> br_id = response.session["br_id"]
> brochure = Brochures.objects.get(br_id)
>
> # set HTTP response headers
> response = HttpResponse(mimetype="application/pdf")
> response["Cache-Control"] = "max-age=0"
> response["Accept-Ranges"] = "none"
> response["Content-Disposition"] = "attachment; 
> filename=document-output.pdf"
>
> for num in list("123456"):
> path = 
> "/home/samuel/Documents/Documents/wilderness/wilderness/static/pdf/"
> html = 
> "http://wilderness.maasaimara.com/{1}/page{0}/".format(num,br_id)
> pdf = "page{0}.pdf".format(num)
> pdf_file = client.convertURI(html)
> local = open(pdf,'w')
> local.write(pdf_file)
> local.close()
> merger.append(open(pdf, 'r+b'))
>
> merger.write("document-output.pdf")
> response.write(merger)
> return response
>
> The urls.py
>
> from django.conf import settingsfrom django.conf.urls import patterns, 
> include, urlfrom django.conf.urls.static import staticfrom 
> django.views.generic import TemplateView
> from django.contrib import adminfrom views import generate_pdf,home
>
> urlpatterns = patterns("",
> url(r"^$", home, name="home"),
> url(r"^(?Pd{4})/page(?P[0-9]+)/", generate_pdf),
>
> url(r"^admin/", include(admin.site.urls)),
> url(r"^account/", include("account.urls")),)
>
> urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
>
> I need to confirm where the file is going, it's not crashing and returns 
> the document-output.pdf but it's blank.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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.goog

Re: i want to know how to use SlugField with slugify to generate url for detail_blog page without using get_absolute_url

2014-11-30 Thread Collin Anderson
Hi,

Is this what you're looking for?

{% url 'add_view' quotation.slug %}

Collin


On Thursday, November 27, 2014 4:26:49 PM UTC-5, Kanchan Prasad wrote:
>
> my model.py is
> class BlogPost(models.Model):
> title= models.CharField(max_length=100)
> text = models.TextField()
> created_on   = models.DateTimeField(auto_now_add=True,auto_now=False)
> updated_on   = models.DateTimeField(auto_now_add=False,auto_now=True)
> submitted_by = models.ForeignKey(User)
> slug = models.SlugField(max_length=100,unique=True)
> def __str__(self):
> return self.title
> def save(self, *args, **kwargs):
> if not self.id:
> self.slug = slugify(self.title)
> super(BlogPost,self).save(*args,**kwargs)
>
> urls.py
>
> url(r'^profile/latest-quotation/(?P[\w-]+)/$',add_view, 
> name='add_view'),
>
> views.py
> def add_view(request,slug):
> blog = get_object_or_404(BlogPost, slug=slug)
> com_form = CommentForm(request.POST or None)
> if com_form.is_valid():
> form = com_form.save(commit=False)
> form.blogpost = blog
> form.name = request.user
> form.save()
> return HttpResponseRedirect(reverse('socialnetwrok:add_view'))
> return 
> render(request,'socialnetwork/detailview.html',{'blog':blog,'com_form':com_form})
>
> my template where i am using it
> {% for quotation in latest_quotation_list %}
> 
> {{quotation.title}}
> 
> {{quotation.text|truncatewords:100}}
>
> please help me i need 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/d334838e-5b9f-4d2f-9b98-75c5a08265ae%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Simple Login Problem

2014-11-30 Thread Collin Anderson
Hi,

If you type your password wrong, user will be None, and your code will then 
redirect to the "register" page.

If you press "back" after a successful login, the CSRF token will be out of 
date and the form won't work.

Are you caching any pages?

Collin

On Friday, November 28, 2014 12:55:35 AM UTC-5, Rootz wrote:
>
> I have a django app but I having problems with my login views and logout 
> views. I do not have a html template designated to handle user login/logout 
> view.
> Django project is configured as follows:
>
> INSTALLED_APPS 
> 
>  setting:
>
>1. 'django.contrib.auth' contains the core of the authentication 
>framework, and its default models.
>2. 'django.contrib.contenttypes' is the Django *content type system* 
>, 
>which allows permissions to be associated with models you create.
>3. 'django.contrib.sessions',
>
>  MIDDLEWARE_CLASSES 
> 
>  setting:
>
>1. SessionMiddleware 
>
> 
> manages *sessions* 
> across 
>requests.
>2. AuthenticationMiddleware 
>
> 
>  associates 
>users with requests using sessions.
>3. csrf.CsrfViewMiddleware 
>
>
> Using Django Template Language and Template inheritance. The login form is 
> on the base template on other templates extends from this base template.
>
> All my login attempts result in some of the views rendering the user info 
> (username to welcome user back) while other views rendering the page as if 
> the user is an anonymous user. If I try to login in again I get an error 
> page stating that there is a missing csrf token or incorrect. Adding to 
> this I have identified many instances where I have tried to logout and it 
> does not seem to log me out because it is still showing the last user login 
> info. For my base template I have hard coded the form (meaning not using 
> Django Form class).
>
> Can You identify the possible fault in how i am implementing the login and 
> logout views?
>
>  
>  Here is a copy of my login and logout views
>
> def members_login(request):
>
> if request.method == 'POST':
> password = request.POST['password']
> username = request.POST['username']
> user = authenticate(username=username,password=password)
>
> if user is not None:
> if user.is_active:
> login(request,user)
> return redirect('members:index')
> else:
> #inactive users required to re-register
> return redirect('members:index')
> else:
> #no account required to register to create one
> return redirect('members:register')
> 
> else:
> #test if login is a regular get request then redirect
> return HttpResponseRedirect(reverse('members:index'))
>
>
> def members_logout(request):
> logout(request)
> return redirect('members:index')
>
>

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


simplifying double decorators?

2014-11-30 Thread Richard Brockie
Hi,

I'm running into the situation where I have several views with the same set
of decorators:

@login_required()
@user_passes_test(some_test_function, login_url='/',
redirect_field_name=None)
def some_view(request):
# some code
return render(request, 'some_template.html', locals())

How would I go about combining the two (or more) decorators into a single
decorator that can be used instead and retain the functionality?

IE: this:

@login_required()
@user_passes_test(some_test_function, login_url='/',
redirect_field_name=None)
def some_view...

becomes abstracted to something like this:

@my_custom_decorator_with_redirects()
def some_view...


-- 
R.

Richard Brockie



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


Re: Newbie help - running django-admin.py produces empty mysite folder

2014-11-30 Thread Collin Anderson
Hi,

Are there any error messages?

Is there already an existing mysite folder?

What method did you use to install django? Did you really install django 
1.8, not 1.7?

Collin


On Thursday, November 27, 2014 10:15:51 AM UTC-5, David Pride wrote:
>
> Title says it all really. Have just installed Django 1.8, can test django 
> version and get correct response so am *fairly* happy it's installed 
> correctly. I have had Python 2.7 installed and been using perfectly for 
> several months. 
>
> Altered the PATH variable as discussed so it points to correct directory. 
>
> However when I run...
>
> django-admin.py startproject mysite 
>
> The mysite folder is created - but it is empty, none of the following is 
> created...
>
> mysite/
> manage.py
> mysite/
> __init__.py
> settings.py
> urls.py
> wsgi.py
>
> All tips gratefully received!
>
> Many thanks, 
>
> D.P. 
>

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


Re: Newbie: How to implement a app/module, which I can include from my html?

2014-11-30 Thread Collin Anderson
Assignment tags are my favorite.

@register.assignment_tag
def get_categories():
return Category.objects.all()

{% get_categories as categories %}
{% for category in categories %}
{{ category }}
{% endfor %}

Collin


On Thursday, November 27, 2014 5:19:20 AM UTC-5, somecallitblues wrote:
>
>
> https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
>  
> here you go chief
> On 27/11/2014 8:04 pm, "ThomasTheDjangoFan"  > wrote:
>
>> Oh ok.
>>
>> so it would be something like:
>>
>> in home.html
>> {% include 'category-list.html' %}
>>
>> in category-lists.html
>> {% load those_categories %}
>> 
>>
>> ?
>>
>> Am Donnerstag, 27. November 2014 09:55:50 UTC+1 schrieb James Bennett:
>>>
>>> The usual way would be to write a custom template tag that fetches the 
>>> objects and puts them into the template context.
>>>
>>  -- 
>> You received this message because you are subscribed 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/d88ef650-0d18-4d6d-bad9-8a6a990524bf%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/9690882c-49da-4ee6-a01b-77270fbc7585%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Problem implementing django-sslserver

2014-11-30 Thread Collin Anderson
Hi,

A few things.

The stacktrace looks like it's getting gibberish. Maybe your cert and key 
don't match?

When I try, I can't get it to listen on a different port number. (It looks 
like you're trying to have it listen on 8020)

Why not have apache (or nginx) handle the SSL for you?

Collin


On Wednesday, November 26, 2014 1:07:52 PM UTC-5, pythonista wrote:
>
>
>
> The application was working successfully on the Linux server.
>
> I am trying to implement the ssl functionality and getting the  stack 
> trace below after following the instructions
>
> Any suggestions as to what is going on and how to fix this.
>
> We are running the dev server with a separate Apache server acting as a 
> proxy.
>
> The comnmand line is
>
> $ python manage.py runsslserver --certificate /path/to/certificate.crt --key 
> /path/to/key.key  ip_adress:8020
>
>
> Thanks
>
>  
>
> [26/Nov/2014 10:38:24] "GET /waitlist/ HTTP/1.1" 200 6341
> [26/Nov/2014 11:30:50] code 400, message Bad HTTP/0.9 request type 
> ('\x16\x03\x01\x00C\x01\x00\x00?\x03\x01Tv\x0eJ\xb2\xecd\x1f\xf5)\xd3\x8a\x9a4\xa5\x8c\xd3U;\x04C')
> Traceback (most recent call last):
>   File "/opt/python-2.7.8/lib/python2.7/SocketServer.py", line 595, in 
> process_request_thread
> self.finish_request(request, client_address)
>   File "/opt/python-2.7.8/lib/python2.7/SocketServer.py", line 334, in 
> finish_request
> self.RequestHandlerClass(request, client_address, self)
>   File 
> "/opt/python-2.7.8/lib/python2.7/site-packages/Django-1.7.1-py2.7.egg/django/core/servers/basehttp.py",
>  
> line 129, in __init__
> super(WSGIRequestHandler, self).__init__(*args, **kwargs)
>   File "/opt/python-2.7.8/lib/python2.7/SocketServer.py", line 651, in 
> __init__
> self.handle()
>   File "/opt/python-2.7.8/lib/python2.7/wsgiref/simple_server.py", line 
> 117, in handle
> if not self.parse_request(): # An error code has been sent, just exit
>   File "/opt/python-2.7.8/lib/python2.7/BaseHTTPServer.py", line 281, in 
> parse_request
> "Bad HTTP/0.9 request type (%r)" % command)
>   File "/opt/python-2.7.8/lib/python2.7/BaseHTTPServer.py", line 368, in 
> send_error
> self.send_response(code, message)
>   File "/opt/python-2.7.8/lib/python2.7/BaseHTTPServer.py", line 385, in 
> send_response
> self.log_request(code)
>   File "/opt/python-2.7.8/lib/python2.7/BaseHTTPServer.py", line 422, in 
> log_request
> self.requestline, str(code), str(size))
>   File 
> "/opt/python-2.7.8/lib/python2.7/site-packages/Django-1.7.1-py2.7.egg/django/core/servers/basehttp.py",
>  
> line 136, in log_message
> msg = "[%s] %s\n" % (self.log_date_time_string(), format % args)
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb2 in position 16: 
> ordinal not in range(128)
>
>
>

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


Re: Python: Assign variable in if statement?

2014-11-30 Thread Masklinn

On 2014-11-30, at 12:30 , ThomasTheDjangoFan 
 wrote:

> Hi guys,
> 
> coming from php I am wondering if there is a way to do something like this in 
> Python/Django:
> 
> if variable = get_a_value_from_function():
>   new_stuff = variable
> 
> Of course I can use
> 
> variable = get_a_value_from_function()
> if variable:
>   new_stuff = variable
> 
> But is there a shortcut similar to php?

Not as such. Python intentionally didn't include assignment within
statements (mostly conditionals) to avoid the common issue of
assignments-instead-of-equality bugs.

If `new_stuff` has a default value, you could always write.

new_stuff = some_function() or new_stuff

which will reassign `new_stuff` to itself if `some_function()` returns a
falsy value. If you need a more complex conditional body than just an
assignment, you'll need the long one.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/E49110AF-E68A-43C6-8E29-11618328B2BD%40masklinn.net.
For more options, visit https://groups.google.com/d/optout.


Re: Python: Assign variable in if statement?

2014-11-30 Thread Marc Aymerich
On Sun, Nov 30, 2014 at 12:30 PM, ThomasTheDjangoFan
 wrote:
> Hi guys,
>
> coming from php I am wondering if there is a way to do something like this
> in Python/Django:
>
> if variable = get_a_value_from_function():
>   new_stuff = variable
>
> Of course I can use
>
> variable = get_a_value_from_function()
> if variable:
>   new_stuff = variable
>
> But is there a shortcut similar to php?

perhaps something like:

new_stuff = get_a_value_from_function() or get_a_value_from_other_function()


-- 
Marc

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


Python: Assign variable in if statement?

2014-11-30 Thread ThomasTheDjangoFan
Hi guys,

coming from php I am wondering if there is a way to do something like this 
in Python/Django:

if variable = get_a_value_from_function():
  new_stuff = variable

Of course I can use

variable = get_a_value_from_function()
if variable:
  new_stuff = variable

But is there a shortcut similar to php?

Kind regards
Thomas

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