Re: django.contrib.auth.update_session_auth_hash not working after change password

2024-11-06 Thread Ken BHHO
@cseb Where did you get that Django Code?

On Wed, 6 Nov 2024 at 15:07, Ruby  wrote:

> Your code needs to be refactored, here is the real deal, your
> ChangePassowrdFrom is missing `request`, it should be as it is below
> form = grandmas4hire.forms.ChangePasswordForm(request, request.POST)
>
>
> On Wed, Nov 6, 2024 at 8:20 PM cseb...@gmail.com 
> wrote:
>
>> Ruby
>>
>> Thank you very much.  Here is my code...
>>
>>
>> INV= grandmas4hire.models.Invitation
>>
>> ...
>>
>> def add_url_param(url, param, arg):
>>
>> prefix = "&" if "?" in url else "/?"
>>
>>
>>
>> return url + prefix + f'{param}={str(arg).replace(" ", "+")}'
>>
>>
>> ---
>>
>> @django.contrib.auth.decorators.login_required
>>
>> def change_password(request):
>>
>> user = request.user
>>
>> msg  = request.GET.get("msg")
>>
>> if request.method == "POST":
>>
>> form =
>> grandmas4hire.forms.ChangePasswordForm(request.POST)
>> if form.is_valid():
>>
>> new_password = form.cleaned_data["new_password"]
>>
>> inv  = INV.objects.get(user = user)
>>
>> inv.user.set_password(new_password)
>>
>> inv.user.save()
>>
>>
>> django.contrib.auth.update_session_auth_hash(request,
>>
>>  user)
>> url  = add_url_param("/change_password",
>>
>>  "msg",
>>
>>  "Password+changed.")
>>
>> reply= django.shortcuts.redirect(url)
>>
>> else:
>>
>> reply = django.shortcuts.render(request,
>>
>>
>> "change_password.html",
>> {"form" : form})
>>
>> else:
>>
>> form  = grandmas4hire.forms.ChangePasswordForm()
>>
>> reply = django.shortcuts.render(request,
>>
>> "change_password.html",
>>
>> {"form" : form,
>>
>>  "msg"  : msg})
>>
>>
>>
>> return reply
>>
>> On Tuesday, November 5, 2024 at 5:41:09 PM UTC-6 Ruby wrote:
>>
>>> How was it implemented?
>>> Show a snippet from your code
>>> See how it was used in my code
>>>
>>> form = ChangePasswordForm(request, request.POST)
>>> if form.is_valid():
>>> user = form.save()
>>> update_session_auth_hash(request, user)
>>> messages.success(
>>> request, "Your password has been successfully updated")
>>> return redirect(request.META.get('HTTP_REFERER'))
>>>
>>> On Tue, Nov 5, 2024 at 10:30 PM cseb...@gmail.com 
>>> wrote:
>>>
 When I change a password, users are logged out.
 Django recommends keeping users logged in
 by calling django.contrib.auth.update_session_auth_hash(request, user).

 This is not working in a Django website of mine.
 They must log in again!?

 There are no error messages.  Is there any way I can provide
 more details?

 Chris

 --
 You received this message because you are subscribed 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 view this discussion visit
 https://groups.google.com/d/msgid/django-users/04908d1c-a1e4-41ea-afd8-e227f78af8bcn%40googlegroups.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 view this discussion visit
>> https://groups.google.com/d/msgid/django-users/0c0c2c50-5064-4e9d-a579-f0ddb323c11an%40googlegroups.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 view this discussion visit
> https://groups.google.com/d/msgid/django-users/CAPUD46tCgtE4bK6yrrZ18FuxE4oTsvkda%2BLG2S8Fz14pxrkb%3DA%40mail.gmail.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...@goog

Re: group

2022-09-28 Thread Ken Booo
Plss add me in the official group of django pls.  I am having 2+ yrs 0f exp
.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAGiSraC%2BodGj_MKqfegUugKSo4Bmv81ActyZx-gziSdZnt4SdA%40mail.gmail.com.


Bug Request!

2022-07-25 Thread Ken Booo
Here, I caught a one bug on Django-->4.0.6
There is no argumented support and base_dir is having exemptions causing
warnings![image: WhatsApp Image 2022-07-18 at 11.59.01 AM.jpeg]

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAGiSraCtPC2oHsXL2EDy%3DhXFFt_4bPDpHrFz0RR-UzJb0wZmRQ%40mail.gmail.com.


Re: Desperately need help.

2021-06-16 Thread Ken Smith
Thank you very much they are very much aware that there is a problem with
that page and and they seemed not be able to fix it for a week's now. I
have contacted them time and time again about it. Actually I am beginning
to think that they have at that way on purpose of that they don't have to
pay out  Is there customers money they just keep getting it in. I take
rather that they might be very unscrupulous. Thank you for your input have
a great day

On Wed, Jun 16, 2021, 1:02 PM Krish M  wrote:

> Ken,
>
> Base on what you're asking, and from the source code (view-source) &
> screenshot, I don't think you have access to the right code to make the fix.
>
> Maybe contacting safewayfx.com and letting them know their platform has a
> bug?
>
> If they are unwilling to fix their backend bug, then there is nothing us
> here can help with.
>
> I am assuming, if you have access to the backend code (Python, Django) you
> should hire someone to fix that bug for you, you can point them to Jul
> response.
>
> On Tuesday, June 15, 2021 at 10:45:05 PM UTC-4 Nikeet NA wrote:
>
>>
>> In your withdraw view you have return render this should be missing check
>> inside if statements or inside your custom logic which you have written
>> without seeing the actual code its hard to tell.
>>
>> On Wednesday, 16 June 2021 at 03:14:26 UTC+5:30 Ken Smith wrote:
>>
>>> jul, thank you so very much for your very simple and honest answer. This
>>> was the best response I could have ever received from anyone and I
>>> appreciate it. I'm getting a bit old at 66 it seems my brain doesn't work
>>> as good as it did even 10 years ago for learning something as difficult as
>>> coding. Although your suggestion makes good sense and holds merit. I do
>>> thank you for your response. I only ask one more simple thing can you tell
>>> me which line of the code the HTTP response is missing from.
>>>
>>> Your answer has really opened up my brain to the possibility that the
>>> website has left that out on purpose so that members cannot withdraw their
>>> money.
>>>
>>> Again thank you so very much for your response and have a wonderful day
>>> On Tuesday, June 15, 2021 at 5:39:54 PM UTC-4 jul.ale...@gmail.com
>>> wrote:
>>>
>>>> Pretty easy to be honest. The web page need an http response and it's
>>>> give none instead. :)
>>>>
>>>>
>>>> If you don't know about the code, maybe you should hire a developer or
>>>> learn by yourself.
>>>>
>>>> El mar., 15 de junio de 2021 3:14 p. m., Ken Smith 
>>>> escribió:
>>>>
>>>>> There is the issue to solve that is the result of pressing the button
>>>>> to complete your transaction. And it may be dumb because I don't know a
>>>>> damn thing about  django and I assume that I would get an intelligent
>>>>> response on this forum.  This was in fact a sincere request because I know
>>>>> nothing about this code. If I did I would've discovered it myself. I 
>>>>> merely
>>>>> had the stupid assumption that someone would actually consider this a
>>>>> challenge. But apparently not even your up to a challenge maybe it's too
>>>>> hard for you. That is coded in django as I understand I may be wrong. I
>>>>> only read what was presented on the error page. If it's not that would you
>>>>> please direct me to what code it could possibly be as I am not a coder in
>>>>> any way shape or form. I stopped even trying long before these new methods
>>>>> of coding came out. I think the last time I tried to write code was in the
>>>>> 1990s. I know there is a solution to my question I just hope there is
>>>>> someone with the intelligence to take on the challenge for me or at least
>>>>> direct me to where I need to go instead of making jokes. Perhaps someone
>>>>> can tell me something about where I need to go or what I need to do there
>>>>> is a lot of money involved in getting this code correct so that I can send
>>>>> the corrected information to the company who owns the webpage. Not
>>>>> everybody here knows how to code some of us are actually wanting some
>>>>> answers to questions that we have. I am by trade an aircraft mechanic. So 
>>>>> I
>>>>> can laugh at you if I asked you to go clean the air sock and you don't 
>>>>> even
>>>>>

Re: Desperately need help.

2021-06-15 Thread Ken Smith
jul, thank you so very much for your very simple and honest answer. This 
was the best response I could have ever received from anyone and I 
appreciate it. I'm getting a bit old at 66 it seems my brain doesn't work 
as good as it did even 10 years ago for learning something as difficult as 
coding. Although your suggestion makes good sense and holds merit. I do 
thank you for your response. I only ask one more simple thing can you tell 
me which line of the code the HTTP response is missing from.

Your answer has really opened up my brain to the possibility that the 
website has left that out on purpose so that members cannot withdraw their 
money.

Again thank you so very much for your response and have a wonderful day
On Tuesday, June 15, 2021 at 5:39:54 PM UTC-4 jul.ale...@gmail.com wrote:

> Pretty easy to be honest. The web page need an http response and it's give 
> none instead. :) 
>
>
> If you don't know about the code, maybe you should hire a developer or 
> learn by yourself. 
>
> El mar., 15 de junio de 2021 3:14 p. m., Ken Smith  
> escribió:
>
>> There is the issue to solve that is the result of pressing the button to 
>> complete your transaction. And it may be dumb because I don't know a damn 
>> thing about  django and I assume that I would get an intelligent response 
>> on this forum.  This was in fact a sincere request because I know nothing 
>> about this code. If I did I would've discovered it myself. I merely had the 
>> stupid assumption that someone would actually consider this a challenge. 
>> But apparently not even your up to a challenge maybe it's too hard for you. 
>> That is coded in django as I understand I may be wrong. I only read what 
>> was presented on the error page. If it's not that would you please direct 
>> me to what code it could possibly be as I am not a coder in any way shape 
>> or form. I stopped even trying long before these new methods of coding came 
>> out. I think the last time I tried to write code was in the 1990s. I know 
>> there is a solution to my question I just hope there is someone with the 
>> intelligence to take on the challenge for me or at least direct me to where 
>> I need to go instead of making jokes. Perhaps someone can tell me something 
>> about where I need to go or what I need to do there is a lot of money 
>> involved in getting this code correct so that I can send the corrected 
>> information to the company who owns the webpage. Not everybody here knows 
>> how to code some of us are actually wanting some answers to questions that 
>> we have. I am by trade an aircraft mechanic. So I can laugh at you if I 
>> asked you to go clean the air sock and you don't even know what I'm talking 
>> about but I won't because you don't know what I'm talking about. Neither do 
>> I know anything about what I presented and I don't pretend to know that's 
>> why I asked for some intelligent information. Have a good day regards Ken
>> On Monday, June 14, 2021 at 5:21:42 PM UTC-4 jacobgr...@gmail.com wrote:
>>
>>> Lol what do you expect anyone to do? You just post some random HTML, 
>>> zero code, no backtrace, nothing to even indicate there is an issue that 
>>> someone could solve even IF they were willing... This has nothing to do 
>>> with Django. I don't understand what you thought was going to happen. This 
>>> is possibly the dumbest "question" I have ever read. I'd be willing to 
>>> consult at double my normal hourly rate if you are the point of contact. 
>>>
>>> On Mon, Jun 14, 2021 at 12:12 PM Kasper Laudrup  
>>> wrote:
>>>
>>>> On 14/06/2021 05.15, Ken Smith wrote:
>>>> > I sure hope that somebody can take the time to do this. I'm just
>>>> > wondering one of you brilliant programmers can look at this webpage 
>>>> and
>>>> > tell me where the errors are so that it can be fixed? Apparently the
>>>> > programmers at the website are not as smart as you people are. If
>>>> > someone has the time and inclination to do so with a please go over 
>>>> the
>>>> > code and highlight where the errors are in the corrections necessary 
>>>> in
>>>> > send back to me in a file in response. I would greatly be so happy.
>>>> > Thank you and have a wonderful day.
>>>> > 
>>>>
>>>> Instead of wasting space on meaningless flattering of the very diverse
>>>> members of this list/forum and begin rude to the developers at
>>>> safewayfx.com you would hav

Re: Desperately need help.

2021-06-15 Thread Ken Smith
Kasper, I am not sure of anything at this point. As for the denigrating of 
the Safeway programmers this has been going on for quite some time and I 
have money in that account that I am unable to withdraw because the failure 
of the page for withdrawal. And no I'm not sure of anything about 
permissions or anything else I just thought that this would be the place to 
ask if someone could provide the corrections so that I could send that to 
the company and have been directed to their programmers and maybe this 
might actually get things going so that I can withdraw my funds from their. 
As for flattery certainly most of the members of this former way smarter 
than I am in this area as I know nothing about the coding that you are 
involved in. It was not flattery it was merely a statement of fact. If you 
want to know how to fix airplanes you come to me as I have over 40 years 
experience in it. However I know nothing about code anymore it is been more 
than two decades since I even tried to code. And I'm/very aware that things 
are greatly changed since then. From the response of another member here 
I'm not even sure if the code is in django. It was merely mentioned on the 
error page that was presented. If you'll read my most recent post you will 
see the error page and why I got that assumption. I merely wish to be able 
to withdraw my money from the website and anything I can do to help their 
coders to do the job would be worth it to me. As I said to other members I 
presented this hoping that someone might be interested in taking up the 
challenge but is as of yet no one on this forum appears to be up to the 
challenge.

It would be appreciative if anyone here could direct me to somebody who 
could actually help me with this so that I can present the corrected 
information to the company so that they may make the corrections necessary 
and have the page work. One thing I do remember from code it can be very 
difficult and mistakes can be made on a simple thing that can cause 
everything not to work. That's why collaboration is often very important 
when things don't work. As you probably well know.

Have a wonderful day
On Monday, June 14, 2021 at 1:13:18 PM UTC-4 Kasper Laudrup wrote:

> On 14/06/2021 05.15, Ken Smith wrote:
> > I sure hope that somebody can take the time to do this. I'm just
> > wondering one of you brilliant programmers can look at this webpage and
> > tell me where the errors are so that it can be fixed? Apparently the
> > programmers at the website are not as smart as you people are. If
> > someone has the time and inclination to do so with a please go over the
> > code and highlight where the errors are in the corrections necessary in
> > send back to me in a file in response. I would greatly be so happy.
> > Thank you and have a wonderful day.
> > 
>
> Instead of wasting space on meaningless flattering of the very diverse
> members of this list/forum and begin rude to the developers at
> safewayfx.com you would have a much better chance of getting help if you
> instead showed that you were willing to do at least a minimal effort
> yourself.
>
> What errors are you talking about and what have you done to try and
> solve them?
>
> Just attaching and HTML file and expecting people to fix errors you
> cannot even bother to point out is not gonna get you much positive 
> feedback.
>
> Also, how is this related to Django at all?
>
> Finally, are you sure that safewayfx.com is OK with you sharing their
> copyrighted works without their acceptance?
>
> Kind regards,
>
> Kasper Laudrup
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/01860dc4-d4ea-47d4-88a3-9d4683ed7fefn%40googlegroups.com.


Re: need to support anonymous users with a simple one time disclaimer agreement

2019-08-04 Thread Ken Whitesell
Gregory,

 Not only is it not practical in Django, it's not a realistic solution 
using any framework. 

There is no "machine ID" that is exposed to a web site, and originating IP 
addresses completely fails for all people accessing your site from behind a 
NAT box or other similar functional device. (I work in an office using a 
private ip address range - 10.1.xxx.xxx. All websites that any of us access 
all see the same originating IP address. So if I were to acknowledge that 
disclaimer, your software would assume that everyone in my office has done 
that - which I don't think you want.)

Yes, there are some options that would cover most of the common cases - you 
could use a cookie for example, to track on the user's side whether or not 
they've agreed to that disclaimer. That'll work for as long as they keep 
the cookies and don't change browsers - or run in incognito mode.

(And all of this is discounting any intentional actions to spoof / avoid 
that disclaimer.)

If you have any _real_ requirement for that disclaimer to be acknowledged, 
then an actual per-user account is the only way to do it.

Ken



On Saturday, August 3, 2019 at 10:08:35 AM UTC-4, Gregory Hines wrote:
>
> I am an experienced software developer but new to django.  I am trying to 
> create a simple website in which each new user (either based on their IP 
> address or even more specific machine ID) would be asked to agree to a 
> simple disclaimer before going on to access the site. On subsequent usage I 
> don't want them to be offered the same disclaimer and repeat user should be 
> sent directly to the main page of the website.
>
> I am using TemplateViews  and  basic templates that offer up form that the 
> user fills and submits.  I specifically don't want each user to have to 
> establish a ogin acct etc.  Is this possible w/ django? 
>
> Any and all hints welcome.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/672dfc54-5b11-4bc9-b7f5-f44d68452b83%40googlegroups.com.


Re: How to use permissions on a CreateView class?

2019-05-29 Thread Ken Whitesell
Fellipe,

In addition to the permissions_required variable, I believe you also need 
to include the PermissionsRequired mixin in your class definition:

https://docs.djangoproject.com/en/2.2/topics/auth/default/#the-permissionrequiredmixin-mixin

Ken

On Tuesday, May 28, 2019 at 5:54:39 PM UTC-4, Fellipe Henrique wrote:
>
> Hi Jim, 
>
> Tried that, as you can see on my code, but not working.. when user type 
> the url, still see the template..
>
> Any suggestions?
>
> Regards,
>
> T.·.F.·.A.·. S+F
> *Fellipe Henrique P. Soares*
>
> e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 
> 's/(.)/chr(ord($1)-2*3)/ge'
> *Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh 
> <https://fedoraproject.org/wiki/User:Fellipeh>*
> *Blog: *http:www.fellipeh.eti.br
> *GitHub: https://github.com/fellipeh <https://github.com/fellipeh>*
> *Twitter: @fh_bash*
>
>
> On Tue, May 28, 2019 at 2:36 PM Jim Illback  > wrote:
>
>> I think you can also add to your class (right under your *template_name*… 
>> for example) this statement: 
>>
>>  permission_required = *‘*appname.permission_name'
>>
>> This will limit to logged on users (as below), and also to users who possess 
>> this permission.
>>
>> Jim
>>
>>
>> On May 28, 2019, at 9:55 AM, Joe Reitman > > wrote:
>>
>> Fellipe, 
>>
>> Here is an example of decorating class based views from the documentation 
>> <https://docs.djangoproject.com/en/2.2/topics/class-based-views/intro/#decorating-class-based-views>
>> :
>>
>> from django.contrib.auth.decorators import login_requiredfrom 
>> django.utils.decorators import method_decoratorfrom django.views.generic 
>> import TemplateView
>> class ProtectedView(TemplateView):
>> template_name = 'secret.html'
>>
>> @method_decorator(login_required)
>> def dispatch(self, *args, **kwargs):
>> return super().dispatch(*args, **kwargs)
>>
>>
>> On Tuesday, May 28, 2019 at 6:54:38 AM UTC-5, Fellipe Henrique wrote: 
>>>
>>> Hello, 
>>>
>>> I have these class, based on CreateView class... and I only want allow 
>>> user with these permissions to add record...
>>>
>>> class ClienteCreateView(ERPbrViewMixin, CreateView):
>>> template_name = 'cadastro/cliente/form.html'
>>> permission_required = ('cliente.can_open', 'cliente.can_edit', 
>>> 'cliente.can_add')
>>> model = Cliente
>>> form_class = ClienteForm
>>>
>>> But, not working... user without these permission, when type the url 
>>> show the form...
>>>
>>> Any tips how to do that?
>>>
>>> Cheers!
>>>
>>>
>>> T.·.F.·.A.·. S+F
>>> *Fellipe Henrique P. Soares*
>>>
>>> e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 
>>> 's/(.)/chr(ord($1)-2*3)/ge'
>>> *Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh 
>>> <https://fedoraproject.org/wiki/User:Fellipeh>*
>>> *Blog: *http:www.fellipeh.eti.br <http://www.fellipeh.eti.br/>
>>> *GitHub: https://github.com/fellipeh <https://github.com/fellipeh>*
>>> *Twitter: @fh_bash*
>>>
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django...@googlegroups.com .
>> To post to this group, send email to djang...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/060a2c59-bf39-456c-a686-bf6ba104e1f7%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/060a2c59-bf39-456c-a686-bf6ba104e1f7%40googlegroups.com?utm_medium=email&utm_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...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/B5E64E45-C1C3-455F-AEC7-167852FE17C7%40hotmail.com
>>  
>> <https://groups.google.com/d/msgid/django-users/B5E64E45-C1C3-455F-AEC7-167852FE17C7%40hotmail.com?utm_medium=email&utm_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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/807b9db0-7dcd-4c42-b1e0-430655352056%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: how handle high incoming data and sending throttled data to web sockets in django-channels

2019-01-15 Thread Ken Whitesell
We deal with a similar rate of data acquisition, and have taken a different 
approach. (We get, on average, about 10,000,000 UDP messages / day)

We have a very small UDP listener (about 50 lines of Python 3 code), and 
_all_ it does is receive the message and dump it into a Celery queue. We 
then run multiple Celery worker tasks to process that data and write it to 
the database.

There are some times during peak period in the day where the queue might 
get backed up 1,000,000 messages or so, but we never have any problems 
getting them all processed that day. (UDP packets effectively stops around 
9 PM.)

We may be losing some packets - with UDP, how can you tell? But the numbers 
of packets processed are well within 95% of projections, and so for our 
purposes it's quite satisfactory.
(There is absolutely no way for us to determine if some upstream device is 
being saturated and dropping packets that we should otherwise be receiving. 
Or more accurately, how many packets are being dropped upstream from our 
collection point. UDP is definitely not the protocol to be using if you 
absolutely need to receive 100% of your data.)

On Monday, January 14, 2019 at 9:31:21 AM UTC-5, Sahil Mangotra wrote:
>
> I am facing a problem in my django web server.
>
> We are using python3, django2, django-rest-framework3.8 and channels2.x
>
> Scenario is we are receiving DATA from a UDP connection at very fast rate 
> (~100 messages per second). The data revived is in proto format (you can 
> say we are receiving byte data). some data gets starved in this process as 
> *Rate 
> of production >>> rate of consumption* we are implementing throttling but 
> still at 100 concurrent users data starves again. Can anyone help us in 
> this scenario.
>
> If anyone has any new architecture idea please share.
>
> *This is surely an interesting problem. This is about stock market feed*
>
> PS :- I cannot post any code as it is my companies. but i can help any 
> time you need clarification on any point.
>

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


Re: Nullable vs empty strings

2018-05-03 Thread Ken Whitesell
Nick,

 A null string (string with length 0) is _not_ the same as a null field 
(no string). The two are distinct, and (can) serve two very different 
functions. 

Take a look at this for some more detailed 
information: 
https://softwareengineering.stackexchange.com/questions/32578/sql-empty-string-vs-null-value

Ken


On Thursday, May 3, 2018 at 5:17:35 AM UTC-4, Nick Sarbicki wrote:
>
> I just saw this in the docs: 
> https://docs.djangoproject.com/en/2.0/ref/models/fields/#null
>
> Suggesting that you should never set a CharField to null unless using a 
> unique index.
>
> Is this generally accepted? Historically I've always nulled a CharField 
> because using empty strings, as opposed to letting a column be nullable, 
> has felt very dirty to me.
>
> I would have expected (not suggesting this as a change) an empty string to 
> fail if the field isn't nullable.
>
> Am I on my own here?
>

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


Re: Multiple websocket connection vs single websocket connection when using django channels

2018-04-06 Thread Ken Whitesell
Hi Robin,

I can't speak to any generalized situations, or what might be considered 
"best practices" or most optimal.

What I can say is that we have gone with the single websocket connection 
for each client - whether it's a real person at a browser or an 
application. All our communications through the channel are JSON objects, 
and we include a key named "app" in the object which identifies the 
specific "feature" or "application" to which a message is directed. It's 
done in both directions - submissions through the channel from the browsers 
to the server and from the server to the browser all have that key in the 
JSON. 

About the most I can say is that it works well for us. 

Ken

On Friday, April 6, 2018 at 5:10:41 AM UTC-4, Robin Lery wrote:
>
> Hi,
>
> Suppose an application has features like Chat, Notification and Activity 
> feeds. 
>
> I would like to know whether its recommended to have different   websocket 
> connection for different  feautues for each user. Meaning for chat purpose 
> a separate socket connection, for notification another separate connection?
>
> Or is it better to have only one websocket connection for a user, and work 
> around that single connection for different features?
>
> Sincerely,
> Robin 
>

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


Re: How to run an external command that must run with the server

2018-04-03 Thread Ken Whitesell
There's an aspect of your situation which isn't entirely clear to me - is this 
management command one that remains running all the time, like a Celery task 
would be; or is it one that starts, runs a process for a period of time, and 
then ends - only to be restarted at a later time? If the former, then yes, 
running the management command from supervisor makes sense to me. If the 
latter, then I'd probably be looking at doing something different.


Ken


> On April 3, 2018 at 6:15 AM 'Alex' via Django users 
>  wrote:
> 
> That makes sense. So leave the source as a management command (as it is 
> now), and just run python manage.py source through supervisor?
> 
> 
> On Sunday, 1 April 2018 13:16:38 UTC+1, Ken Whitesell wrote:
> 
> > > We set up all our Django-related processes as a group 
> under supervisor. This includes our celery-based processes. (We have some 
> long-running tasks that are kicked off by the web site.) By setting it up as 
> a group, we can manage all the different processes as a set.
> > 
> > Whether or not that's the "best" way is possibly debatable. But it 
> > works for us and doesn't give us any problems.
> > 
> > Ken
> > 
> > On 4/1/2018 7:06 AM, 'Alex' via Django users wrote:
> > 
> > > > > I have a daphne server running a django 
> > channels application. I also have a python script that aggregates data from 
> > various sources, and sticks it into the channel layer (called source.py). 
> > At the moment, I run it as a management command (python manage.py source). 
> > It is nearly time for deployment(!), so I'm moving towards production 
> > solutions. Daphne itself currently runs under supervisor.
> > > 
> > > My question is, what is the best way to run source.py? As a 
> > > management command, also under supervisor? Using celery? In some other 
> > > way? Since source.py feeds into the channel layer, it needs access to 
> > > settings.py in order to identify the details of the channel layer etc.
> > > --
> > > You received this message because you are subscribed to the 
> > > Google Groups "Django users" group.
> > > To unsubscribe from this group and stop receiving emails from 
> > > it, send an email to django-users...@googlegroups.com.
> > > To post to this group, send email to 
> > > django...@googlegroups.com.
> > > Visit this group at 
> > > https://groups.google.com/group/django-users 
> > > https://groups.google.com/group/django-users .
> > > To view this discussion on the web visit 
> > > https://groups.google.com/d/msgid/django-users/b3c22939-b520-4c9c-90f9-ef8cb7b8c661%40googlegroups.com
> > >  
> > > https://groups.google.com/d/msgid/django-users/b3c22939-b520-4c9c-90f9-ef8cb7b8c661%40googlegroups.com?utm_medium=email&utm_source=footer
> > >  .
> > > For more options, visit https://groups.google.com/d/optout 
> > > 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 
> mailto:django-users+unsubscr...@googlegroups.com .
> To post to this group, send email to django-users@googlegroups.com 
> mailto:django-users@googlegroups.com .
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/432d449c-d089-43cd-a739-702847729b6b%40googlegroups.com
>  
> https://groups.google.com/d/msgid/django-users/432d449c-d089-43cd-a739-702847729b6b%40googlegroups.com?utm_medium=email&utm_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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2038894656.742154.1522760902201%40connect.xfinity.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to run an external command that must run with the server

2018-04-01 Thread Ken Whitesell
We set up all our Django-related processes as a group under supervisor. 
This includes our celery-based processes. (We have some long-running 
tasks that are kicked off by the web site.) By setting it up as a group, 
we can manage all the different processes as a set.


Whether or not that's the "best" way is possibly debatable. But it works 
for us and doesn't give us any problems.


Ken

On 4/1/2018 7:06 AM, 'Alex' via Django users wrote:
I have a daphne server running a django channels application. I also 
have a python script that aggregates data from various sources, and 
sticks it into the channel layer (called source.py). At the moment, I 
run it as a management command (python manage.py source). It is nearly 
time for deployment(!), so I'm moving towards production solutions. 
Daphne itself currently runs under supervisor.


My question is, what is the best way to run source.py? As a management 
command, also under supervisor? Using celery? In some other way? Since 
source.py feeds into the channel layer, it needs access to settings.py 
in order to identify the details of the channel layer etc.

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

Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b3c22939-b520-4c9c-90f9-ef8cb7b8c661%40googlegroups.com 
<https://groups.google.com/d/msgid/django-users/b3c22939-b520-4c9c-90f9-ef8cb7b8c661%40googlegroups.com?utm_medium=email&utm_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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b3acf9a3-41e9-08ee-1180-80fb5bc346d0%40comcast.net.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.0.2, Channels 2.0.2 and Celery 4.1 Issue

2018-03-02 Thread Ken Whitesell
Taking a stab at this - I believe the original problem may be here:
channel_layer.group_send(
settings.CHANNEL_GROUP,
{"type": "epics.message", "text": "Hello World"},
)

Your updateData method is a synchronous method. However, 
channel_layer.group_send is an asynchronous method.

What you might try is wrapping the group_send method in the async_to_sync 
function.
See the documentation at 
http://channels.readthedocs.io/en/latest/topics/channel_layers.html#synchronous-functions

async_to_sync(channel_layer.group_send)(
settings.CHANNEL_GROUP,
{"type": "epics.message", "text": "Hello World"},
)


Your first solution to make updateData an asynchronous method might work 
with some other work involved in adding that task to the event loop - but 
that answer is beyond me at the moment.

Hope this helps,
 Ken


On Friday, March 2, 2018 at 1:36:08 PM UTC-5, G Broten wrote:
>
> Hi All:
>  I'm migrating a small application from Django 1.x/Channels 1.x to Django 
> 2.0.2 and Channels 2.0. I've run into an issue whose cause I'm trying to 
> determine. It could be due to a failure on my part to correctly implement 
> the channel_layer or it could be due to an
> incompatibility with Celery 4.1. The basics are:
> - Run a periodic Celery task
> - Use the channel_layer to perform a group_send
> - Have the consumer receive the group_send event and push a json  message 
> over the socket
>
> Show below is my simple consumer.py module:
> class mstatusMessage(AsyncJsonWebsocketConsumer):
>
> # WebSocket event handlers
>
> async def connect(self):
> """
> Called when the websocket is handshaking as part of initial 
> connection.
> """
> logging.info("### Connected ###")
> # Accept the connection
> await self.accept()
>
> # Add to the group so they get messages
> await self.channel_layer.group_add(
> settings.CHANNEL_GROUP,
> self.channel_name,
> )
>
> async def disconnect(self, code):
> """
> Called when the WebSocket closes for any reason.
> """
> # Remove them from the group
> await self.channel_layer.group_discard(
> settings.CHANNEL_GROUP,
> self.channel_name,
> )
>
> # Handlers for messages sent over the channel layer
>
> # These helper methods are named by the types we send - so epics.join 
> becomes epics_join
> async def epics_message(self, event):
> """
> Called when the Celery task queries Epics.
> """
> logging.error("### Received Msg ###")
> # Send a message down to the client
> await self.send_json(
> {
> "text": event["message"],
> },
> )
>
> The routing is simple:
> application = ProtocolTypeRouter({
> "websocket":  mstatusMessage
> })
>
> The Celery task is as follows:
> @shared_task
> def updateData(param):
>
> logger.error('# updateData #')
>
> # # Get an instance of the channel layer for
> # # inter task communications
> channel_layer = get_channel_layer()
>
> channel_layer.group_send(
> settings.CHANNEL_GROUP,
> {"type": "epics.message", "text": "Hello World"},
> )
>
> The results are promising as the websocket connect opens successfully and 
> the Celery task run as show by the debugging output given below:
> 127.0.0.1:59818 - - [02/Mar/2018:09:32:11] "GET /" 200 100639
> 127.0.0.1:59844 - - [02/Mar/2018:09:32:12] "WSCONNECTING /epics/" - -
> 2018-03-02 09:32:12,280 INFO ### Connected ###
> 127.0.0.1:59844 - - [02/Mar/2018:09:32:12] "WSCONNECT /epics/" - -
> [2018-03-02 09:32:12,312: ERROR/ForkPoolWorker-2] 
> mstatus.tasks.updateData[8d329e61-]: # updateData #
> [2018-03-02 09:32:13,310: ERROR/ForkPoolWorker-2] 
> mstatus.tasks.updateData[786f51a6-]: # updateData #
>
> BUT ... although the Celery task runs the consumer never 
> receives a message via the channel layer. This could be due to an
> implementation error or, maybe, a compatibility issue. The application 
> doesn't crash but the following warning is issued:
>
> [2018-03-02 09:32:02,105: WARNING/ForkPoolWorker-2] 
> /mstatus/mstatus/tasks.py:33: RuntimeWarning: coroutine 
> 'RedisChannelLayer.group_send' was ne

Re: Channels 2.0 - Exception when sending a message to client

2018-02-25 Thread Ken Whitesell
And while we're at it, I'm going to toss out another opinion.

I've found it extremely beneficial _for me_ to not try to relate channels 
2.0 to channels 1.1. I'm approaching it as if I'm learning about a 
completely separate package - working from a clean slate so-to-speak.

Ken

On Sunday, February 25, 2018 at 5:04:13 AM UTC-5, muha...@swordfish.co.za 
wrote:
>
> While I'm at it, would you mind confirming if I understand the following 
> changes in channels 2.0 correctly ?
>
> 1) Channel names are not auto-detected and must be specified when running 
> a worker
> 2) *runserver* no long starts up a worker by default, this has be done 
> manually
>
>
>>

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


Re: Channels 2.0 - Exception when sending a message to client

2018-02-25 Thread Ken Whitesell
In so far as you are talking about background worker tasks, you are correct.

But those statements do not pertain to a websocket consumer that accepts 
connections from a browser. You can run an application without ever 
creating a worker task. (Again, I'll refer you to the channels-examples app 
for such a demonstration.)

Ken


On Sunday, February 25, 2018 at 5:04:13 AM UTC-5, muha...@swordfish.co.za 
wrote:
>
> While I'm at it, would you mind confirming if I understand the following 
> changes in channels 2.0 correctly ?
>
> 1) Channel names are not auto-detected and must be specified when running 
> a worker
> 2) *runserver* no long starts up a worker by default, this has be done 
> manually
>
> On Sunday, February 25, 2018 at 2:56:45 AM UTC+2, muha...@swordfish.co.za 
> wrote:
>>
>> I'm still trying to find my way around channels 2.0, so I'm not sure if 
>> my implementation is incorrect or if this is a valid issue. I'm going to 
>> post as much info as possible in the hope that it will assist with finding 
>> the problem.
>>
>> I have a single page app which opens a JS websocket connection - with 
>> channels 1 I used to add a *session_key *to the querystring and that 
>> used to handle the authentication.
>>
>> I see this is no longer the case, so I now have a custom middleware class 
>> that sets the user object on the scope:
>>
>> from django.contrib.sessions.models import Session
>>
>> from users.models import User
>>
>>
>> class QueryAuthMiddleware:
>>
>> def __init__(self, inner):
>> # Store the ASGI application we were passed
>> self.inner = inner
>>
>> def __call__(self, scope):
>> # Look up user from query string (you should also do things like
>> # check it's a valid user ID, or if scope["user"] is already 
>> populated)
>> if scope.get("user", None) is None:
>> session_obj = 
>> Session.objects.get(session_key=scope["query_string"].decode("utf-8").split("=")[1])
>> session_decoded = session_obj.get_decoded()
>>
>> scope["user"] = 
>> User.objects.get(id=session_decoded.get("_auth_user_id"))
>>
>> # Return the inner application directly and let it run 
>> everything else
>> return self.inner(scope)
>>
>>
>>
>>
>> This is in turn added to my routing (channels.py):
>>
>> from django.conf.urls import url
>> from django.conf import settings
>> from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter
>>
>> from notifications.consumer import TestWebsocketConsumer, TestConsumer
>> from notifications.middleware.query_auth_middleware import 
>> QueryAuthMiddleware
>>
>> ROOT_PATH = "" if settings.DEBUG else "/ws/"
>>
>>
>> application = ProtocolTypeRouter({
>>
>> "websocket": QueryAuthMiddleware(
>> URLRouter([
>> url(f"^{ROOT_PATH}(?P[-\w]+)/$", TestWebsocketConsumer),
>>
>> ])
>> ),
>>
>> "channel": ChannelNameRouter({
>>  "user-notifications": TestConsumer,
>> })
>>
>>
>> })
>>
>>
>>
>>
>>
>> Here's my *consumers.py*:
>>
>> from asgiref.sync import async_to_sync
>> from channels.consumer import SyncConsumer
>> from channels.generic.websocket import WebsocketConsumer
>>
>>
>> class TestWebsocketConsumer(WebsocketConsumer):
>> def websocket_connect(self, message):
>> 
>> async_to_sync(self.channel_layer.group_add)(str(self.scope["user"].id), 
>> "user-notifications")
>> self.connect()
>>
>>
>> class TestConsumer(SyncConsumer):
>> def notification_handler(self, message):
>>
>> self.send(
>> {
>>  "type": "websocket.send",
>>  "text": message["text"]
>> }
>> )
>>
>>
>>
>>
>>
>>
>> The idea of the app is that each user that logs in on the front end is 
>> able to receive messages meant only for them sent by the back end.  I have 
>> been trying to test it like this:
>>
>> >>> channel_layer = get_channel_layer()
>> >>> async_to_sync(channel_layer.send)("user-notifications", {"type": 
>&

Re: Channels 2.0 - Exception when sending a message to client

2018-02-25 Thread Ken Whitesell
Before I get to the guts of my answer, I'd suggest you get Andrew Godwin's 
"channels-examples" application and read it completely until you believe 
you understand everything that it's doing. 
(https://github.com/andrewgodwin/channels-examples)

Now, to the extent of my understanding, the "ChannelNameRouter" is used for 
background tasks - it's not used for connections by a websocket client- so 
the API is different than the router used for a websocket.

The applicable excerpt from the routing.py file in the channels-examples 
app (comments removed - see the full file for more details):
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
# URLRouter just takes standard Django path() or url() entries.
path("chat/stream/", ChatConsumer),
]),
),
"channel": ChannelNameRouter({
"mpge-timer": TimerConsumer
}),

})

What this is saying to me is that in the channels world, there are (at 
least) two fundamentally different types of objects - 
1) There are websocket consumers, which are connected to by an external 
client using a websocket connection, _and_ can send and receive messages on 
the internal channel. These are defined in the "websocket" key of the 
ProtocolTypeRouter object.
When they are created by a connection being made, they are given a "scope" 
which exists for the life of the connection. This scope include a 
system-generated channel name - but it's implicit in the API that that 
consumer uses to send & receive messages - you don't specify it when making 
calls. (Don't know if that's universally true, but it's my current 
impression.)

2) There are worker tasks, which do _not_ create or use websockets to make 
a connection to the outside world. They exist to send and receive events 
via channels. (They can also make changes to your models, so strictly 
speaking, channels aren't their only means of communication to other tasks 
or processes.)

So for your task, you'll want to define your TestWebSocketConsumer within 
the websocket key of the ProtocolTypeRouter

Keep in mind that a websocket is created as an "upgrade" of a regular HTTP 
connection - hence the requirement of a url as part of the routing. 
Effectively, the client is issuing an HTTP GET request for a url, and also 
says, "Oh, by the way, I want to upgrade this connection to be a 
websocket". (The actual protocol is a little bit more complex than that - 
but not too much.) So the server gets the GET, and needs to route it to 
something that will handle that URL and provide the upgraded protocol. That 
is handled by Daphne at the lowest layers - this definition is just 
information that Daphne uses to figure out what object gets to handle each 
url.

Hope this helps.
Ken

Disclaimer: I am not Andrew Godwin, I do not play him on TV, and my code 
will never be mistaken for his. In any situation where there's a 
discrepancy between anything he has written and my comments, I am wrong. At 
this point I'm guessing I'm just about a step and a half ahead of you in 
working my way though this.


On Sunday, February 25, 2018 at 4:42:27 AM UTC-5, muha...@swordfish.co.za 
wrote:
>
> Thanks for the update - I think I understand now.
>
> I updated my channel name routing and pointed it at the Websocket consumer:
>
> "channel": ChannelNameRouter({
> "user-notifications": TestWebsocketConsumer,
> })
>
>
>
> Moved the message handler into *TestWebsocketConsumer:*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *from asgiref.sync import async_to_syncfrom channels.generic.websocket 
> import WebsocketConsumerclass TestWebsocketConsumer(WebsocketConsumer):
> def websocket_connect(self, message):
> async_to_sync(self.channel_layer.group_add)(str(self.scope["user"].id), 
> "user-notifications")self.connect()def 
> notification_handler(self, message):self.send({
>  "text": message["text"]})*
> This raises the same exception:
>
> ERROR:root:Exception inside application: You must implement 
> application_send()
>   File 
> "/Users/muhammed/projects/xxx/lib/python3.6/site-packages/channels/consumer.py",
>  
> line 54, in __call__
> await await_many_dispatch([receive, self.channel_receive], 
> self.dispatch)
>   File 
> "/Users/muhammed/projects/xxx/lib/python3.6/site-packages/channels/utils.py", 
> line 48, in await_many_dispatch
> await dispatch(result)
>   File 
> "/Users/muhammed/projects/xxx/lib/python3.6/site-packages/asgiref/sync.py", 
> line 110, in _

Re: Simple Search Feature

2018-02-24 Thread Ken Whitesell
One of the issues is here:
if request.method == 'GET':
song_name = request.GET.get('name', "Error")
songs = self.model.objects.filter(name__icontains=song_name)
else:
songs = self.models.all()
return render(request, self.template_name, {'songs': songs})

When no parameter is passed, request.method is still "GET" - In fact, this 
method should only be called on a get method, making this test irrelevant.

You _could_ change it to look something like this:
song_name = request.GET.get('name', None)
if song_name:
songs = self.model.objects.filter(name__icontains=song_name)
else:
songs = self.models.all()
return render(request, self.template_name, {'songs': songs})

Hope this helps,
 Ken


On Saturday, February 24, 2018 at 8:18:25 PM UTC-5, tangoward15 wrote:
>
> Hi,
>
> I am playing around on adding a search feature to a website. I am 
> currently encountering a problem when the page should load a list of songs 
> and after typing in a song title in the search box:
>
>
> views.py
>
> class SongListView(ListView):
> model = SongOne 
> context_object_name = 'songs'
> template_name = 'songs/song_list.html'
>
> def get(self, request, *args, **kwargs):
>
> if request.method == 'GET':
> song_name = request.GET.get('name', "Error")
> songs = self.model.objects.filter(name__icontains=song_name)
> else:
> songs = self.models.all()
> return render(request, self.template_name, {'songs': songs})
>
> problem is when I click the search button with the text box empty, I am 
> getting the list of all the song (url: /songs/?name=) but if I just load 
> the page wihout clicking the submit button (url: /songs/), it doesn't give 
> me the list all the songs. The search box works if I type the correct song 
> name as it shows the song title.  Problem is the page should load all the 
> songs before I search a particular song.
>
> Any suggestions so I can enhance my code?
>
>
> Thanks,
> Jarvis
>
>

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


Re: Channels 2.0 - Exception when sending a message to client

2018-02-24 Thread Ken Whitesell
I'm going to take a stab at this - with the warning that I'm extremely 
uncertain that I'm anywhere close to being correct, but I'm hoping that I'm 
at least close enough that it might give you some clues.

So where I think the issue may be is that you're trying to do a "self.send" 
from a worker task, not from a websocket task. If you look at the docs for 
the "Worker and Background Tasks", you'll see that to send an event you 
call "self.channel_layer.send" with a first parameter of the channel to 
which you wish to send the message.

Since this worker task isn't running in the context of a websocket 
consumer, it doesn't automatically know to which channel a response should 
be sent. (I _know_ that my wording there is imprecise and probably 
inaccurate, but I think I'm sufficiently close for casual conversation.)

If you want the worker task to send a message back to a client, what _I_ 
have done is create another method in my WebSocket consumer that takes a 
message and forwards it back out to the client. In thinking about it, I 
guess it may be possible that if I pass something (whatever that 
"something" might be) to the worker task, I might be able to send a message 
back out without going back through the consumer - again, that's a guess 
for something I haven't tried yet.

Anyway, I hope this helps.

Ken

On Saturday, February 24, 2018 at 7:56:45 PM UTC-5, muha...@swordfish.co.za 
wrote:
>
> I'm still trying to find my way around channels 2.0, so I'm not sure if my 
> implementation is incorrect or if this is a valid issue. I'm going to post 
> as much info as possible in the hope that it will assist with finding the 
> problem.
>
> I have a single page app which opens a JS websocket connection - with 
> channels 1 I used to add a *session_key *to the querystring and that used 
> to handle the authentication.
>
> I see this is no longer the case, so I now have a custom middleware class 
> that sets the user object on the scope:
>
> from django.contrib.sessions.models import Session
>
> from users.models import User
>
>
> class QueryAuthMiddleware:
>
> def __init__(self, inner):
> # Store the ASGI application we were passed
> self.inner = inner
>
> def __call__(self, scope):
> # Look up user from query string (you should also do things like
> # check it's a valid user ID, or if scope["user"] is already 
> populated)
> if scope.get("user", None) is None:
> session_obj = 
> Session.objects.get(session_key=scope["query_string"].decode("utf-8").split("=")[1])
> session_decoded = session_obj.get_decoded()
>
> scope["user"] = 
> User.objects.get(id=session_decoded.get("_auth_user_id"))
>
> # Return the inner application directly and let it run everything 
> else
> return self.inner(scope)
>
>
>
>
> This is in turn added to my routing (channels.py):
>
> from django.conf.urls import url
> from django.conf import settings
> from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter
>
> from notifications.consumer import TestWebsocketConsumer, TestConsumer
> from notifications.middleware.query_auth_middleware import QueryAuthMiddleware
>
> ROOT_PATH = "" if settings.DEBUG else "/ws/"
>
>
> application = ProtocolTypeRouter({
>
> "websocket": QueryAuthMiddleware(
> URLRouter([
> url(f"^{ROOT_PATH}(?P[-\w]+)/$", TestWebsocketConsumer),
>
> ])
> ),
>
> "channel": ChannelNameRouter({
>  "user-notifications": TestConsumer,
> })
>
>
> })
>
>
>
>
>
> Here's my *consumers.py*:
>
> from asgiref.sync import async_to_sync
> from channels.consumer import SyncConsumer
> from channels.generic.websocket import WebsocketConsumer
>
>
> class TestWebsocketConsumer(WebsocketConsumer):
> def websocket_connect(self, message):
> 
> async_to_sync(self.channel_layer.group_add)(str(self.scope["user"].id), 
> "user-notifications")
> self.connect()
>
>
> class TestConsumer(SyncConsumer):
> def notification_handler(self, message):
>
> self.send(
> {
>  "type": "websocket.send",
>  "text": message["text"]
> }
> )
>
>
>
>
>
>
> The idea of the app is that each user that logs in on the front end is 
> able to receive messages meant only for them sent 

Re: Channels worker and call_later

2018-02-23 Thread Ken Whitesell
Andrew,

 Thanks for the quick reply! Yea, I kinda guessed I was overthinking 
this. Your solution works 100% for exactly what I'm trying to do.

Sorry about the confusion regarding my reference to Twisted, it's no part 
of this particular project - I only mentioned it to state that while it has 
been awhile, I do have some familiarity with (in a general sense) 
asynchronous / event-driven programming in Python, but no specific 
knowledge of the current asyncio in Python 3.6 - so while I'm comfortable 
with the general concepts, there are a lot of the specifics that I'm still 
picking up.

Anyway, thanks again!

Ken 


On Friday, February 23, 2018 at 10:56:03 PM UTC-5, Andrew Godwin wrote:
>
> Hi Ken,
>
> You should write asyncio code, rather than Twisted code - we have Twisted 
> running on it asyncio reactor so both are available, and asyncio is the 
> only thing you're guaranteed from the spec/other future servers.
>
> Given that, I would recommend making a separate asyncio Task that has an 
> "await asyncio.sleep(30)" in it and then does what you want. If you then 
> need to cancel the task, you can call ".cancel()" on it (and remember, you 
> can put it on `self` if you need to keep a reference).
>
> To make a task, just do:
>
> loop = asyncio.get_event_loop()
> self.task = loop.create_task(coroutine_function())
>
> Hope that helps!
>
> Andrew
>
> On Fri, Feb 23, 2018 at 7:48 PM, Ken Whitesell  > wrote:
>
>> TLDR: Is there a way to use the call_later function within a worker task? 
>> (Or am I just looking at this issue the wrong way?)
>>
>> Software - Python 3.6, Django 2.0.2, Channels 2.0.2, trying to run this 
>> on either / both Windows 10 and Ubuntu 17.10 if it matters
>>
>> Longer version - I'm having surprisingly few problems with wrapping my 
>> head around the new Channels 2, especially since this is the first I've 
>> been using asyncio and it's been about 10 years since I've used Twisted. 
>> All my personal sample code that I've been trying to write has been working 
>> great.
>>
>> Except... I have the situation where I want to schedule an event for some 
>> fixed period of time in the future - say 30 seconds.
>> But, it's also necessary for me to be able to cancel that scheduled event.
>>
>> I've tried a number of different combinations for the worker task between 
>> SyncConsumer and AsyncConsumer, and different combinations of async and 
>> regular methods, and get a variety of different errors. But the bottom line 
>> is that I haven't stumbled across the magic sauce that will let this work.
>>
>> I _can_ get the delay to work by using the asyncio.sleep method, using 
>> the pattern shown in the "Delay server" paragraph in the "What's new in 
>> Channels 2?" section of the docs. But while that method (sleep) returns a 
>> generator object, I don't see where that does me any good with trying to 
>> cancel that sleep.
>>
>> I know I can make this work by setting some variable, and check that 
>> after the sleep has finished to determine whether or not I still need to do 
>> my work, but that just "feels wrong" to me for some reason.
>>
>> Is there something simple that I'm missing? Or does this fit into the 
>> category of "Don't do that!"
>>
>> Thanks,
>>  Ken
>>
>> -- 
>> You received this message because you are subscribed 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 https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/642da2f0-5c07-44ee-9059-a366ef67de14%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/642da2f0-5c07-44ee-9059-a366ef67de14%40googlegroups.com?utm_medium=email&utm_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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ae18c2ea-5503-4c97-85e1-121c5a765ae2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Channels worker and call_later

2018-02-23 Thread Ken Whitesell
TLDR: Is there a way to use the call_later function within a worker task? 
(Or am I just looking at this issue the wrong way?)

Software - Python 3.6, Django 2.0.2, Channels 2.0.2, trying to run this on 
either / both Windows 10 and Ubuntu 17.10 if it matters

Longer version - I'm having surprisingly few problems with wrapping my head 
around the new Channels 2, especially since this is the first I've been 
using asyncio and it's been about 10 years since I've used Twisted. All my 
personal sample code that I've been trying to write has been working great.

Except... I have the situation where I want to schedule an event for some 
fixed period of time in the future - say 30 seconds.
But, it's also necessary for me to be able to cancel that scheduled event.

I've tried a number of different combinations for the worker task between 
SyncConsumer and AsyncConsumer, and different combinations of async and 
regular methods, and get a variety of different errors. But the bottom line 
is that I haven't stumbled across the magic sauce that will let this work.

I _can_ get the delay to work by using the asyncio.sleep method, using the 
pattern shown in the "Delay server" paragraph in the "What's new in 
Channels 2?" section of the docs. But while that method (sleep) returns a 
generator object, I don't see where that does me any good with trying to 
cancel that sleep.

I know I can make this work by setting some variable, and check that after 
the sleep has finished to determine whether or not I still need to do my 
work, but that just "feels wrong" to me for some reason.

Is there something simple that I'm missing? Or does this fit into the 
category of "Don't do that!"

Thanks,
 Ken

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


Re: LDAPSearch Troubleshooting

2017-10-10 Thread Ken Jenney
Good catch! I just fixed it and re-tried and it works now. I had to get 
past the group search but ultimately my mispellings caught me up. Thanks 
for all the help James!

On Tuesday, October 10, 2017 at 3:10:39 PM UTC-4, James Schneider wrote:
>
>
>
> On Oct 10, 2017 11:55 AM, "Ken Jenney" > 
> wrote:
>
> I fixed the DN for the service account:
>
> AUTH_LDAP_BIND_DN = "UID=netbox,CN=users,DC=kenset,DC=priv"
>
> I've tried at least a 100 different things so far and nothing is getting 
> me there.
>
> from django_auth_ldap.config import LDAPSearch, PosixGroupType
> AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=kensnet,dc=priv", 
> ldap.SCOPE_SUBTREE, (objectClass=posixGroup)")
>
>
>
> I also just noticed that the dc= values are different between your BIND_DN 
> and GROUP_SEARCH as well. 
>
> kensnet vs. kesnet
>
> -James
>

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


Re: LDAPSearch Troubleshooting

2017-10-10 Thread Ken Jenney
I fixed the DN for the service account:

AUTH_LDAP_BIND_DN = "UID=netbox,CN=users,DC=kenset,DC=priv"

I've tried at least a 100 different things so far and nothing is getting me 
there.

from django_auth_ldap.config import LDAPSearch, PosixGroupType
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=kensnet,dc=priv", 
ldap.SCOPE_SUBTREE, (objectClass=posixGroup)")
AUTH_LDAP_GROUP_TYPE = PosixGroupType()

AUTH_LDAP_USER_ATTR_MAP = { 
   "first_name": "cn",
   "last_name":  "sn"
}

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
 "is_staff": f"cn={AUTH_LDAP_USER_STAFF},cn=groups,dc={dc1},dc={dc2}",
"is_superuser": 
f"cn={AUTH_LDAP_USER_SUPERUSER},cn=groups,dc={dc1},dc={dc2}"
}

There must be a better way to troubleshoot this than shooting in the dark. 
posixGroup is set on each group but I'm not sure if that's the best way to 
search for the groups since it's still not working. I've opened up a ticket 
with Synology in the meantime.

On Sunday, October 8, 2017 at 10:34:31 PM UTC-4, Ken Jenney wrote:
>
> I've got LDAPSearch configured to work with my Synology Directory Server. 
> Users can authenticate fine but when I try to map a user to a group I get 
> INVALID_CREDENTIALS:
>
> import ldap
>
>
> # Server URI
> AUTH_LDAP_SERVER_URI = "ldaps://synology.kensnet.priv"
>
>
> # Set the DN and password for the NetBox service account.
> AUTH_LDAP_BIND_DN = "CN=netbox,CN=users,DC=kensnet,DC=priv"
> AUTH_LDAP_BIND_PASSWORD = bindpassword
>
>
> LDAP_IGNORE_CERT_ERRORS = True
>
>
> from django_auth_ldap.config import LDAPSearch, PosixGroupType, 
> GroupOfNamesType
>
>
> AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=users,dc=kensnet,dc=priv",
> ldap.SCOPE_SUBTREE,
> "(sAMAccountName=%(user)s)")
>
>
> # If a user's DN is producible from their username, we don't need to 
> search.
> AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,cn=users,dc=kensnet,dc=priv"
>
>
> ### EVERYTHING WORKS UP UNTIL HERE
>
>
>  Groups
>
>
> # # This search ought to return all groups to which the user belongs. 
> django_auth_ldap uses this to determine group
> # # heirarchy.
> AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=kensnet,dc=priv", ldap.
> SCOPE_SUBTREE,
> "(objectClass=organizationalRole")
> AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
>
>
> # # Define a group required to login.
> AUTH_LDAP_REQUIRE_GROUP = "cn=users,cn=groups,dc=kensnet,dc=priv"
>
>
> # Define special user types using groups. Exercise great caution when 
> assigning superuser status.
> AUTH_LDAP_USER_FLAGS_BY_GROUP = {
> "is_staff": "cn=staff,cn=groups,dc=kensnet,dc=priv",
> "is_superuser": "cn=administrators,cn=groups,dc=kensnet,dc=priv"
> }
>
>
> How can I troubleshoot the group search/mapping to figure out what the 
> issue is? 
>

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


Re: LDAPSearch Troubleshooting

2017-10-08 Thread Ken Jenney
1) I'm using a service account. I verified the DN's by connecting using 
Apache Directory Studio. 
2) I just promoted the service account user but I'm still facing the same 
error.
3) Logging is not helping: it's only reiterating what the original error is 
telling me: Caught LDAPError while authenticating ken: 
INVALID_CREDENTIALS({'desc': 'Invalid credentials'},) I added logging by 
adding this to the config:

import logging


logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)


On Sunday, October 8, 2017 at 11:06:20 PM UTC-4, James Schneider wrote:
>
>
>
> On Oct 8, 2017 7:33 PM, "Ken Jenney" > 
> wrote:
>
> I've got LDAPSearch configured to work with my Synology Directory Server. 
> Users can authenticate fine but when I try to map a user to a group I get 
> INVALID_CREDENTIALS:
>
>
> Are you binding to LDAP using the users' credentials, or do you have a 
> service account? It appears you have a service account configured, but I 
> can't tell whether or not it is in use based on the settings you provided.
>
> Have you:
>
> a) Verified the DN being used against the Synology NAS for the user and 
> group authentication requests? This can be found in the Synology auth logs.
> b) Verified that the account in use has permission to traverse that 
> portion of the LDAP schema, including a user being able to query their own 
> groups, or the service account being able to list other users' groups?
> c) Increased the logging level for Django and specifically for the Django 
> LDAP package you are using to examine what is happening?
>
> This issue will likely be illuminated very easily by the detailed logs on 
> each side of the connection.
>
> -James
>

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


LDAPSearch Troubleshooting

2017-10-08 Thread Ken Jenney
I've got LDAPSearch configured to work with my Synology Directory Server. 
Users can authenticate fine but when I try to map a user to a group I get 
INVALID_CREDENTIALS:

import ldap


# Server URI
AUTH_LDAP_SERVER_URI = "ldaps://synology.kensnet.priv"


# Set the DN and password for the NetBox service account.
AUTH_LDAP_BIND_DN = "CN=netbox,CN=users,DC=kensnet,DC=priv"
AUTH_LDAP_BIND_PASSWORD = bindpassword


LDAP_IGNORE_CERT_ERRORS = True


from django_auth_ldap.config import LDAPSearch, PosixGroupType, 
GroupOfNamesType


AUTH_LDAP_USER_SEARCH = LDAPSearch("cn=users,dc=kensnet,dc=priv",
ldap.SCOPE_SUBTREE,
"(sAMAccountName=%(user)s)")


# If a user's DN is producible from their username, we don't need to search.
AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,cn=users,dc=kensnet,dc=priv"


### EVERYTHING WORKS UP UNTIL HERE


 Groups


# # This search ought to return all groups to which the user belongs. 
django_auth_ldap uses this to determine group
# # heirarchy.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("dc=kensnet,dc=priv", ldap.SCOPE_SUBTREE
,
"(objectClass=organizationalRole")
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()


# # Define a group required to login.
AUTH_LDAP_REQUIRE_GROUP = "cn=users,cn=groups,dc=kensnet,dc=priv"


# Define special user types using groups. Exercise great caution when 
assigning superuser status.
AUTH_LDAP_USER_FLAGS_BY_GROUP = {
"is_staff": "cn=staff,cn=groups,dc=kensnet,dc=priv",
"is_superuser": "cn=administrators,cn=groups,dc=kensnet,dc=priv"
}


How can I troubleshoot the group search/mapping to figure out what the 
issue is? 

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


django_tables2: Unable to manually iterate through column values in template

2017-10-06 Thread Ken
Hi all

I came to django_tables2 via django_tables.

There are a few occasions when I want to manually iterate through the 
columns of each row of a table in my template.  I've always done this using:

{% for row in table.rows %}{{ row.det_id }}{% endfor %}


It's worked OK in my code for years - on Django 1.9 and django_tables2 1.1.1

However, I recently upgraded to django_tables2 1.10, and this no longer 
works.  (I just get empty fields - not even hyphens.)

How do I do the iteration now?  If I am required to do this completely 
differently, then the migration info from django_tables to django_tables2 
is now misleading.

Cheers,

Ken


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


Re: How to pass data between Django module/app functions without using database in asynchronous web service

2016-12-29 Thread Ken McDonald
On Thursday, December 29, 2016 at 6:00:03 AM UTC-5, Andrew Godwin wrote:
>
> *Q) Are the websocket and the AJAX calls going to different clients/pages 
> entirely, rather than them both being in the same page context? It sounds 
> like the websocket is going to a server somewhere that's allocating 
> resources and not going to a webpage/browser at all.*
>
> A) Currently the websockets are used in a background system running on 
Django and most of the use for websockets on this service are so the remote 
system we are interfacing with can pull a list of subscribers from a Django 
model and then the remote system does uncoordinated stuff with that. 
Occasionally, the remote system updates data to Django models for debugging 
information or sending statistics back.

In the normal course of the application, the web server web page interface 
is between user and Django model and has no need for a direct connection to 
the remote system through websockets; they are just setting up subscription 
types as a seller or buying subscriptions as a buyer. Later, when they are 
using the remote system, which happens with a completely different client 
native compiled application, not Django or web interface, they make use of 
the real purpose of our system which is enhanced by the subscriptions we 
sell. Basically, we
are using the Django web service to sell subscriptions which are then 
periodically download through websockets to a remote native compiled 
application.
 

*On Thursday, December 29, 2016 at 6:00:03 AM UTC-5, Andrew Godwin wrote:*

> *Q) - Could it potentially take the websocket client that is sending the 
> LOBBY data back that needs to then be conveyed over AJAX some time to 
> reply? Say, more than ten seconds?*
>
> A) The return replies are just about instantaneous and very small in size. 
Although ultimately the system will interface with potentially 1000's of 
distinct remote systems, the Django web service is only used for a very, 
very short period of time by a user, and then maybe never again if they 
just continue to renew their subscription. The users are at the remote 
systems. We just sell stuff that makes that experience better. The need for 
displaying return data as envisioned in my original question is a rare 
occurannce almost exclusively used by sellers and more so, just by 
administrators of the system.
 

*On Thursday, December 29, 2016 at 6:00:03 AM UTC-5, Andrew Godwin wrote:*

> *Q) I think I have an idea of what you're trying to do here and how to 
> solve it, but I just need to be a bit more clear on the architecture first.*
>

A) My primary purpose for the django-channels to remote system is working 
great. I can download from a model and upload to a model through websockets 
(just for reference: the interface at the remote system is a C++ compiled 
application (w/ websockets) connected to a C# final product). 

There are various need, by this example can best describe a single feature:

1) We have a debugging system on the remote system that will upload 
transactions from there to our Django model through websockets.
2) In that debugging system, we can set various levels of verbosity to 
control how much detail is returned.
3) I have a working Django web page now that can send commands that change 
the debugging level through a websocket-routed command in a JSON message 
with a particular debugging level (like 1-7). This web page uses a Django 
template with a radio button form for the 1-7 choices.
4) When a choice is changed on the form, Javascript catches it and calls a 
Django function that send the websocket command to the remote system to 
change the debugging (we track websocket instances of channel names in a 
database, so I can always contact a particular remote system by knowing our 
own internally-assign db id to lookup the Django channel name for that 
websocket connection).

In the above example, what I am looking for is that when the web page is 
initially rendered (url'd in browser), fetch the current debugging level 
from the remote system and pre-set the radio buttons. Right now of course, 
the page just renders with a default layout of the radio button without 
reference to what the current debugging level actually is at the remote 
site.

In addition to the websocket JSON command to tell the remote system to set 
a particular debugging level, I also have a command that requests the 
current debugging level. It's connecting the reply back data from that 
request command to the webpage when it's initially rendered that is proving 
difficult to understand.

Thanks for any help you or anyone can provide. I'm dealing with a lot of 
technologies and a lot of languages that I'm not totally expert or 
experienced with, but I will complete this project in one form or another. 
My system engineering background leads me to want a design that is more 
push and event-driven, than pull and polling. I can find a solution that is 
pull and polling (store in table, Javascript t

How to pass data between Django module/app functions without using database in asynchronous web service

2016-12-28 Thread Ken McDonald
I've got a web service under development that uses Django and Django 
Channels to send data across websockets to a remote application. The 
arrangement is asynchronous and I pass information between the 2 by sending 
JSON formatted commands across websockets and then receive replies back on 
the same websocket.

The problem I'm having is figuring out how to get the replies back to a 
Javascript call from a Django template that invokes a Python function to 
initiate the JSON websocket question. Since the command question & data 
reply happen in different Django areas and the originating 
Javascript/Python functions call does not have a blocking statement, the 
Q&A are basically disconnected and I can't figure out how to get the 
results back to the browser.

Right now, my idea is to use Django global variables or store the results 
in the Django models. I can get either to work, but I beleive the Django 
global variables would not scale beyond multiple workers from runserver or 
if the system was eventually spread across multiple servers. 

But since the reply data is for different purposes (for example, list of 
users waiting in a remote lobby, current debugging levels in remote system, 
etc), the database option seems unworkable because the reply data is 
varying structure. That, plus the replies are temporal and don't need to be 
permanently stored in the database.

Here's some code showing the flow. I'm open to different implementation 
recommendations or a direct answer to the question of how to share 
information between the 2 Django functions.

In the template, for testing, I just have a button defined like this:

Request Lobby


With a Javascript function. This function is incomplete as I've yet to do 
anything about the response (because I can't figure out how to connect it):

$("#request_lobby").click(function(){
$.ajax({
type: "POST",
url: "{% url 'test_panel_function' %}",
data: { csrfmiddlewaretoken: '{{ csrf_token }}', button:
"request_lobby" },
success: function(response){
}
});
});


This is the Django/Python function in views.py . The return channel for the 
remote application is pre-stored in the database as srv.server_channel when 
the websocket is initially connected (not shown):

@login_required
def test_panel_function(request):

button = request.POST.get('button', '')

if button == "request_lobby" :
srv = Server.objects.get(server_key="1234567890")
json_res = []
json_res.append({"COMMAND": "REQUESTLOBBY"})
message = ({
"text": json.dumps(json_res)
})
Channel(srv.server_channel).send(message)
return HttpResponse(button)



Later, the remote application sends the reply back on the websocket and 
it's received by a Django Channels demultiplexer in routing.py :

class RemoteDemultiplexer(WebsocketDemultiplexer):
mapping = {
"gLOBBY"   : "gLOBBY.receive",
}
http_user = True
slight_ordering = True
  

channel_routing = [
route_class(RemoteDemultiplexer, path=r
"^/server/(?P[a-zA-Z0-9]+)$"),
route("gLOBBY.receive"   , command_LOBBY),
]



And the consumer.py :

@channel_session
def command_LOBBY(message):
skey = message.channel_session["server_key"]
for x in range(int(message.content['LOBBY'])):
logger.info("USERNAME:  " + message.content[str(x)]["USERNAME"])
logger.info("LOBBY_ID:  " + message.content[str(x)]["LOBBY_ID"])
logger.info("OWNER_ID:  " + message.content[str(x)]["IPADDRESS"
])
logger.info("DATETIME:  " + message.content[str(x)]["DATETIME"])


So I need to figure out how to get the reply data in command_LOBBY to the 
Javascript/Python function call in test_panel_function

Current ideas, both of which seem bad and why I think I need to ask this 
question for SO:

*1) Use Django global variables:*

Define in globals.py:

global_async_result = {}



And include in all relevant Django modules:

from test.globals import global_async_result


In order to make this work, when I originate the initial command in 
test_panel_function to send to the remote application (the REQUESTLOBBY), 
I'll include a randomized key in the JSON message which would be 
round-tripped back to command_LOBBY and then global_async_result dictionary 
would be indexed with the randomized key.

In test_panel_function , I would wait in a loop checking a flag for the 
results to be ready in global_async_result and then retrieve them from the 
randomized key and delete the entry in global_async_result.

Then the reply can be given back to the Javascript in the Django template.

That all makes sense to me, but uses global variables (bad), and seems that 
it wouldn't scale 

Re: Newbie question - data structure for game

2016-10-29 Thread Ken Albright
Sounds good. Thanks for the advice. Now if I could only figure out how to 
get forms to expand and contract to match the size of the quote...

Thanks.

On Friday, October 28, 2016 at 5:00:14 PM UTC-7, Ken Albright wrote:
>
> I'm just learning Python and Django so please be gentle...
>
> I've written a quote decryption game (like you see in the newspaper) in 
> Python. I'd like to put it on a web page with Django. However, I'm not sure 
> of the best way to structure the data. The original quote and the encrypted 
> quote need to have a one-to-one relationship at the letter level. So it 
> could be two strings on the same row (same id) or a set of tuples, a 
> dictionary, or ???
>
> How to set up the database and models.py?
>
> 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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d97d972b-ec64-483a-8aaf-e69482a4050e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Newbie question - data structure for game

2016-10-28 Thread Ken Albright
I'm just learning Python and Django so please be gentle...

I've written a quote decryption game (like you see in the newspaper) in 
Python. I'd like to put it on a web page with Django. However, I'm not sure 
of the best way to structure the data. The original quote and the encrypted 
quote need to have a one-to-one relationship at the letter level. So it 
could be two strings on the same row (same id) or a set of tuples, a 
dictionary, or ???

How to set up the database and models.py?

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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b37833bf-e474-4b15-844d-4ef8d8e854b6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Models

2016-05-27 Thread Ken Edem
Wow, Derek what a great link. Thanks very much.

Ken

On Friday, May 27, 2016 at 4:47:56 PM UTC+2, Derek wrote:
>
> There a number of designs for similar situations online; a quick Google 
> showed me:
>
> * http://www.databasedev.co.uk/student_courses_data_model.html
> * http://databaseanswers.org/data_models/ 
>
> And I am sure there are more... 
>
> If this is your first project. I would not be too fussed about making it 
> perfect.  Try out what seems to work and then iterate as you go.  You'll 
> learn a lot and probably end up having to rewrite based on all your 
> learning.
>
> On Friday, 27 May 2016 02:47:34 UTC+2, Ken Edem wrote:
>>
>> I am new to Django Python and I need bit of help
>>
>>
>>
>> Can someone please help me with how I should structure my models, since 
>> this is a very important part of the project I am trying to develop, I had 
>> been teaching myself and not yet good at this stuff. I want to develop a 
>> web project for matching teachers or instructors who will teach students 
>> who subscribes to our service at they residence.For now I think I will need 
>> these models:
>>
>>
>> Students = Database to contain all students details.  See below for the 
>> database fields
>>
>> Instructors = Database to contain all instructors or teachers details. 
>> See below
>>
>> Course = Databases for all the courses or services that will be offering
>>
>> Feedbacks = Database to contains both feedbacks from students about 
>> teachers and also teachers about students.
>>
>>
>> So, I have done something in terms of normalising my database, but I do 
>> not think it is efficient enough.? I think I also need a database Class, 
>> which is combination of Students and Instructors, but I cannot figures what 
>> the fields of this database should be.
>>
>> I also think I need a combine database Instructors & Course and Course & 
>> Students. But I cannot figure out what the fields of these databases also 
>> should be and what the foreign key or whatever should be.
>>
>>
>> You see, our primary service will be matching students with instructors 
>> and having these instructors teach student what they want to be thought.
>>
>>
>> Please can  someone assist me in structuring my models a structure and 
>> also should I just have one app or separate apps for students, instructors, 
>> feedbacks etc. Thanks in advance.
>>
>>
>> Below is my database models.
>>
>>
>> Thanks agains
>>
>>
>>  
>>
>>
>> Models and Tables
>>
>> -   Students
>>
>> -   Instructors
>>
>> -   Course
>>
>> -   Feedbacks
>>
>> -   Class
>>
>>
>> Model Properties and Fields
>>
>> Students
>>
>> -   student-id
>>
>> -   student_firstname
>>
>> -   student_lastname
>>
>> -   student_address
>>
>> -   student_city
>>
>> -   student_region
>>
>> -   student_startdate  (immediately, in 2 weeks, in a month over 6 months)
>>
>> -   student_classLocation (student address, instructor address, arrange 
>> location)
>>
>> -   student_phone1
>>
>> -   student_email
>>
>> -   student_phone2
>>
>> -   student_internetContact  (skype, viber etc)
>>
>> -   student_days_to_take_classes (mon - sun)
>>
>> -   student_duration_of_course  (1 - 12 months)
>>
>> -   student_hours_to_spend_on_course  (1 -8 hours)
>>
>> -   student_class_start_time  ( 06am - 06am)
>>
>> -   student_course_skill_level (beginner, intermediate, advance)
>>
>> -   student_personal_wishes_to_help_match_an_intructor ( )
>>
>> -   student_budget_amount
>>
>> -   student_preferred_instructor_gender  (male, female)
>>
>> -   student_date_of_birth
>>
>>
>> Students Methods and actions
>>
>> -   match a student to instructors
>>
>> -   seek payment
>>
>> -   message update
>>
>>
>>
>>
>> Instuctors
>>
>> -   id
>>
>> -   firstname
>>
>> -   lastname
>>
>> -   middlename
>>
>> -   gender
>>
>> -   date_of_birth
>>
>> -   phone1
>>
>> -   phone2
>>
>> -   streetaddress
>>
>> -   city
>>
>> -   region
>>
>> -   country
>>
>> -   qualifications  (multiple entry)
>>
>> -   certfications  (multiple entry)
>>
>> 

Django Models

2016-05-26 Thread Ken Edem
 

I am new to Django Python and I need bit of help



Can someone please help me with how I should structure my models, since 
this is a very important part of the project I am trying to develop, I had 
been teaching myself and not yet good at this stuff. I want to develop a 
web project for matching teachers or instructors who will teach students 
who subscribes to our service at they residence.For now I think I will need 
these models:


Students = Database to contain all students details.  See below for the 
database fields

Instructors = Database to contain all instructors or teachers details. See 
below

Course = Databases for all the courses or services that will be offering

Feedbacks = Database to contains both feedbacks from students about 
teachers and also teachers about students.


So, I have done something in terms of normalising my database, but I do not 
think it is efficient enough.? I think I also need a database Class, which 
is combination of Students and Instructors, but I cannot figures what the 
fields of this database should be.

I also think I need a combine database Instructors & Course and Course & 
Students. But I cannot figure out what the fields of these databases also 
should be and what the foreign key or whatever should be.


You see, our primary service will be matching students with instructors and 
having these instructors teach student what they want to be thought.


Please can  someone assist me in structuring my models a structure and also 
should I just have one app or separate apps for students, instructors, 
feedbacks etc. Thanks in advance.


Below is my database models.


Thanks agains


 


Models and Tables

-   Students

-   Instructors

-   Course

-   Feedbacks

-   Class


Model Properties and Fields

Students

-   student-id

-   student_firstname

-   student_lastname

-   student_address

-   student_city

-   student_region

-   student_startdate  (immediately, in 2 weeks, in a month over 6 months)

-   student_classLocation (student address, instructor address, arrange 
location)

-   student_phone1

-   student_email

-   student_phone2

-   student_internetContact  (skype, viber etc)

-   student_days_to_take_classes (mon - sun)

-   student_duration_of_course  (1 - 12 months)

-   student_hours_to_spend_on_course  (1 -8 hours)

-   student_class_start_time  ( 06am - 06am)

-   student_course_skill_level (beginner, intermediate, advance)

-   student_personal_wishes_to_help_match_an_intructor ( )

-   student_budget_amount

-   student_preferred_instructor_gender  (male, female)

-   student_date_of_birth


Students Methods and actions

-   match a student to instructors

-   seek payment

-   message update




Instuctors

-   id

-   firstname

-   lastname

-   middlename

-   gender

-   date_of_birth

-   phone1

-   phone2

-   streetaddress

-   city

-   region

-   country

-   qualifications  (multiple entry)

-   certfications  (multiple entry)

-   degrees (multiple entry)

-   present occupation

-   previous occupations (multiple entry)

-   present job position

-   length of teaching skills

-   type of skills to teach

-   class location (student address, tutor address, arranged address)


Instructor Methods and Actions

match instructor to students

seek instructors

pay instructors

-



Courses

-   id

-   course_name

-   course_description

-   course_duration


Methods



Feedbacks

-   id

-   course_name

-   instructor

-   student

-   Feedback_details

-   Grade (Beneficial, Great, Average, Satisfied, Very Satisfied, Excellent)




Class

-   instructor

-   students

-   course

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


remove ./ from commands

2016-04-21 Thread ken . foust
I just installed django 1.9.5.  Now I have to type ./manage.py when I used 
to just type manage.py.  How do I get rid of the need to type ./ 
osx el capitan

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


Django - Upload Image to the server with dimension

2015-12-29 Thread ken phanith
I simply use ImageField from PIL package for Django Image Upload but it 
does not satisfy me at all. I have a models class which contain many fields 
including ImageField also. I am trying to upload 10 images to the server 
but those images have the different dimension. I want to upload those image 
to the server but with same dimension (700*400) as the example.
Actually, I want to do that by using Django but I don't have any idea on 
how to do that. Does anyone have any ideas on how to do that? Please help 
me.
Thank you very much.

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


testcase argument via manage.py

2015-12-05 Thread Ken
Is it possible to pass options or arguments to a testcase?  The docs talk 
about subclassing DiscoverRunner and over-riding add_arguments but does not 
indicate how the arguments are retrieved in a test module.

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/93aec62b-b0b7-4b8b-a693-4ea62b5e6b6c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: BaseListView's get_context_data is missing kwargs?

2015-08-04 Thread Ken
Django is really well documented.  So much so, it's an effort to wade 
through it.  So, sometimes (most times), I resort to looking at the source 
code.  The downside is you miss these little tips mentioned in the docs, 
you miss the philosophy behind why it's done a particular way.


On Monday, August 3, 2015 at 9:55:49 PM UTC-5, James Schneider wrote:
>
> No problem. Not sure if you were looking at the source code or somewhere 
> else, but Classy CBV's is always the place I start:
>
> http://ccbv.co.uk/projects/Django/1.8/django.views.generic.list/ListView/
>
> -James
> On Aug 3, 2015 7:37 PM, "Ken" > wrote:
>
>> @Jordi,  Thanks for tip on self.kwargs in View.  That should work.  I'll 
>> rewrite my get().
>>
>> @James - No, no reason in particular.  Wasnt paying attention, I guess.  
>> I was just staring at the get() method in BaseListView and thinking, ah, 
>> this is the place I want to inject my filter form into the context.  Thanks 
>> for the heads up on the docs.
>>
>> Thanks for taking the time to respond.
>>
>>
>>
>> On Sunday, August 2, 2015 at 5:41:29 PM UTC-5, James Schneider wrote:
>>>
>>> Is there a reason you are using BaseListView rather than ListView? The 
>>> docs mention that BaseListView is not really meant to be used directly. 
>>> ListView also includes some extra context processing beyond the base class 
>>> that may be of use.
>>>
>>> -James
>>> On Aug 2, 2015 3:21 PM, "jordi collell"  wrote:
>>>
>>>> Not sure if i'm understanding what are you saying. But kwargs on get.. 
>>>> Are stored on a object property. Self.kwargs (prior the dispatch) method.
>>>>
>>>> --
>>>> You received this message because you are subscribed 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/5375c024-ee41-4b46-816d-e63fadb4a720%40googlegroups.com
>>>> .
>>>> For more options, visit https://groups.google.com/d/optout.
>>>>
>>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/a9d1ded2-4175-41ad-ad8e-22f48edb9677%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/a9d1ded2-4175-41ad-ad8e-22f48edb9677%40googlegroups.com?utm_medium=email&utm_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/214685fd-62ad-42ea-b69e-7b563e19018c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: BaseListView's get_context_data is missing kwargs?

2015-08-03 Thread Ken
@Jordi,  Thanks for tip on self.kwargs in View.  That should work.  I'll 
rewrite my get().

@James - No, no reason in particular.  Wasnt paying attention, I guess.  I 
was just staring at the get() method in BaseListView and thinking, ah, this 
is the place I want to inject my filter form into the context.  Thanks for 
the heads up on the docs.

Thanks for taking the time to respond.



On Sunday, August 2, 2015 at 5:41:29 PM UTC-5, James Schneider wrote:
>
> Is there a reason you are using BaseListView rather than ListView? The 
> docs mention that BaseListView is not really meant to be used directly. 
> ListView also includes some extra context processing beyond the base class 
> that may be of use.
>
> -James
> On Aug 2, 2015 3:21 PM, "jordi collell" > 
> wrote:
>
>> Not sure if i'm understanding what are you saying. But kwargs on get.. 
>> Are stored on a object property. Self.kwargs (prior the dispatch) method.
>>
>> --
>> You received this message because you are subscribed 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/5375c024-ee41-4b46-816d-e63fadb4a720%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/a9d1ded2-4175-41ad-ad8e-22f48edb9677%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


BaseListView's get_context_data is missing kwargs?

2015-07-31 Thread Ken
I created a class FilteredListView(BaseListView, FormMixin) so I can have a 
filter form in my list view.  The form submits filters via GET.  I have it 
working.  But there is a piece of the code that I feel ought to be handled 
by django.  In order to get the form into the context, I duplicated 
BaseListView.get() and changed the line

context = self.get_context_data()

to 

context = self.get_context_data(form=form)

BaseListView's get() accepts a kwargs but it is not used anywhere.  It 
seems to me that it should be passed to get_context_data() since it accepts 
a kwargs.  If it did, then I would only need to write a small get() method 
to instantiate (and optionally bind) the form, then call super with the 
appropriate kwargs argument to complete the get request processing.

Is there some reason why kwargs is not passed to get_context_data()?

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/0228628d-d979-47c1-a426-8d08922cabaa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Ken Nguyen
Hi Bernardo,

I appreciate the feedback.  I've heard of many ways to pass data between 
methods in views such as session, write to a file, or use formwizard.  It 
is still a problem accessing the session from the "cleaned_data"?  This is 
my first time hearing about query string, care to explain or giving me an 
example of how it works?  In the meantime, I'll read up on it.

Thanks,
Ken

P.S. - In some part of my code, you may notice the "location"parameter.  
You can ignore it or not include it in my code.  I was cut and paste so I 
didn't catch it. 

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


Re: How to Process Multi Step Forms in Django?

2015-05-05 Thread Ken Nguyen
I've finally figured it out after weeks of troubleshooting and here's how I 
do it.

In the original post, my views takes in the request from form1 and renders 
it to form2.  I would get the dreadful "Management Form Data is Missing" 
error no matter what I did and it led to asking a bunch of questions on 
here.  I decided to isolate the 2 forms to see if that rendered.  It took a 
few tries before getting both forms and templates to work separately.  What 
I noticed was form1.html's action was equal to "none" which was what I 
wanted.  It would render and posted the form with the errors to itself 
without redirecting to another page.  I then discovered that the address 
was still hooked to form1 instead of form2 after it had rendered.  In 
another word when form1 rendered the data to form2, the address was still 
on userinfo/form1.html when it should have been userinfo/form2.html in 
order for action to call the correct form in views.  The magic that I used 
to fix the issue was *HttpResponseRedirect*.  I saved the data retrieved 
from form 1 in a session and recovered it from beginning of form 2.  I used 
session to render data from form 2 instead of rendering directly from form 
1.

*Changes to form1 in views.py*

   - Save the data in a session for access in different part of views
   - Re-direct to form2 instead of render data from form1
   
def form1 (request):
...
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data

request.session ['names'] = data

return HttpResponseRedirect ('form2')
...

*Changes to form2 in views.py*

   - Retrieve data from session
   - Do something with data from form2.   For my case, I merged both 
   dictionary into one.

def form2 (request):

data = request.session ['names']
...
if checkbox_formset.is_valid ():
for i, form in enumerate (checkbox_formset.cleaned_data):
data [i].update (form)  # This will give me a list of name 
dictionary with the checkbox appended
  
  context = {'data': data}
return render (request, 'userinfo/success.html', context)
else:
checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')

 context = {'checkbox_formset': checkbox_formset, 'data': data, 
'location': location}
 return render (request, 'userinfo/form2.html', context)


*form2.html*





{% load staticfiles %}

Confirmation


Submitted Entries:
{% csrf_token %}

  
Firstname
Lastname
Location
Overwrite
Index
  
  {% for info in data %}
  
{{ info.first_name }}
{{ info.last_name }}
{{ location }}
{{ checkbox_formset.management_form }}


{{ forloop.counter0 }}
  
  {% endfor %}



Cancel





All there's left to do is create a template for success.html





Success


Submitted Entries:

{% for info in data %}
{{ info.first_name }} {{ info.last_name }} {{ 
info.overwrite }}
{% endfor %}

Add more names



Hope this will help some stragglers.  Nevertheless, thanks to Bernardo for 
helping me all along.

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


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen
Nevermind what I said on my last post, something is internally wrong with 
my second form.  It can't even render when I hard coded the first_name, 
last_name and the checkboxes.  Still getting Management Form Data is 
Missing.





{% load staticfiles %}

User Information


User Information:


{{ checkbox_formset.management_form }}




First Name
Last Name
Overwrite


John
Doe




John
Smith










Cancel





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


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen
Hi Bernardo,

Using your hidden method works.  I can see the "hidden" value from Form2 
but how do I use those hidden information in form2 so it can redisplay 
correctly?  First time around, it will use the variable from form1.  The 
second time around it should use the hidden information without the 
variable.  How do I achieve that?

You are correct!  I cannot carry the information to the second method in 
view having it the way it is so I've added the session under the 
cleaned_data of form1 and retrieved it at the beginning of form2.

data = name_formset.cleaned_data
request.session ['location'] = location
request.session ['data'] = data

Step 1:  Form1 - Display First Name, Last Name, and location Input Field
Step 2:  Once user submit the information, render the data to form2 and add 
the checkbox next to it.
Step 3:  User choose to select the overwrite checkbox and then click 
"Confirm".
Step 4:  Form2 in view checked for 'POST' method and process cleaned data 
or return empty form2.  This stage created a "Management Form is Missing 
Error" because of the variables that I used in form1 to create the form2 
template are no longer there.  The {{ checkbox_formset.management_form }} 
is already in the template.

Here you can see that the names are displaying correctly.  By the way, I 
made an error in my original post.  It was supposed to be "last_name" not 
"last_address".




form2.html
form2.html




{% load staticfiles %}

User Information


User Information:

{{ checkbox_formset.management_form }}



First Name
Last Name
Overwrite

{% for info in data %}



{{ info.first_name }}
{{ info.last_name }}


{% endfor %}





Cancel







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


Re: How to Process Multi Step Forms in Django?

2015-05-04 Thread Ken Nguyen


Thank you for the input.  I've already tried what you've suggested but 
still the same result, "Management Form Data is Missing."  It's not going 
to know the "first_name" and "last_name" the second time around since I 
have the variable

{{ info.first_name }} and {{ info.last_name }}

My* form2.html* currently looking like so:

{% for info in data %}



{{ info.first_name }}
{{ info.last_name }}


{% endfor %}


When you say inherit from form1 and just add the checkboxes, can you 
elaborate that?  How do I inherit it?  Do you mean just replicate the first 
form and add checkboxes to it?

Thanks,

Ken


On Saturday, May 2, 2015 at 1:24:22 PM UTC-7, Bernardo Brik wrote:
>
> You should add the same fields (first_name and address) to form2 and 
> render them with hidden inputs.
> You can try to make form2 inherit from form1 and just add the checkbox.
>
> On Friday, May 1, 2015 at 9:58:28 PM UTC-3, Ken Nguyen wrote:
>>
>> I've made some attempted to use formwizard but there wasn't much 
>> documentation about it so I decided to stay with the basic. I've 
>> successfully obtained and display the data from the first form to the 
>> second form and added some checkbox next to the data to allow user to 
>> choose whether to overwrite or ignore the duplicate data found in the 
>> backend process. The problem I have is the second form doesn't know how 
>> retrieve the data of the first form after hitting "Confirm" button. The 
>> form2.html template invalidated the data completely since it called itself 
>> again by the form action after submitting the data. Is there a way to solve 
>> this or a better approach to this?
>>
>> *forms.py*
>>
>> class NameForm (forms.Form): 
>> first_name = forms.CharField (required = False)
>> last_name = forms.CharField (required = False)
>>
>> class CheckBox (forms.Form):
>> overwrite = forms.BooleanField (required = False)
>>
>> views.py
>>
>> def form1 (request):
>>
>> NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, 
>> extra = 2, max_num = 5)
>>
>> if request.method == 'POST':
>>
>> name_formset = NameFormSet (request.POST, prefix = 'nameform')
>>
>> if name_formset.is_valid ():
>> data = name_formset.cleaned_data
>>
>> context = {'data': data}
>> return render (request, 'nameform/form2.html', context)
>> else:
>> name_formset = NameFormSet (prefix = 'nameform')
>>
>>  context = {..}
>>
>>  return render (request, 'nameform/form1.html', context)
>>
>> def form2 (request):
>>
>> CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)
>>
>> if request.method == 'POST':
>>
>> checkbox_formset = CheckBoxFormSet (request.POST, prefix = 
>> 'checkbox')
>>
>> if checkbox_formset.is_valid ():
>> data = checkbox_formset.cleaned_data
>>
>> context = {'data': data}
>> return render (request, 'nameform/success.html', context)
>>
>> else:
>> checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')
>>
>>  return HttpResponse ('No overwrite data.')
>>
>>
>>
>> *form2.html*
>>
>>
>> 
>> 
>> 
>> 
>> {% load staticfiles %}
>> 
>> User Information
>> 
>> 
>> User Information:
>> 
>> 
>> 
>> 
>> First Name
>> Last Name
>> Overwrite
>> 
>> {% for info in data %}
>> 
>> {{ info.first_name }}
>> {{ info.last_address }}
>> > value="1">
>> 
>> {% endfor %}
>> 
>> 
>> 
>> 
>> 
>> Cancel
>> 
>> 
>> 
>>
>>

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


How to Process Multi Step Forms in Django?

2015-05-01 Thread Ken Nguyen


I've made some attempted to use formwizard but there wasn't much 
documentation about it so I decided to stay with the basic. I've 
successfully obtained and display the data from the first form to the 
second form and added some checkbox next to the data to allow user to 
choose whether to overwrite or ignore the duplicate data found in the 
backend process. The problem I have is the second form doesn't know how 
retrieve the data of the first form after hitting "Confirm" button. The 
form2.html template invalidated the data completely since it called itself 
again by the form action after submitting the data. Is there a way to solve 
this or a better approach to this?

*forms.py*

class NameForm (forms.Form): 
first_name = forms.CharField (required = False)
last_name = forms.CharField (required = False)

class CheckBox (forms.Form):
overwrite = forms.BooleanField (required = False)

views.py

def form1 (request):

NameFormSet = formset_factory (NameForm, formset = BaseNodeFormSet, extra = 
2, max_num = 5)

if request.method == 'POST':

name_formset = NameFormSet (request.POST, prefix = 'nameform')

if name_formset.is_valid ():
data = name_formset.cleaned_data

context = {'data': data}
return render (request, 'nameform/form2.html', context)
else:
name_formset = NameFormSet (prefix = 'nameform')

 context = {..}

 return render (request, 'nameform/form1.html', context)

def form2 (request):

CheckBoxFormSet = formset_factory (CheckBox, extra = 2, max_num = 5)

if request.method == 'POST':

checkbox_formset = CheckBoxFormSet (request.POST, prefix = 'checkbox')

if checkbox_formset.is_valid ():
data = checkbox_formset.cleaned_data

context = {'data': data}
return render (request, 'nameform/success.html', context)

else:
checkbox_formset = CheckBoxFormSet (prefix = 'checkbox')

 return HttpResponse ('No overwrite data.')



*form2.html*






{% load staticfiles %}

User Information


User Information:




First Name
Last Name
Overwrite

{% for info in data %}

{{ info.first_name }}
{{ info.last_address }}


{% endfor %}





Cancel




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


Django BooleanField Checkbox Returns Empty

2015-04-29 Thread Ken Nguyen
I read every corner of the documentation but couldn't figure out why the 
BooleanField Form doesn't return 'True' when the checkbox is checked. Is 
this a valid test? Shouldn't formset.cleaned_data = [{True}, {False}]?



>>> from django import forms
>>> from django.forms.formsets import formset_factory
>>>
>>> class CheckBox (forms.Form):
...overwrite = forms.BooleanField (required = False)
...
>>>
>>> data = {
... 'form-TOTAL_FORMS': '2',
... 'form-INITIAL_FORMS': '0',
... 'form-MAX_NUM_FORMS': '3',
... 'checkbox-0-overwrite': True,
... 'checkbox-1-overwrite': False,
...}
>>>
>>> CheckboxFormSet = formset_factory (CheckBox)
>>> formset = CheckboxFormSet (data)
>>> formset.is_valid ()
True
>>> formset.cleaned_data
[{}, {}]
>>>


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


Reading Dynamic Checkbox in Django

2015-04-28 Thread Ken Nguyen
Hi Folks,

First time posting on here so if I violate any laws, please forgive me.  I 
also posted the same question 
on 
StackOverflow but didn't get any answers so I'm hoping this place will get 
more attention.

I'm having a hard time reading whether the checkbox is checked or not.  I 
created a formset with just the first_name and last_name since my initial 
page is only asking for those 2 information.  Once entered and validated, 
the next page will show a checkbox next to the duplicate names.

Here are the things that I've tried:

   - Changed the checkbox's name to iterate with the for-loop for 
   uniqueness.  (Regardless if I check the box or not, the results are always 
   the same {'overwrite': False}.)
   - Added the Boolean value with the first_name & last_name formset 
   (Result - 'ManagementForm data is missing or has been tampered with')

I think the problem lies with obtaining the 'POST' data.  Any help is much 
appreciated.


*Step 1*




*Step 2*



*Step 3* *- Output Expectation*

John Doe Location A 1 ("1" is checked)

James Smith Location A 0 ("0" is not checked)


*forms.py*

from django import forms
from django.forms.formsets import BaseFormSet


class UserInfo (forms.Form):

first_name = forms.CharField (max_length = 20, required = False)
last_name = forms.CharField (max_length = 20, required = False)
overwrite = forms.BooleanField (required = False)


class BaseUserInfoFormSet (BaseFormSet):

def clean (self):
if any (self.errors):
return

firstnames = []
lastnames = []
errors = []

for form in self.forms:
firstname = form.cleaned_data.get ('first_name')
lastname = form.cleaned_data.get ('last_name')

if ((firstname in firstnames) or (lastname in lastnames)) and 
len (errors) < 2:
errors.append ('First and/or last name must be unique')
if ((firstname == '') or (lastname == '')) and len (errors) < 2:
errors.append ('First and/or last name cannot be blanked')

firstnames.append (firstname)
lastnames.append (lastname)

if errors:
raise forms.ValidationError (errors)

return self.cleaned_data


#class DuplicateForm (forms.Form):
#overwrite = forms.BooleanField (required = False)

*views.py*

from django.shortcuts import render, render_to_response
from django.forms.formsets import formset_factory
from userinfo.forms import UserInfo
from userinfo.forms import BaseUserInfoFormSet
from userinfo.addName import webform


# Create your views here.
def addname (request):
UserInfoSet = formset_factory (UserInfo, formset = BaseUserInfoFormSet, 
extra = 2, max_num = 3)
if request.method == 'POST':
formset = UserInfoSet (request.POST)

if formset.is_valid ():
location = request.POST ['site']
names = formset.cleaned_data

request.session ['location'] = location
request.session ['names'] = names

for name in names:
firstname = name.get ('first_name')
lastname = name.get ('last_name')

if firstname and lastname:
webform (firstname, lastname, location)

context = {'names': names, 'location': location}
return render (request, 'userinfo/response.html', context)

else:
formset = UserInfoSet ()

context = {
'formset': formset,
'first_name_0': request.POST.get ('form-0-first_name', ''),
'last_name_0': request.POST.get ('form-0-last_name', ''),
'first_name_1': request.POST.get ('form-1-first_name', ''),
'last_name_1': request.POST.get ('form-1-last_name', ''),
}

return render (request, 'userinfo/addname.html', context)


def response (request):
location = request.session ['location']
names = request.session ['names']

UserInfoSet = formset_factory (UserInfo, formset = BaseUserInfoFormSet, 
extra = 2, max_num = 3)
if request.method == 'POST':
formset = UserInfoSet (request.POST)

if formset.is_valid ():
data = formset.cleaned_data
for duplicate in data:
overwrite = duplicate.get ('overwrite')

#if request.method == 'POST':
#form = DuplicateForm (request.POST)

#if form.is_valid ():
#data = form.cleaned_data

#for duplicate in data:
#overwrite = duplicate.get ('overwrite')


context = {'names': names, 'location': location, 'data': data}
return render (request, 'userinfo/results.html', context)

return render_to_response ('No valid data.')


*addname.html*





Add Name


 

Re: Template Not Applying - Django Polls Tutorial (Newbie Question)

2014-12-29 Thread Ken Wayne
That was it...

On Friday, December 26, 2014 4:45:13 PM UTC-6, Collin Anderson wrote:
>
> Hi,
>
> This one comes up a lot. It's confusing because {% block title %} is the 
> _html_ , the title of the browser tab.
>
> You want to change {% block branding %}.
>
> Collin
>
> On Tuesday, December 23, 2014 5:18:49 PM UTC-6, Ken Wayne wrote:
>>
>>  Hmmm, that is one of the directories I tried, 
>> C:\Python34\Scripts\mysite\templates\admin with the file base_site.html 
>>
>> On 12/23/2014 5:07 PM, Néstor wrote:
>>  
>>  You might need to make for admin
>>  mysite/templates/admin/base_site.html
>>  
>> for regular html files for the polls only
>>  mysite/polls/templates/polls/index.html
>>
>>  That is how I got it to work.  Good luck!!!
>>
>> :-)
>>  
>> On Tue, Dec 23, 2014 at 2:13 PM, Ken Wayne  wrote:
>>
>>>  Windows 8
>>>  Django 1.7.1
>>> Python 3.4.2
>>>  Google Chrome Version 39.0.2171.95 m
>>>
>>>  Bottom of part 2 of the the tutorial 
>>> https://docs.djangoproject.com/en/1.7/intro/tutorial02/ it indicates 
>>> how to customize the admin template but when I follow the directions it 
>>> doesn't show any change in my browser.  I've restarted the development 
>>> server and refreshed my browser. 
>>>
>>>  *File Snip base_site.html:*
>>>  {% block title %}{{ title }} | Polls Administration {% endblock %}
>>>  
>>>  *File Snip settings.py:*
>>>  import os
>>> BASE_DIR = os.path.dirname(os.path.dirname(__file__))
>>> # TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
>>> TEMPLATE_DIRS = ['C:\Python34\Scripts\mysite\templates']
>>>  
>>>  I tried the environment path, and hard coding the path.  Since the 
>>> tutorial didn't indicate the BASE_DIR path I made a copy of the file in 
>>> each of the following directories:
>>> C:\Python34\Scripts\mysite\templates\admin
>>>  C:\Python34\Scripts\mysite\mysite\templates\admin
>>>  C:\Python34\Scripts\mysite\polls\templates\admin
>>>  
>>>  Any thoughts on what I might be doing wrong?
>>>  -- 
>>> You received this message because you are subscribed 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/0a7c4e30-ba26-418b-b217-72936c72975f%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/django-users/0a7c4e30-ba26-418b-b217-72936c72975f%40googlegroups.com?utm_medium=email&utm_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/CAON-vCPcGEhk3%2B0wO4RXSnuQWqW5H6H4ZbiHoo1h5yRx36GbBQ%40mail.gmail.com
>>  
>> <https://groups.google.com/d/msgid/django-users/CAON-vCPcGEhk3%2B0wO4RXSnuQWqW5H6H4ZbiHoo1h5yRx36GbBQ%40mail.gmail.com?utm_medium=email&utm_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/7c710aea-10a9-4f45-9c1e-29fc78db0476%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Template Not Applying - Django Polls Tutorial (Newbie Question)

2014-12-23 Thread Ken Wayne
Hmmm, that is one of the directories I tried, 
C:\Python34\Scripts\mysite\templates\admin with the file base_site.html


On 12/23/2014 5:07 PM, Néstor wrote:

You might need to make for admin
mysite/templates/admin/base_site.html

for regular html files for the polls only
mysite/polls/templates/polls/index.html

That is how I got it to work.  Good luck!!!

:-)

On Tue, Dec 23, 2014 at 2:13 PM, Ken Wayne <mailto:ecommg...@gmail.com>> wrote:


Windows 8
Django 1.7.1
Python 3.4.2
Google Chrome Version 39.0.2171.95 m

Bottom of part 2 of the the tutorial
https://docs.djangoproject.com/en/1.7/intro/tutorial02/ it
indicates how to customize the admin template but when I follow
the directions it doesn't show any change in my browser.  I've
restarted the development server and refreshed my browser.

*File Snip base_site.html:*
{% block title %}{{ title }} | Polls Administration {% endblock %}

*File Snip settings.py:*
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
TEMPLATE_DIRS = ['C:\Python34\Scripts\mysite\templates']

I tried the environment path, and hard coding the path.  Since the
tutorial didn't indicate the BASE_DIR path I made a copy of the
file in each of the following directories:
C:\Python34\Scripts\mysite\templates\admin
C:\Python34\Scripts\mysite\mysite\templates\admin
C:\Python34\Scripts\mysite\polls\templates\admin

Any thoughts on what I might be doing wrong?
-- 
You received this message because you are subscribed to the Google

Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it,
send an email to django-users+unsubscr...@googlegroups.com
<mailto:django-users+unsubscr...@googlegroups.com>.
To post to this group, send email to django-users@googlegroups.com
<mailto: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/0a7c4e30-ba26-418b-b217-72936c72975f%40googlegroups.com

<https://groups.google.com/d/msgid/django-users/0a7c4e30-ba26-418b-b217-72936c72975f%40googlegroups.com?utm_medium=email&utm_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 
<mailto:django-users+unsubscr...@googlegroups.com>.
To post to this group, send email to django-users@googlegroups.com 
<mailto: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/CAON-vCPcGEhk3%2B0wO4RXSnuQWqW5H6H4ZbiHoo1h5yRx36GbBQ%40mail.gmail.com 
<https://groups.google.com/d/msgid/django-users/CAON-vCPcGEhk3%2B0wO4RXSnuQWqW5H6H4ZbiHoo1h5yRx36GbBQ%40mail.gmail.com?utm_medium=email&utm_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/5499F84E.1060109%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Template Not Applying - Django Polls Tutorial (Newbie Question)

2014-12-23 Thread Ken Wayne
Windows 8
Django 1.7.1
Python 3.4.2
Google Chrome Version 39.0.2171.95 m

Bottom of part 2 of the the 
tutorial https://docs.djangoproject.com/en/1.7/intro/tutorial02/ it 
indicates how to customize the admin template but when I follow the 
directions it doesn't show any change in my browser.  I've restarted the 
development server and refreshed my browser.

*File Snip base_site.html:*
{% block title %}{{ title }} | Polls Administration {% endblock %}

*File Snip settings.py:*
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
TEMPLATE_DIRS = ['C:\Python34\Scripts\mysite\templates']

I tried the environment path, and hard coding the path.  Since the tutorial 
didn't indicate the BASE_DIR path I made a copy of the file in each of the 
following directories:
C:\Python34\Scripts\mysite\templates\admin
C:\Python34\Scripts\mysite\mysite\templates\admin
C:\Python34\Scripts\mysite\polls\templates\admin

Any thoughts on what I might be doing wrong?

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


Poll Tutorial (for Django 1.7) Files Available?

2014-12-22 Thread Ken Wayne
I'm trying to work through the Poll Tutorial and I've run into some 
problems.  I'd like to compare the code I've written to a working file.  Is 
there any place to download the entire working project?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.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/26f1c16c-865c-43a6-910e-5dd90beb22bb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-18 Thread Ken Winter
OK, I've written and unit-tested the database components - see 
https://drive.google.com/file/d/0B-thboqjuKZTSjRHTXhqMlo3RlU/view?usp=sharing.  
Now I could use a little advice on the Django part.

I believe that all that is needed is to have the app call the DB function 
set_session_user() while logging in the user, passing it the user id.  I 
guess my questions are:


   1. Where to put this call? - i.e. in what Django module and function?
   2. How to make the call? - Is it just executing a SQL statement like 
   "SELECT set_session_user()", or is there a better way?

~ Tx again, Ken

On Friday, October 17, 2014 5:46:05 PM UTC-6, Ken Winter wrote:
>
> Thanks again Carl (and others) ~
>
> I agree wıth you that the "DB users" approach seems the most promısıng.  
> It's the one I will pursue, and certainly glad to share the code when I 
> have some worth sharing - and quite likely I'll have some more questions 
> before that, as I try to implement this idea.  
>
> As it happens, I'm leaving on a trip tomorrow, so it may be a while for my 
> next communiqué on this matter.  But I'll be back!
>
> ~ Ken
>

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


Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-17 Thread Ken Winter
Thanks again Carl (and others) ~

I agree wıth you that the "DB users" approach seems the most promısıng.  
It's the one I will pursue, and certainly glad to share the code when I 
have some worth sharing - and quite likely I'll have some more questions 
before that, as I try to implement this idea.  

As it happens, I'm leaving on a trip tomorrow, so it may be a while for my 
next communiqué on this matter.  But I'll be back!

~ Ken

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


Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-17 Thread Ken Winter
To keep this conversation fairly modular, I'm responding to different 
possible solutions in different posts.  This one is about Carl's comments 
on:

>  2. Have Django create a new *database user *for each session login, 
> using the user id that Django knows and that I want to record in the 
> last_updated_by column, and establish a new database connection with 
> that user as the user. Then the database would know the user and 
> could record it in the last_updated_by column for every update in 
> that session.  At logout, the database user would be dropped.  Do 
> you think a Django app could be programmed to handle the creation 
> and dropping of this user, and to establish a db connection for that 
> user?  I will also put this proposal to a PostgreSQL forum to see if 
> they think it would work on the database end. 

My comments inserted below are prefaced with "Ken:"

On Thursday, October 16, 2014 12:13:20 PM UTC-4, Carl Meyer wrote:

I think this is probably technically possible (though I don't see why 
> you'd drop the database user when they logout, better to keep the 
> account around for their next login). I also expect it will be quite a 
> tough slog, take weeks or more likely months to get working reliably, 
> and require you to become an expert on the internals of the Django ORM. 
> I also think it's the only feasible path to your "universal and magic" 
> goal. 
>
> (Here's a blog post where someone tried this and apparently got it 
> working, though I see at least three things they did along the way that 
> are terrible hacks and either insecure or quite likely to break: 
>
> http://blog.everythingtastesbetterwithchilli.com/2010/02/07/per-user-database-authentication-in-django-/)
>  
>
>

Ken: Thanks for this link.  What the author of that post did is similar to 
what I had in mind, tho my requirement is more modest than his.  He wants 
to have the database actually handle the authentication.  I'm OK having 
Django authenticate its users; I just want to communicate their user-ids to 
the database with each query.

Ken: My idea for doing this goes something like:

   1. For every session, let's say that the Django app's database 
   connection is with a user I'll call "myapp" here.  User "myapp" has the 
   CREATEUSER privilege.
   2. Someone requests a page from the app.  They're not logged in yet, so 
   they get the login page.
   3. The app handles authentication in usual Django fashion.  
   4. When the user has been authenticated, the app: 
   1. Checks whether a database user already exists named , where 
   is the user just authenticated by the app, and hence is that 
  value that we want to have recorded in the last_update_by columns.  
  2. If not, creates a  user.  
  3. Issues the SQL command: SET SESSION AUTHORIZATION ''. 
  5. In the database, all user tables have an ON UPDATE trigger that 
   assigns the PostgreSQL system variable *current_user *to* 
   last_updated_by* for each row that was updated.  
   6. Because the SET SESSION AUTHORIZATION command was executed, 
   *current_user* evaluates to  throughout this session.  So * 
   last_updated_by* gets set as required.  An added benefit is that the 
   permissions applicable throughout the session are those of , and 
is an ordinary end user without any admin permissions.  So a 
   certain kind of possible destructive mischief or bumbling is prevented.

Ken: Here are the aspects of this scheme that I'm more and less confident 
about:

   1. I'm fairly confident that steps 1-3 are OK, because I think that's 
   normal Django process.
   2. I'm less confident about step 4, because I'm not very fluent with how 
   Django handles actions like this.
   3. I'm confident that this will work at the DB level, i.e. that steps 
   5-6 will work fine once step 4 has been accomplished.  I'm fluent with 
   PostgreSQL, and I've unit-tested these bits.
   
Ken: I'd appreciate comments and suggestions about any and all parts of 
this approach.

Ken: If it *is* feasible, this does satisfy my criteria of being 
"universal" (all DB updates thru the Django app, whether thru object model 
save() or raw SQL or whatever, would appropriately set last_updated_by) and 
"magic" (once the login process is programmed to do step 4, last_updated_by 
would be properly set without any action of the developer who programs each 
update action).

Ken: Thanks again!

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

Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-17 Thread Ken Winter
To keep this conversation fairly modular, I'm responding to different 
possible solutions in different posts.  This one is about Carl's comments 
on:

>  1. Stick some code into the database connector, as I described in 
> possibility 1 of my original post.  I guess the connector would be 
> the "connection" class? 

My commenst inserted below are prefaced with "Ken:"

On Thursday, October 16, 2014 12:13:20 PM UTC-4, Carl Meyer wrote:


> I don't see any way this is feasible, if you want it to cover raw SQL 
> executed through ``cursor.execute``. Are you planning to parse the SQL 
> for every raw statement, 


*Ken: Yes.*
 

> figure out if its an INSERT or UPDATE, 


*Ken: Yes.*
 

> and then 
> figure out which row(s) it might affect? 


Ken: No; at this point my code inserts an element that assigns the user id 
to "last_updated_by" into the SET clause of an UPDATE query or the VALUES 
clause of an INSERT query, then hands the modified query back to the 
connector, which passes it on to the DB.

At this point you're well into 
re-implementing chunks of PostgreSQL in your app code. 


Ken: No, just a modest bit of parsing and tweaking of SQL queries.  My code 
doesn't have to execute the queries in any way.

Ken: Here's how I did it back in the dark ages, when Zope rather than 
Django was my framework: 
https://drive.google.com/file/d/0B-thboqjuKZTNG9DR3lqalJaOWM/view?usp=sharing.  
The db.py module is the query pathway of the ZPsycopgDA adapter.  I have 
changed this out-of-the-box Zope module only by adding the lines I have 
enclosed here in "ADDED: << ... >>" delimiters.  I have added the whole 
_insert_when_who_updates() function, three lines invoking it from the 
query() function, and a few import lines.

Ken: So to implement this in Django, one would have to find the Django 
counterpart of ZPsycopgDA.db.py and insert this code in the same way.

Ken: Whaddya think?
<https://drive.google.com/file/d/0B-thboqjuKZTNG9DR3lqalJaOWM/view?usp=sharing>

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


Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-15 Thread Ken Winter
Thanks, Collin, Carl, & Tom ~

Is this a reasonable summary of what you have said so far?:

   1. You've suggested two solutions, which I'll call "middleware" (from 
   Collin) and "save() argument" (from Carl and Tom).
   2. A limitation of both is that they aren't what I'll call "universal".  
   That is, they only work when the update is done with the save() method of a 
   Django data model object (or perhaps with other methods that unleash DB 
   actions, such as update(), that could be customized)in a similar way).  
   Other ways of doing a DB update action - ways that don't go thru save()or 
   other such methods - would fail to set last_updated_by.  Questions: What 
   are these "other ways"?  Do they include "raw SQL" as discussed in 
   https://docs.djangoproject.com/en/dev/topics/db/sql/, using 
   Manager.raw() or cursor.execute()?  Are there any other "other ways"? 
   3. The difference between the "middleware" and "save() argument" 
   solutions is that "middleware" is "magic", i.e totally invisible to the 
   developer, where "save() argument" is not.

I'm a relative newbie to Django, so I'm trying to get clear that I'm 
understanding you.

Assuming that my understanding isn't too far off, let me say that I'm 
looking for a solution that is "universal" and "magic".  (And I'm willing 
to live with the risks of "magic").  I think this requires a solution at a 
deeper level of middleware ("deeper" meaning closer to the DB and farther 
from app code), some level that *all *DB update actions go through.  

Let me float two more not-even-half-baked ideas for your comments:

   1. Stick some code into the database connector, as I described in 
   possibility 1 of my original post.  I guess the connector would be the 
   "connection" class?
   2. Have Django create a new *database user *for each session login, 
   using the user id that Django knows and that I want to record in the 
   last_updated_by column, and establish a new database connection with that 
   user as the user. Then the database would know the user and could record it 
   in the last_updated_by column for every update in that session.  At logout, 
   the database user would be dropped.  Do you think a Django app could be 
   programmed to handle the creation and dropping of this user, and to 
   establish a db connection for that user?  I will also put this proposal to 
   a PostgreSQL forum to see if they think it would work on the database end.
   
~ Tx, Ken




On Tuesday, October 14, 2014 11:46:40 AM UTC-4, Collin Anderson wrote:
>
> Hi Ken,
>
> If you _really_ want it to be automatic, I think your best bet is to use a 
> middleware to store the user or request object in a "thread local" 
> variable, and then have a pre_save signal set the last_updated_by field 
> based on that. That method is frowned upon, but should work. (If you're 
> doing "green" threading, it may break.) The pre_save signal could error, or 
> something if it is not able to determine the request (like in the 
> command-line case).
>
> Thanks,
> Collin
>
>

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


Incremental inspectdb, anyone?

2014-10-15 Thread Ken Winter
Is there a Django utility or add-on that can read database schemas and turn 
them into Django data models *incrementally*? 

By "incrementally", I mean that the utility would be able to update a set 
of already existing Django models so they match the current DB schema.  In 
other words, the utility would incorporate changes to the schema that have 
been made at the DB level into the Django model set.

It seems to me that this utility would have some or all of the following 
level of functionality, which I list in increasing order of difficulty:

1. Inspect a DB schema and create a Django model for every table in it.  
This is what inspectdb does.  It's fine for initializing a Django app that 
doesn't already contain any data models.  Level 1 functionality is easiest 
to implement, because the utility doesn't have to look at the existing 
model set at all.

2. Inspect a DB schema and create a Django model for user-selected tables 
in the schema.  This extension seems easy to implement, as the utility 
still doesn't have to inspect the existing model set.  Adding level 2 
functionality would be a big help for those of us who need to evolve our DB 
schema directly at the DB level and then create-modify Django models to fit 
the DB, rather than vice-versa.  For us, a level 1 utility is good only for 
a one-time run when initializing the model set of a brand-new app.  A level 
2 utility would spare us the error-prone and labor-intensive effort of 
creating subsequent models by hand.  (As someone suggested elsewhere in 
this forum, it is possible to run inspectdb and then lop out the 
pre-existing models from its output file before adding the rest of them to 
the model set, but this is at best rather clunky.)  

3. Inspect a DB schema and create a Django model for every table in the 
schema that doesn't already have a model in the existing model set.  Harder 
to implement, because now the utility has to compare the schema with the 
model set - albeit at a quite coarse level:  all it needs to ask is "Does 
this table already have a model or not?"  Level 3 functionality would shave 
off some additional work, leaving only the altering and deleting of 
pre-existing models (and the impact of those changes on code) to be done by 
hand.

4. Inspect a DB schema and modify the Django model set so that they match 
completely.  Much harder, because it involves (a) comparing every detail of 
each existing model with the DB schema, (b) altering and deleting models as 
well as just creating them, and (c) dealing with the problems that these 
alterations and deletions may cause for existing app code.  The last point 
in particular is a big hurdle.  So level 4 functionality may not be worth 
the effort - but if someone has already gone to the trouble of building it, 
great to have!

So my question is:  Has anybody built something that provides functionality 
beyond level 1?  If so, where is it and what can it do?

~ TIA, Ken

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


How to "automatically " populate "last_updated_by" DB columns with the current user's id

2014-10-13 Thread Ken Winter
 

I'm building a Django app that will work against a pre-existing PostgreSQL 
database.  Every user data table in my DB has an auditing column called 
last_updated_by.  The requirement I need to meet is that every time an 
UPDATE is run against a table, that column is automatically set to the id 
of the logged-in user.

By "automatically", I mean that this is done without any effort (or choice) 
on the part of the Django developer who writes an UPDATE (either as a SQL 
query or as an update on a Django object representing a row of that table) 
on a particular user data table.

For example (from https://docs.djangoproject.com/en/1.7/topics/db/queries/), 
the declarer of the Blog class, which corresponds to the blog table, can 
declare the class as:

class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()

and a developer can write an update as:

>>> b5.name = 'New name'>>> b5.save()

Neither the declarer or the developer gave a thought to the last_updated_by 
column.  But when logged-in user 12345 causes this code to execute, the 
blog.last_updated_by column of that row will be set to 12345.

The nub of this problem is that when the database receives an UPDATE query, 
that query does not identify the Django end user that caused the query to 
be submitted.  The DB contains a list of the users (auth_user), and my DB 
also contains a list of the currently active user sessions (and the 
logged-in user of each session).  But multiple users can be logged in at 
once, and there is no way for the DB to deduce which of them issued this 
particular update.  The fact that this update came from user 12345 is known 
only within the Django app.  

So the problem is:  How to get this info from the app to the database, 
without requiring the developer to put this bit of housekeeping explicitly 
into every update?

Three possibilities have occurred to me:

1. A decade ago, when I was using the Zope framework, I found the Zope 
module (called a database connector) that actually formulates the SQL query 
strings en route from Zope apps to the DB.  I wrote a routine that inserts 
"last_updated_by = " into the 
SET clause of each UPDATE query, and called this routine from the Zope 
database connector code.  This worked.  But it's an ugly hack and, worse, 
involves tinkering with the framework's DNA, so it would not have survived 
the next version of the database connector module.

2. Could this be done by defining last_updated_by in an abstract base 
class, as in https://docs.djangoproject.com/en/1.7/topics/db/models/, that 
includes an update method that automatically assigns the user id to 
last_update_by for each update?

3. Or could it be done with a modified Manager, with a modified QuerySet (
https://docs.djangoproject.com/en/1.7/topics/db/managers/)?
Not sure if this is relevant, but let me add that in the PostgreSQL 
database, the last_updated_by column is in all user data tables because 
their CREATE TABLE definitions all include an "INHERITS FROM when_and_who" 
clause, where when_and_who is the table that actually contains the 
last_updated_by column.  I'm not sure if Django's inspectdb utility makes 
any use of INHERITS FROM.

Thanks in advance for any suggestions you have for meeting this requirement!

~ Ken

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


Re: django templates and tex/latex

2013-03-13 Thread Ken
Actually, that's exactly what I'm trying to do.  I have database tables 
whose
columns contain TeX fragments.  I am trying to generate various file outputs
from database searches - TeX, pdf, etc.

I could construct the tex file on the fly with python strings as you 
suggest but
that's rather cumbersome.  It's simpler with a template.

I've also considered using the xml.element api to construct my own template
but that would set me back several weeks.  I'm trying to finish. :/

I have something that almost resembles a template.  It is not the most 
flexible
or elegant but it works.  I have a single replacement string between
\begin{document} and \end{document} and I simply replace this one token 
with a
string.replace()



On Wednesday, March 13, 2013 11:39:18 AM UTC-5, Drew Ferguson wrote:
>
> On Wed, 13 Mar 2013 07:01:45 -0700 (PDT) 
> Ken > wrote: 
>
> > I would like to write a tex/latex file with django tags in it.  Load it 
> > with the template loader and render it with a context.  The problem is 
> > that my tex/latex file has quite a few '{%' in them.   They are 
> > conventional in TeX for writing readable macros and are used to escape 
> > the newline.  I could try rewriting them but before I do, I thought I'd 
> > ask if this is even worth tackling.  TeX uses curly braces as grouping 
> > and percent signs as a comment.   
> > 
> > The TeX file would look rather confusing but the more important question 
> > is what the loader does when it sees braces and brace comments.  Is it 
> > possible to reassign the block and variable tags? 
> > 
> > Thanks 
> > 
> > 
>
> I have done this in the past (with Plone rather than django) by calling a 
> python wrapper script to generate a file which latex can process; 
> essentially construct the Latex source as python strings 
> and have the script assemble the components you want. The objective was to 
> generate a PDF file by Latex with variables fed from SQL & a web page. But 
> this may not be what you are interested in. 
>
> Are you trying to render a Latex source document as a web page? 
>
> -- 
> Drew 
>

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




django templates and tex/latex

2013-03-13 Thread Ken
I would like to write a tex/latex file with django tags in it.  Load it 
with the template loader and render it with a context.  The problem is that 
my tex/latex file has quite a few '{%' in them.   They are conventional in 
TeX for writing readable macros and are used to escape the newline.  I 
could try rewriting them but before I do, I thought I'd ask if this is even 
worth tackling.  TeX uses curly braces as grouping and percent signs as a 
comment.  

The TeX file would look rather confusing but the more important question is 
what the loader does when it sees braces and brace comments.  Is it 
possible to reassign the block and variable tags?

Thanks


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




getting same order in SQL as ManytoMany selection in Admin

2013-01-30 Thread Ken Ricci
I have a Django/Grappelli admin form for job postings which has a 
manytomany relationship for job requirements (using filter_horizontal).  In 
the admin form, the order chosen stays constant when I save the job posting 
and display it again later.  I'm trying to repeat the order in another app 
that selects the job requirements using the join table, but no matter which 
column I ORDER BY (or even if I don't use an ORDER BY) in the SQL, I cannot 
get the same order of job requirements as displayed in the admin form.

Any idea how the chosen items retain their selected order?

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




Re: Implementing a monitoring system with django.

2012-12-12 Thread Ken Hill
I've been considering a very similar Django to help simplify some of my 
daily server system admin tasks (e.g. monitor and trend CPU uase, memory 
usage, disk space, etc.). I'd like to try CouchDB to store the data with a 
Django UI to make the app usable to non-technical users.

On Monday, December 10, 2012 11:41:14 AM UTC-8, Marc Aymerich wrote:
>
> Hi, 
> I'm considering to implement a simple monitorization system that 
> basically gathers some data from a set of nodes (<1000 nodes). The 
> gathered data should be stored in order to let users perform some 
> queries and maybe also generate some graphs. 
>
> I'm looking for advice in what components are best suited for each of 
> the following parts: 
>
> 1) Storage: maybe something nonsql like MongoDB? or perhaps RRD? 
> 2) Data gathering: celery periodic tasks? 
> 3) Graphs: rrd? or some java script framework for graphing? 
>
> thanks for your comments!! 
> -- 
> Marc 
>

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



Re: What persists in memory across requests?

2012-05-18 Thread Ken J
Thanks for the suggestions.

I have been using pgbouncer for awhile, and while it helps with the
issue of setup/tear down of postgres processes, it still leaves the
overhead of a socket setup/tear down between the django app and the
pgbouncer process.  Because almost every django request I have uses
the DB, I don't mind "wasting" a DB connection on the few that don't
touch the DB.

I dug into the django 1.3 code today and found that
BaseDatabaseWrapper is as you say, storing everything in thread local
storage including the db connection.  I also answered my own question
of how modules are cached in python.  Apparently, once a module has
been imported in any way, the module remains loaded, and can be
accessed through sys.modules by any thread if you so choose.  Any
globals defined in any loaded module remain in memory.

At the end of the day, I don't mind if there is simply a 1-to-1
mapping between django threads (spread over multiple processes even),
and DB connections.  I don't wish or requiring pooling strictly, I was
only looking into using a pool to work around the issue I have found
of DB connections being leaked if you disable the db connection close
after every request.  Ultimately, if I could find the source of this
leak, I would be a happy camper.

I know it sounds like I'm screwing around with a case of "premature
optimization" and all, but I've done a good amount of load testing
against our service, with the number of concurrent connections we
expect to see, and persistent DB connections do seem to make a
dramatic difference.  Over the course of tens going on hundreds of
thousands of requests, it can save mins worth of processing time.

On May 18, 1:52 pm, akaariai  wrote:
> On May 18, 7:54 pm, Ken J  wrote:
>
>
>
>
>
>
>
>
>
> > I'm quite curious as to what persists in memory across requests in
> > terms of django application variables.  I'm currently running a django
> > app in mod_wsgi daemon mode.
>
> > Because of performance concerns when dealing with large numbers of
> > concurrent requests, I wanted to modify django to keep persistent DB
> > connections to Postgres using a connection pool.
>
> > This in turn got me wondering, how can I persist a thread pool, or
> > even a simple DB connection, across requests?  I realize anything that
> > is global to the wsgi entry point script will persist.  The current
> > wsgi entry point I'm using is something like:
>
> > import django.core.handlers.wsgi
>
> > _application = django.core.handlers.wsgi.WSGIHandler()
>
> > def application(environ, start_response):
> >     return _application(environ, start_response)
>
> > Obviously _application will remain, but since code modules are
> > dynamically loaded based on URL resolvers, would the view/model/db
> > connection not be destroyed once the variables referencing said
> > objects go out of scope?
>
> > From logging statements, it has become apparent I can in fact make DB
> > connections persistent simply by not closing the DB connection after
> > the request has finished.  Unfortunately, I also found this to slowly
> > leak socket connections to the DB eventually making it so that I can't
> > log into the DB, hence why I was looking into a connection pool.
>
> > Anyways, I was hoping someone could shed some light as to the
> > internals of python/django on why django/db/__init__.py is able to
> > reference persistent connections.
>
> > My best guess is that because
>
> > connections = ConnectionHandler(settings.DATABASES)
>
> > is at the top level of a module, it remains held within the python
> > interpreter after being imported, thus holding a reference.
>
> > Any insight would be greatly appreciated.
>
> First, you should look into external connection poolers. PgBouncer is
> excellent if you need just a connection pool. Pg-pool II is another
> option, but it provides way more than just a connection pool.
>
> If you would like to implement a connection pool in Python code, it
> isn't the easiest thing to do. If you are using Django 1.4, then the
> connections object will be thread local - that is, it provides a
> different connection for each thread. Note that if you are using
> multiple processes (instead of threads) then the processes share
> nothing between each other. This is the reason you should look for
> external poolers - they can see all connection attempts
> simultaneously, but Python poolers are restricted to seeing one
> processes at a time.
>
> Still, if you want to experiment on poolers in Python code, I have
> written a couple of attempts for a connection pool you can use as
> bases of your work.https://git

What persists in memory across requests?

2012-05-18 Thread Ken J
Howdy,

I'm quite curious as to what persists in memory across requests in
terms of django application variables.  I'm currently running a django
app in mod_wsgi daemon mode.

Because of performance concerns when dealing with large numbers of
concurrent requests, I wanted to modify django to keep persistent DB
connections to Postgres using a connection pool.

This in turn got me wondering, how can I persist a thread pool, or
even a simple DB connection, across requests?  I realize anything that
is global to the wsgi entry point script will persist.  The current
wsgi entry point I'm using is something like:

import django.core.handlers.wsgi

_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
return _application(environ, start_response)

Obviously _application will remain, but since code modules are
dynamically loaded based on URL resolvers, would the view/model/db
connection not be destroyed once the variables referencing said
objects go out of scope?

>From logging statements, it has become apparent I can in fact make DB
connections persistent simply by not closing the DB connection after
the request has finished.  Unfortunately, I also found this to slowly
leak socket connections to the DB eventually making it so that I can't
log into the DB, hence why I was looking into a connection pool.

Anyways, I was hoping someone could shed some light as to the
internals of python/django on why django/db/__init__.py is able to
reference persistent connections.

My best guess is that because

connections = ConnectionHandler(settings.DATABASES)

is at the top level of a module, it remains held within the python
interpreter after being imported, thus holding a reference.

Any insight would be greatly appreciated.

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



templates couple apps to a site; how do you separate them?

2012-03-13 Thread Ken
I'm struggling with how I should go about writing "pluggable" apps.  I
haven't found a satisfactory way of decoupling apps from a site and
the primary sticking point is templates.  I've combed through some
discussions but have not found any that have helped.

A site's templates determine the look and feel.  If an app is to play
nice, then it needs to know a site's templates.  If an app uses its
own templates, then it can override the site's look and feel.

One approach is for an app to provide only functionality.  A site that
uses an app then has the responsibility of developing views for an app
it chooses to use.  This seems to me the best way forward.

How do you go about solving this problem?

Thanks.



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



Re: runserver namespace problem?

2011-11-13 Thread Ken
Does anybody have any idea?

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



runserver namespace problem?

2011-11-10 Thread Ken
hi all

   I have a django website dir tree like this:

mysite - app1 - tasks.py
 - tests.py
 - views.py
 - models.py

there is a function  *outprint* in tasks.py

In shell one, I use command "python manage.py celeryd -B -l info" to run
celery in beat mod.

In shell two, when I use "python manage.py shell" and call
outprint.delay(), shell one show the task  "app1.tasks.outprint" is
accepted and processed.

But when I run "python manage.py runserver 0.0.0.0:8080" in shell two, and
call outprint.delay() in a view function,  celery said "Received
unregistered task of type 'mysite.app1.tasks.outprint'."

It seems that when I run my django site using "python manage.py runserver",
all the package name have a "mysite." prefix.

I wonder what is the right way to deal with this kind of namespace problem?

Best wishes,
Kenneth Tse
Email: xie.kenn...@gmail.com
Twitter: kenneth_tse

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



Re: model: how to reference to the model itself?

2011-10-23 Thread Ken
oh, I found the answer:

use ForeignKey('self') to a many-to-one ref to model self

please ignore my former post. >_<

On 10月24日, 下午12时47分, Ken  wrote:
> I want to create a parent-child like catalog system.
>
> from django.db import models
>
> class Catalog(models.Model):
> username = models.EmailField()
> name = models.CharField(max_length=64)
> color = models.CharField(max_length=20)
> state = models.IntegerField()
> parentcatalog = models.ManyToOneRel(Catalog)
>
> but when syncdb i got:
>   File "/home/ken/sites/mysite/catalog/models.py", line 12, in Catalog
> parentcatalog = models.ManyToOneRel(Catalog)
> NameError: name 'Catalog' is not defined
>
> It seems like I cannot ref to a model which is not completely defined.
> What should I do?

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



model: how to reference to the model itself?

2011-10-23 Thread Ken
I want to create a parent-child like catalog system.

from django.db import models

class Catalog(models.Model):
username = models.EmailField()
name = models.CharField(max_length=64)
color = models.CharField(max_length=20)
state = models.IntegerField()
parentcatalog = models.ManyToOneRel(Catalog)

but when syncdb i got:
  File "/home/ken/sites/mysite/catalog/models.py", line 12, in Catalog
parentcatalog = models.ManyToOneRel(Catalog)
NameError: name 'Catalog' is not defined

It seems like I cannot ref to a model which is not completely defined.
What should I do?

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



load-on-startup equivalent in django?

2011-10-20 Thread Ken
Hello all
I'm new to django and I have a question.

I want to find a way to run some code periodicly in the background.
Because I have a fax device which will put incoming call data in the
database, I scan the database each 3 minutes for new incomings.

In tomcat when I can make a servlet load on startup. I add
"0"  in the web.xml file. This servlet
will be autoloaded when tomcat started and I then started the 3-min rountine
repeatly.

I wonder how do I do the same in django framework. Or there is some
other way to run some background code periodicly?


Thank you in advance.

    Ken

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



Re: creating dynamic forms with django

2011-07-20 Thread ken paul
Hey you know the link actually has what I want thanks
Kenneth


On Wed, Jul 20, 2011 at 3:27 PM, ken paul  wrote:

> Thank man but what I mean is like you create a dynamic class
> ||new_class=type('myform',(forms.Form),{attrib})|| but the dict with attribs
> is a bit complex coz the form attributes have there own attributes and
> widgets
> Kenneth
>
>
>
> On Wed, Jul 20, 2011 at 1:00 PM, NISA BALAKRISHNAN <
> snisa.balakrish...@gmail.com> wrote:
>
>> may be dis link helps u:
>>
>> http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/
>>
>> On Wed, Jul 20, 2011 at 12:46 PM, ken paul  wrote:
>>
>>> hey can anyone get a way of writing dynamic form classes with django. I
>>> have tried but putting the attributes became a bit hard.
>>> Kenneth
>>>
>>> --
>>> You received this message because you are subscribed to the Google Groups
>>> "Django users" group.
>>> To post to this group, send email to django-users@googlegroups.com.
>>> To unsubscribe from this group, send email to
>>> django-users+unsubscr...@googlegroups.com.
>>> For more options, visit this group at
>>> http://groups.google.com/group/django-users?hl=en.
>>>
>>
>>
>>
>> --
>> Thanks & Regards,
>>
>> Nisa Balakrishnan,
>> SHARJAH, UAE.
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>
>

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



Re: creating dynamic forms with django

2011-07-20 Thread ken paul
Thank man but what I mean is like you create a dynamic class
||new_class=type('myform',(forms.Form),{attrib})|| but the dict with attribs
is a bit complex coz the form attributes have there own attributes and
widgets
Kenneth


On Wed, Jul 20, 2011 at 1:00 PM, NISA BALAKRISHNAN <
snisa.balakrish...@gmail.com> wrote:

> may be dis link helps u:
>
> http://uswaretech.com/blog/2008/10/dynamic-forms-with-django/
>
> On Wed, Jul 20, 2011 at 12:46 PM, ken paul  wrote:
>
>> hey can anyone get a way of writing dynamic form classes with django. I
>> have tried but putting the attributes became a bit hard.
>> Kenneth
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>
>
>
> --
> Thanks & Regards,
>
> Nisa Balakrishnan,
> SHARJAH, UAE.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

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



creating dynamic forms with django

2011-07-20 Thread ken paul
hey can anyone get a way of writing dynamic form classes with django. I have
tried but putting the attributes became a bit hard.
Kenneth

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



2 Python/Django Developers Needed ASAP

2011-03-30 Thread Ken Zinchiak

In need of 2 Python, Django developers, for Mobile Applications, ASAP

In the NYC area for the 3 largest media company in the country.

Permanent roles

 

Functions:

Develop back end services for Mobile Applications

Develop extensible online applications

Develop and maintain Automated Testing Frameworks

Working in our own Cloud Environment

 

Required Skills:

Python, prefer 2-4 years exp.

Django framework

Open Source Familiarity

OOP

Linux command line proficiency

 

Desired Skills:

Clustered Server Environment

Scalable Wed Architecture

Web Interface Design


Look forward to hearing from you soon.

Thanks,

 

Ken Zinchiak

Moore Associates

973-560-4830

973-296-5787  Cell

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



Re: Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
Yes, I think I have it figured out now.  Sorry for asking such a newb 
question.  If I understand correctly, all I need to do is change the form 
action to the login URL.  Then, url.py will direct the request to my 
existing login view function.

I bet you guys were all bashing your heads against the wall!  Sorry for the 
confusion.  Thanks for all the input, guys! I really appreciate it.

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



Re: Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
Hi James - I want to point out that I will not have a dedicated login URL, 
as the functionality will be available on each page (not just a link to the 
login page, but the actual form).  Previously, I had a dedicated login URL 
and link to the login page, but my frontend guy made a slick jQuery 
drop-down login/register box that shows up on each page.  As to whether this 
was a good way to implement login is a whole different story that goes 
beyond the scope of what I'm dealing with at the moment.  

I'm kinda leaning towards a decorator for each view function.  At least the 
login view code will be in one place.  The only thing I will be repeating 
over and over is "@login", which isn't a big deal.

Base.html already has the necessary html/JS to show the login form.  I just 
need to figure out how to organize or call the view code.

Let's suppose that we're on my blog page.  The login/register form from 
base.html shows at the top of the page and the blog is directly below it.  
If the user enters login info and clicks the login submit button, what 
mechanism should I use to ensure that the request object goes to the login 
view code -- wherever it might live (not implying that it has to be in a 
view.py).

Thanks!

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



Re: Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
A global context processor would probably work, but is it kosher to put 
business logic in a context processor?  To me it seems that the whole point 
of a context processor is to simply take a piece of data and extract/format 
information from it to form a context dictionary.

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



Re: Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
Because I will have the login form on each page, I will not have a separate 
login URL. That's why I'm having difficulties with organizing the business 
logic code (i.e. view).  It's almost as if I need to have two view functions 
-- one for login and another for the current page -- for the URL for the 
current page.  I hope that makes sense.  Of course, we all know that we 
can't have two separate view functions for one URL, so I would have to take 
the login code and somehow tie it to the view for each page.  There are 
several ways to make this work, but my main question is:  What is the 
cleanest and most maintainable way for me to do this?

Thanks all for your input!

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



Re: Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
Hey - Thanks for replying.  So I'm thinking that the method that I 
originally described would amount to only a few lines of code.  A decorator 
would look nicer, but i'd have to remember to add it for future views, which 
is kinda annoying.  Also, I wouldn't have a login URL because all pages will 
have it available.

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



Best DRY practices for a view function that will be used by all other views.

2011-02-05 Thread Ken Chida
I tried my best to search for an answer but my efforts yielded nothing.  
Allow me to give you a simple example to illustrate my problem.  Let's 
pretend that I want to have a login form on every single page on my 
website.  Obviously, the login form will have a corresponding view 
function.  What is the most elegant way to implement the login functionality 
on every single page?  One brute force method would be to include the login 
view inside all view functions for every page; these view functions would 
call the login view if the HttpRequest object contains a flag that becomes 
active when the user clicks the login submit button.  This method would 
work, but it goes against DRY best practices.

Is there a better way to do this?  Maybe I can use a custom template tag?

Thanks in advance!!
Ken

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



Re: How to get a web development job (i.e. Django/Python) if someone is an amateur programmer?

2010-12-17 Thread Ken Huang
OP here.

I've got a still-live Digg-like PHP site that I built two years ago with a
few buddies. How much cred does that buy me if I'm looking for a Django job?
Do I need to specifically build and/or open source Django?

Thanks for the advice guys - much appreciated!

On Fri, Dec 17, 2010 at 1:10 PM, garagefan  wrote:

> I was once in your shoes. No real resume experience to show... no
> sites to display my knowledge.
>
> My advice... makes more friends. It's all in who you know. Met some at
> an intro html course at a community college, ended up being good
> friends. He was a developer already, but a few years later he tells me
> about a company he got placed at and said I could easily do the
> work... then he helped me get an interview, then I got hired...
> knowing basic stuff.
>
> Moral of the story, network
>
> On Dec 17, 12:03 pm, Dopster  wrote:
> > *This is a question that can be generalized for any other amateur
> > programmers looking to get into software development, and specifically
> > startups. I specify Django/Python in my own details below, but it can be
> > replaced with PHP, Ruby, etc.*
> >
> > As an amateur, how could I position myself to get in the door at an
> > established startup (i.e., not founding team) or web dev shop as a junior
> > Django/[insert language/framework here] developer? What could I do that
> > would give me a chance of getting a job? My guess is that actually
> building
> > something is the right way to go about this?
> >
> > Build a really simple web app? Build a web resume? Start a technical
> blog?
> > Contribute to open source? (though as an amateur, making meaningful
> > contributions is unlikely...)
> > --
> >
> > My own personal details, as to define what I mean by "amateur":
> >
> > Academic CS knowledge:
> >
> >- Non-CS degree
> >- Two Java courses in college as a non-CS engineer (4+ years ago),
> which
> >I admittedly have since forgotten, but helped me establish...
> >- Comfort with basic CS elements (i.e., classes, functions, basic data
> >structures, control flow tools, etc.)
> >
> > Practical experience (from a failed startup and work):
> >
> >- 1 year of HTML/CSS/JS
> >- 1 year of PHP
> >- 3 years of SQL (mySQL, Oracle, MS Access)
> >- 2 years of VBA development in Excel/Access (front-end and back-end)
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: What does an ideal django workflow setup look like?

2010-10-27 Thread Ken
Ok -

I put together more research. It's a huge pile of links. Hope this
helps as additional places to learn/look. As a disclaimer, I'm a noob,
which is why I am providing Internet research instead of a personal
expert opinion.

--Simon Willison (co-Founder of Django) answered the question at
Quora.com--

Short answer: virtualenv, pip, south for migrations, fabric for
deployment.

Long answer: I haven't seen the perfect tutorial covering all of the
above yet, which is a shame, but here are some good links:

http://morethanseven.net/2009/07/27/fabric-django-git-apache-mod_wsgi-virtualenv-and-p.html

http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip

http://www.caktusgroup.com/blog/2010/04/22/basic-django-deployment-with-virtualenv-fabric-pip-and-rsync/

---Hacker News threads

http://news.ycombinator.com/item?id=1824171

http://news.ycombinator.com/item?id=1827160

http://news.ycombinator.com/item?id=135829

The next few are more git-focused.

http://news.ycombinator.com/item?id=1343753

http://news.ycombinator.com/item?id=441670

--Old Reddit threads

http://www.reddit.com/r/django/comments/dpnfr/fabric_django_git_apache_mod_wsgi_virtualenv_and/

http://www.reddit.com/r/django/comments/95oeo/django_development_workflow/

http://www.reddit.com/r/programming/comments/a5j8b/mozilla_addons_team_switching_to_django_git_and/

On Oct 26, 8:26 am, Celso González  wrote:
> On Fri, Oct 22, 2010 at 08:02:56AM -0700, Ken wrote:
>
> Hi
>
> > I understand there are many different ways and products to use to
> > setup a great workflow for developing in django, but would like to
> > hear how you or your startup team (or corporate dev group) does it.
> > Specifics would be amazing, as I need a little hand holding, i.e.
> > please cover anything and everything that I should know in order to
> > develop efficiently, robustly, and eventually collaboratively.
>
> There are common ideas like +1 South, local_settings.py, vcs and
> helper scripts like fabric
>
> > Basically, please explain it in a way that a layman can follow the
> > steps and setup a workflow without pulling his hair out. =P
>
> ok, my system
>
> Every project has its own virtual enviroment
>
> -virtualenv
> --bin
> --include
> --lib
> --requirements.txt
> --myproject
> ---apps
> ...
> ---static
> ---templates
>
> *All the structure and contents goes into git or vcs of choice
> *pip freeze > requirements.txt and pip install -r requirements.txt
> to handle the external soft installed
> *in .gitignore I override bin, include, lib, src directories
>
> Just using git and virtualenv im able to create the same enviroment
> quickly in several machines (dev, testing, production)
>
> Still working on the database exports
>
> --
> Celso Gonz lez (PerroVerd)http://mitago.net

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



What does an ideal django workflow setup look like?

2010-10-22 Thread Ken
*I've Googled, but have not found any really organized and layman-
friendly overview, which is why I came here*

I know how to get python/django working on my computer (PC or Mac) and
have developed simple test apps using django's built-in dev server and
a mysql back-end. So I can get things to work and don't need help on
installing stuff.

But as a coding hobbyist, I don't know how to set up a pro workflow. I
don't know best practices on how to setup and maintain a dev and
production environment, how to efficiently publish to production, how
to integrate all that into a version control system (i.e., git),
basically anything that a pro coder at a startup would take for
granted as "the way to do things".

I understand there are many different ways and products to use to
setup a great workflow for developing in django, but would like to
hear how you or your startup team (or corporate dev group) does it.
Specifics would be amazing, as I need a little hand holding, i.e.
please cover anything and everything that I should know in order to
develop efficiently, robustly, and eventually collaboratively.

Basically, please explain it in a way that a layman can follow the
steps and setup a workflow without pulling his hair out. =P

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



Need Help!

2010-07-29 Thread Ken
Looking for a django developer in the NYC area!
I would appreciate any help, if you know of anyone!
Thank you!

Ken

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



checking an IP range

2010-04-09 Thread Ken Lacey
Hi

I am trying to check an IP so some information will/will not be
displayed based on the first 8 digites of the remote IP address.

I have a vairable ip_address which contains the remote address and a
vairable accept_ip with a value "192.168." but when I carry out the
following it is not working correctly.

{% ifequal ip_address|slice:"8" accept_ip %}
   do something
{% endifequal %}


I have also tried
{% ifequal ip_address|slice:"8" "192.168." %}
   do something
{% endifequal %}

and
{% ifequal ip_address|slice:"8"|stringformat:"s" "192.168." %}
   do something
{% endifequal %}

the same results appaear whether the ip_address is 192.168. or any
other range.

Thanks

Ken

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



Re: REMOTE_ADDR

2010-03-16 Thread Ken Lacey
Hi

I still cant get this to work. Everything elese in the template works
fine, i.e. accessing several tables from the database.

I have the following in the settings.py

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.middleware.http.SetRemoteAddrFromForwardedFor',
)

and the following in http.py in the middleware folder

class SetRemoteAddrFromForwardedFor(object):
"""
Middleware that sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, if
the
latter is set. This is useful if you're sitting behind a reverse
proxy that
causes each request's REMOTE_ADDR to be set to 127.0.0.1.

Note that this does NOT validate HTTP_X_FORWARDED_FOR. If you're
not behind
a reverse proxy that sets HTTP_X_FORWARDED_FOR automatically, do
not use
this middleware. Anybody can spoof the value of
HTTP_X_FORWARDED_FOR, and
because this sets REMOTE_ADDR based on HTTP_X_FORWARDED_FOR, that
means
anybody can "fake" their IP address. Only use this when you can
absolutely
trust the value of HTTP_X_FORWARDED_FOR.
"""
def process_request(self, request):
try:
real_ip = request.META['HTTP_X_FORWARDED_FOR']
except KeyError:
return None
else:
# HTTP_X_FORWARDED_FOR can be a comma-separated list of
IPs. The
# client's IP will be the first one.
real_ip = real_ip.split(",")[0].strip()
request.META['REMOTE_ADDR'] = real_ip

but still cant access the ip address.

Can anyone tell me what I am doing incorrectly.

Thanks

Ken

On Mar 15, 1:49 pm, "ge...@aquarianhouse.com"
 wrote:
> it seem to me, it's in the template.
>
> when it should work like this:
>
> {{ request.META.REMOTE_ADDR }}
>
> btw:
>
> > 'request.METTA['REMOTE_ADDR']' <--- in META is one T to much
>
> On Mar 15, 2:45 pm, Ken Lacey  wrote:
>
>
>
> > Hi
>
> > I am trying to access the remote addr in a view.
>
> > Using request.META['REMOTE_ADDR'] I get an error
>
> > Exception Type: TemplateSyntaxError
> > Exception Value: Could not parse the remainder: '['REMOTE_ADDR']' from
> > 'request.METTA['REMOTE_ADDR']'
>
> > How do I get over this?
>
> > Thanks
>
> > Ken- Hide quoted text -
>
> - Show quoted text -

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



REMOTE_ADDR

2010-03-15 Thread Ken Lacey
Hi

I am trying to access the remote addr in a view.

Using request.META['REMOTE_ADDR'] I get an error

Exception Type: TemplateSyntaxError
Exception Value: Could not parse the remainder: '['REMOTE_ADDR']' from
'request.METTA['REMOTE_ADDR']'


How do I get over this?


Thanks

Ken

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



Re: Django and database user column update privileges

2010-03-05 Thread Ken
Cheers Karen.

I just wanted to make sure that all aspects of my question were
answered, so I separated the second problem into this thread.  Thanks
for your help.  (See other thread.)

Ken

On 5 Mar, 02:17, Karen Tracey  wrote:
> I answered your question in the other thread you had asking the exact same
> thing.
> Karen

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



Re: Update a single column of a row in a Model

2010-03-05 Thread Ken
Many thanks Karen.  This worked perfectly (though the 'name' attribute
is just name without the quotes).

Cheers,

Ken


On 5 Mar, 01:42, Karen Tracey  wrote:
> On Thu, Mar 4, 2010 at 2:24 PM, Ken  wrote:
> > Thanks for your example, but whilst you're correct about Person.id not
> > getting updated, all the other columns do get changed (even if it is
> > to the same value).
>
> > Here's my code...
>
> > class TcsDetectionListsForm(forms.Form):
> >    name = forms.CharField()
>
> > def candidateWithForm(request, tcs_transient_objects_id):
> >    detectionListRow = TcsDetectionLists.objects.get(pk=0)
>
>    if request.method == 'POST':
>
>
>
>
>
> >        form = TcsDetectionListsForm(request.POST)
> >        if form.is_valid(): # All validation rules pass
> >            detectionListRow.name = form.cleaned_data['name']
> >            detectionListRow.save()
> >    else:
> >        form = TcsDetectionListsForm(initial={'name':
> > detectionListRow.name })
>
> > Here's what happened in the database (from the DB log):
>
> > 223592 Query    UPDATE `tcs_detection_lists` SET `name` = 'rubbish',
> > `description` = 'Bad Candidates' WHERE `tcs_detection_lists`.`id` = 0
>
> > We shouldn't be updating the 'description' column.  If my security
> > settings were in place, this query would fail, because my DB user only
> > has update access to the 'name' column.
>
> TcsDetectionLists.objects.filter(pk=0).update('name'=form.cleaned_data['nam 
> e'])
>
> will produce an SQL UPDATE that only touches the name column.
>
> Karen

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



Django and database user column update privileges

2010-03-04 Thread Ken
Folks

I need to get my users to submit a form, the result of which is a an
update of one column of one row of my database table.  For security
reasons the Django database user only has privileges to update a
single column of this table (and select privs on the rest).

However, when I submit the form, I note that the database UPDATE
command that was received updated ALL columns except the primary key,
which was used in the WHERE clause.

Here is some very simple Form code (I'm new to Forms, so bear with
me...  Thanks for your help Shawn...)

class TcsDetectionListsForm(forms.Form):
name = forms.CharField()

def candidateWithForm(request):
detectionListRow = TcsDetectionLists.objects.get(pk=0)
if request.method == 'POST':
form = TcsDetectionListsForm(request.POST)
if form.is_valid(): # All validation rules pass
detectionListRow.name = form.cleaned_data['name']
detectionListRow.save()
else:
form = TcsDetectionListsForm(initial={'name':
detectionListRow.name })

Here's what happened in the database (from the DB log):

223592 QueryUPDATE `tcs_detection_lists` SET `name` = 'rubbish',
`description` = 'Bad Candidates' WHERE `tcs_detection_lists`.`id` = 0

We shouldn't be updating the 'description' column.

If my security settings were in place, the above query would fail,
because the Django DB user only has update access to the 'name' column
for this table.

The actual table that will be updated eventually has a much larger set
of columns, with lots of doubles & floats.  I really don't want to be
re-writing the entire row and I really don't want to have to resort to
raw SQL.  Any ideas (preferably with an example)?

Cheers,

Ken

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



Re: Update a single column of a row in a Model

2010-03-04 Thread Ken
Thanks for your example, but whilst you're correct about Person.id not
getting updated, all the other columns do get changed (even if it is
to the same value).

Here's my code...

class TcsDetectionListsForm(forms.Form):
name = forms.CharField()

def candidateWithForm(request, tcs_transient_objects_id):
detectionListRow = TcsDetectionLists.objects.get(pk=0)

if request.method == 'POST':
form = TcsDetectionListsForm(request.POST)
if form.is_valid(): # All validation rules pass
detectionListRow.name = form.cleaned_data['name']
detectionListRow.save()
else:
form = TcsDetectionListsForm(initial={'name':
detectionListRow.name })

Here's what happened in the database (from the DB log):

223592 QueryUPDATE `tcs_detection_lists` SET `name` = 'rubbish',
`description` = 'Bad Candidates' WHERE `tcs_detection_lists`.`id` = 0

We shouldn't be updating the 'description' column.  If my security
settings were in place, this query would fail, because my DB user only
has update access to the 'name' column.

Ken



On 4 Mar, 18:35, Shawn Milochik  wrote:
> 1. Doing Person.save() will NOT update every field in your model.
>
> 2. Your snippet uses a ModelForm. Mine used a Form. There's a huge difference.
> If you use a ModelForm you're going to have to exclude all the fields you 
> don't want.
>
> 3. If you use a ModelForm and instantiate it with request.POST, don't send an 
> argument
> for 'instance' as well. One or the other.
>
> Look at my example again. It does exactly what you want.
> It seems that all your problems are due to not understanding the difference 
> between a Form and a ModelForm.
>
> Read the Django book ("The Definitive Guide").
>
> Shawn
>
> On Mar 4, 2010, at 1:29 PM, Ken wrote:
>
>
>
> > Thanks Shawn
>
> > My problem is that Person.save() will do an update of all my columns.
> > Even though they are all identical, apart from the changed value, this
> > will violate my minimum privileges requirement of only allowing the
> > application access to the columns that it is allowed to change - hence
> > your original suggestion of using ModelForms (and only specified
> > fields).
>
> > Maybe if I try something like this...
>
> > #Use a ModelForm for Person..
> > class PersonForm(forms.ModelForm):
> >    model=Person
> >    fields = ('age')
>
> > #When the user submits the form:
> > person = Person.objects.get(pk = 123)
> > person_form = PersonForm(request.POST, instance = person)
> > if person_form.is_valid()
> >        person_form.save()
>
> > Would that work...?  I'll attempt to hack an example in my code and
> > tell you what happens...
>
> > Thanks for your time...
>
> > Ken
>
> > On 4 Mar, 17:28, Shawn Milochik  wrote:
> >> Here's a simple example. It could be improved, but it's meant to be very 
> >> simple.
>
> >> #Make a simple form.
>
> >> class AgeForm(forms.Form):
> >>     age = forms.IntegerField()
>
> >> #When the user submits the form:
>
> >> age_form = AgeForm(request.POST)
>
> >> if age_form.is_valid()
>
> >>         #get the pk however you need to
> >>         person = Person.objects.get(pk = 123)
> >>         person.age = age_form.cleaned_data['age']
> >>         person.save()
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.

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



Re: Update a single column of a row in a Model

2010-03-04 Thread Ken
Thanks Shawn

My problem is that Person.save() will do an update of all my columns.
Even though they are all identical, apart from the changed value, this
will violate my minimum privileges requirement of only allowing the
application access to the columns that it is allowed to change - hence
your original suggestion of using ModelForms (and only specified
fields).

Maybe if I try something like this...


#Use a ModelForm for Person..
class PersonForm(forms.ModelForm):
model=Person
fields = ('age')

#When the user submits the form:
person = Person.objects.get(pk = 123)
person_form = PersonForm(request.POST, instance = person)
if person_form.is_valid()
person_form.save()

Would that work...?  I'll attempt to hack an example in my code and
tell you what happens...

Thanks for your time...

Ken


On 4 Mar, 17:28, Shawn Milochik  wrote:
> Here's a simple example. It could be improved, but it's meant to be very 
> simple.
>
> #Make a simple form.
>
> class AgeForm(forms.Form):
>     age = forms.IntegerField()
>
> #When the user submits the form:
>
> age_form = AgeForm(request.POST)
>
> if age_form.is_valid()
>
>         #get the pk however you need to
>         person = Person.objects.get(pk = 123)
>         person.age = age_form.cleaned_data['age']
>         person.save()

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



Re: Update a single column of a row in a Model

2010-03-04 Thread Ken
Thanks

Unfortunately I'm very new to Forms/ModelForms, and I'm having a lot
of difficulty understanding the Django examples.

All I want is to allow my users to make one change to one column.  I
don't want them to see the ID, just a text box and a submit button.
Hitting Submit should take them back to exactly the same page, with
the text field pre-populated to what they entered.

The database update should only change one column of the relevant row
in the database table.

This would take 30 seconds to do in PHP.

Can anyone point me to some simple examples (other than the Django
site).

Cheers,

Ken


On 3 Mar, 00:31, Shawn Milochik  wrote:
> Use a forms.ModelForm and exclude all the fields except one, or use a  
> forms.Form with one field and use its value in a queryset .update()  
> call.
>
> Shawn
>
> Sent from my iPhone
>
> On Mar 2, 2010, at 7:11 PM, Ken  wrote:
>
>
>
> > Folks
>
> > This is a bit of a newbie question on Model updates.  I've been
> > happily using Django to give my users a read-only view of the database
> > for nearly a year, but now I'd like my users to be able to update a
> > row in one of my tables.
>
> > We're told in the Model documentation that "Django knows best" when it
> > comes to talking to the database.
>
> > However, I want my users to ONLY update ONE column in one row in my
> > database, but Django seems to insist on updating all the columns.  (A
> > related problem is that I'd also like the database user only to be
> > allowed to update a subset of columns of my table - mostly because I'm
> > paranoid.)
>
> > If you don't specify the column value, and the column is nullable, the
> > unspecified columns get set to NULL instead of left alone.
>
> > Here's an example...
>
> > select * from tcs_detection_lists;
> > ++---+-+
> > | id | name      | description         |
> > ++---+-+
> > |  0 | garbage   | Bad Candidates      |
> > |  1 | confirmed | Confirmed SNe       |
> > |  2 | good      | Good Candidates     |
> > |  3 | possible  | Possible Candidates |
> > |  4 | pending   | Not Yet Eyeballed   |
> > ++---+-+
>
> > I want to update the word 'garbage' to 'bad'.
>
> > Here's my simplistic Django code...
>
> > dl = views.TcsDetectionLists(id=0, name ='bad')
> > dl.save()
>
> > select * from tcs_detection_lists;
> > ++---+-+
> > | id | name      | description         |
> > ++---+-+
> > |  0 | bad       |                     |
> > |  1 | confirmed | Confirmed SNe       |
> > |  2 | good      | Good Candidates     |
> > |  3 | possible  | Possible Candidates |
> > |  4 | pending   | Not Yet Eyeballed   |
> > ++---+-+
>
> > I only wanted the user to change one column, but Django has assumed
> > None for the rest of the columns and therefore deleted my
> > 'description' field.
>
> > The update that I want is:
>
> > update tcs_detection_lists
> > set name = 'bad'
> > where id = 0;
>
> > Note that some of my tables have many columns (>50) with a lot of
> > floating point data and I certainly don't want my users inadvertently
> > deleting data.
>
> > Do I need to specify something in my Model columns to get Django to
> > behave the way I want it to...?  I really don't want to have to resort
> > to a bit of custom SQL...
>
> > Thanks in advance,
>
> > Ken
>
> > --
> > You received this message because you are subscribed to the Google  
> > Groups "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com
> > .
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en
> > .

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



Update a single column of a row in a Model

2010-03-02 Thread Ken
Folks

This is a bit of a newbie question on Model updates.  I've been
happily using Django to give my users a read-only view of the database
for nearly a year, but now I'd like my users to be able to update a
row in one of my tables.

We're told in the Model documentation that "Django knows best" when it
comes to talking to the database.

However, I want my users to ONLY update ONE column in one row in my
database, but Django seems to insist on updating all the columns.  (A
related problem is that I'd also like the database user only to be
allowed to update a subset of columns of my table - mostly because I'm
paranoid.)

If you don't specify the column value, and the column is nullable, the
unspecified columns get set to NULL instead of left alone.

Here's an example...

select * from tcs_detection_lists;
++---+-+
| id | name  | description |
++---+-+
|  0 | garbage   | Bad Candidates  |
|  1 | confirmed | Confirmed SNe   |
|  2 | good  | Good Candidates |
|  3 | possible  | Possible Candidates |
|  4 | pending   | Not Yet Eyeballed   |
++---+-+

I want to update the word 'garbage' to 'bad'.

Here's my simplistic Django code...

dl = views.TcsDetectionLists(id=0, name ='bad')
dl.save()

select * from tcs_detection_lists;
++---+-+
| id | name  | description |
++---+-+
|  0 | bad   | |
|  1 | confirmed | Confirmed SNe   |
|  2 | good  | Good Candidates |
|  3 | possible  | Possible Candidates |
|  4 | pending   | Not Yet Eyeballed   |
++---+-+

I only wanted the user to change one column, but Django has assumed
None for the rest of the columns and therefore deleted my
'description' field.

The update that I want is:

update tcs_detection_lists
set name = 'bad'
where id = 0;

Note that some of my tables have many columns (>50) with a lot of
floating point data and I certainly don't want my users inadvertently
deleting data.

Do I need to specify something in my Model columns to get Django to
behave the way I want it to...?  I really don't want to have to resort
to a bit of custom SQL...

Thanks in advance,

Ken

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



How to pass raw sql results (cursor.fetchall()) to the template?

2010-01-14 Thread Ken
Newb question here.  How do I pass raw sql results to my template?
The sql results contains a two column queryset with several rows .

Below doesn't work.  How do I make this work?  Do I need to parse the
results into an array and then pass to the template?

IN THE VIEW:
cursor = connection.cursor()
cursor.execute("query goes here")
results = cursor.fetchall()

return render_to_response('template.html', {'results': results})

IN THE TEMPLATE:
{% for result in results %}
{{ result[0] }} is a big {{ result[1] }}
{% endfor %}


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




Re: How to create multiple 'submit' buttons using 'forms' package

2009-12-05 Thread Ken
Sorry for repeating what you said Shawn, but for some reason your
reply wasn't showing up in my browser until after I had answered the
question for myself.

Thanks,
Ken

--

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




Re: How to create multiple 'submit' buttons using 'forms' package

2009-12-05 Thread Ken
Never mind, got it. the forms package merely provides the interior of
the ; the  markup, plus any submit buttons, are the
responsibility of the template (or other code).

Thanks,
Ken

On Dec 5, 8:55 pm, Ken  wrote:
> I have the following form, which displays nicely:
>
> class BuySellForm(forms.Form):
>     symbol = forms.CharField()
>     shares = forms.CharField()
>     price = forms.CharField()
>
> However, I can't figure out how to get multiple 'submit' buttons to
> display (one 'buy' and the other 'sell'). Actually, I can't even
> figure out how to get a single standard submit button to show up--
> there doesn't seem to be a 'submit widget' listed in the Django book.
> Or perhaps I'm just not seeing it?
>
> As you can tell, I'm an absolute newbie. First day. Thanks for the
> patience.
>
> Ken

--

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




How to create multiple 'submit' buttons using 'forms' package

2009-12-05 Thread Ken
I have the following form, which displays nicely:

class BuySellForm(forms.Form):
symbol = forms.CharField()
shares = forms.CharField()
price = forms.CharField()

However, I can't figure out how to get multiple 'submit' buttons to
display (one 'buy' and the other 'sell'). Actually, I can't even
figure out how to get a single standard submit button to show up--
there doesn't seem to be a 'submit widget' listed in the Django book.
Or perhaps I'm just not seeing it?

As you can tell, I'm an absolute newbie. First day. Thanks for the
patience.

Ken

--

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




Re: Can't run Django from the command line using just "manage.py runserver", following attempt to install Python2.6 on windows 7.

2009-12-01 Thread Ken MacDonald
Hi,
Check this out - on my XP system anyway (understand it hasn't changed much
for W7) use the 'assoc' and 'ftype' commands to find out what ".py" is doing
on your system. It should look something like this, except for file paths
appropriate for your system. If your ftype is messed up (missing the "%*"
maybe), you wouldn't see the args.
Ken

C:\>*assoc .py*
.py=Python.File

C:\>*ftype Python.File*
Python.File="C:\Python25\python.exe" "%1" %*


On Tue, Dec 1, 2009 at 7:18 AM, Rodrigo Cea  wrote:

> Thanks for the response.
>
> Doing some more tests python programs do work, they just seem to not
> recieve sys.argv. The results of calling "manage.py runserver" is the
> same as calling just "manage.py". Other simple scripts bear this out.
>
> Thanks,
>
> Rodrigo
>
> On Dec 1, 6:32 am, John M  wrote:
> > Sounds like the .py extension isn't seen as using python, should be an
> > easy fix.  Check your file associations (where they are in Win7) I'll
> > have to find at work tomorrow, but that should fix your issue.
> >
> > Or, it could be some new security scheme that MS has come up with to
> > not allow associations at the CMD level?  sounds like that would break
> > too much stuff though, I'll try it at work tomorrow and if it's not an
> > association thing, I'll check back on this thread.
> >
> > J
> >
> > On Nov 30, 8:36 am, Rodrigo Cea  wrote:
> >
> > > Following an abortive attempt to install Python2.6 on Windows 7, I
> > > can't run the Django dev server without prepending "python" before
> > > "manage.py runserver".
> >
> > > I tried recently to install Python2.6 on a windows 7 system that
> > > already has python 2.5 installed. I had problems running some Django
> > > applications I'm working on, so I uninstalled it.
> >
> > > Now I can't run the dev server the way I used to: "manage.py
> > > runserver", I get:
> >
> > > "Type 'manage.py help' for usage."
> >
> > > If I run it like so: "python manage.py runserver" it works.
> >
> > > I have checked for other python installs on the system, and there was
> > > just one in Cygwin which I have deleted.
> > > I have checked running programs with and without "python" and the
> > > executable is the same: "C:\python2.5\python.exe".
> >
> > > This also affects other programs, e.g.: easy_setup, which I can't just
> > > run as "easy_setup package_name" anymore, but rather "python /path/to/
> > > easy_setup package_name".
> >
> > > This is more annoying than anything else, but any help is greatly
> > > appreciated.
> >
> >
>
> --
>
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>
>

--

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




Re: how to symlink to django-admin.py from some place on path?????.

2009-11-23 Thread Ken MacDonald
Actually, ".py" or any other extension can become an executable type by
defining the extension via the commands "assoc" and "ftype". I believe that
Python installation on Windows probably does something like this, as any of
my "xxx.py" files (and Django-supplied files such as django-admin.py and
manage.py) can be run from the command prompt directly, and include support
for command-line parameters as well. Looking at the output from "assoc",
you'll find that even ".bat" and ".exe" extensions are defined in this
manner.
Ken

But a bigger problem on Windows is that on windows .py files are not
> an executable type.
>

--

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




Re: autogenerated 'id' field from Django model doesn't autoincrement?

2009-11-20 Thread Ken MacDonald
>
> All of this looks correct.  Note the data type of integer is not wrong --
> serial is not a true data type.  See:
>
> http://www.postgresql.org/docs/8.1/static/datatype.html#DATATYPE-SERIAL
>
>
>
>>
>>
> So, it has a sequence, but the sequence is out-of-sync (value=7) with the
>> actual DB (max id is 92,000+), thus the code to first setval() the sequence.
>> Anyway the code seems to work, but it's still odd that the type isn't
>> serial.
>>
>
>
> I think the question is not why was the wrong type created (it wasn't) but
> how did the sequence get out of sync with the actual values in the table?
>
> Karen
>
> Ah. This begins to make sense, now. I think that the sequence must  not
have been set when I did the initial load of the data, as the original data
had its own sequence numbers and did not use 'nextval' to generate them.
I've changed the initial data loader to use nextval instead of the data's
sequence numbers, so shouldn't have this problem again. I'm leaving the
setval() in my code (modified as in a prev. reply) so that the sequence will
reset to 1 if the table rows are all dropped.
Ken

--

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




  1   2   >