Re: Preview of Form

2021-05-29 Thread Jim Illback
If I understand you correctly, you have an add (or update) form and you want to 
see what those fields would look like in a preview display (like a paper form 
equivalent). I would use an add/update form to input the data fields. At the 
bottom have 2 buttons: one would do the add/update without preview and one 
would show the preview display. The fields could be sent over in context or 
even stored in a temp row of a holding table. Then, on the preview page, you 
format the preview appropriately. You could have 2 buttons: one to accomplish 
the update as is and one to return to the previous page so changes could be 
made. With all this, you stay within Django and maintenance is simplistic, too.

Hope I understood your situation. If not, just ignore this.

Jim

On May 29, 2021, at 11:40 AM, pankaj palmate 
mailto:pankajpalmate61...@gmail.com>> wrote:

Yes using javascript

On Sat, 29 May, 2021, 11:22 pm Kumar Gaurav, 
mailto:gauravcusat1...@gmail.com>> wrote:
Hi All,

How to show a preview of the form filled before submitting. I don't want to 
edit the form in preview but just to see how it will be submitted.

Can Django form tools will help or should I use Jquery or Javascript for this 
purpose. Please suggest a better solution.


Thank You

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to 
django-users+unsubscr...@googlegroups.com<mailto:django-users+unsubscr...@googlegroups.com>.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6a392a73-4f99-4d58-8501-780ba1cf14b7n%40googlegroups.com<https://groups.google.com/d/msgid/django-users/6a392a73-4f99-4d58-8501-780ba1cf14b7n%40googlegroups.com?utm_medium=email_source=footer>.

--
You received this message because you are subscribed to the Google 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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAPyMU1%2BBmf1%3DN1h2Mxdu1oUa1JZvH%2B0%3DbyYvS7CsGohAvY6gOg%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CAPyMU1%2BBmf1%3DN1h2Mxdu1oUa1JZvH%2B0%3DbyYvS7CsGohAvY6gOg%40mail.gmail.com?utm_medium=email_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"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/32207D5D-4257-429D-94AB-4FCFD3D353D9%40hotmail.com.


Re: Assistance for deploying django app to heroku

2021-04-24 Thread Jim Illback
I didn’t see a “createsuperuser" command. Was that done or is it part of your 
fixtures.json load?

Jim

On Apr 24, 2021, at 8:04 AM, Ejike Enyinnaya 
mailto:ejike.chib...@gmail.com>> wrote:

Good day Kasper,

Thanks for your response.

The git commands I put in the email was just to give a summary of what I had 
done and not the full details, that way my email is not too long and cumbersome 
to read.

I can assure you on my CLI, I ran the proper git commands putting in the right 
information and not leaving it empty.

BR,
Ejike Chiboka
0804537; 08166516400


On Fri, Apr 23, 2021 at 7:53 PM Kasper Laudrup 
mailto:laud...@stacktrace.dk>> wrote:
On 23/04/2021 20.41, Ejike Enyinnaya wrote:
> I did a git add ., git commit -m and git push heroku master

Not sure if it's related, but it's possible: This is not how you should
use revision control (git).

You should keep your source files under revision control, not just
blindly add everything and committing it with an empty commit message.
Then you might as well not use any kind of revision control at all.

It might be slightly off topic and not related to your problem, but on
the other hand, there's a huge chance that you have added a bunch of
stuff like your database file and you have zero way of tracking what you
have actually changed.

Not sure if this has every worked for you, but if you have a similar
problem and it used to work and then suddenly didn't, using revision
control like git can be an enormous help.

Do yourself a huge favor and learn how to use revision control.

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<mailto:django-users%2bunsubscr...@googlegroups.com>.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4ebee094-cc84-ce01-ddfd-11ca231960d6%40stacktrace.dk.

--
You received this message because you are subscribed to the Google 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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CADe59C-Sau_rAhxLJQKBmMcHDMxq_Uc12aTVo%2BRL4YoSdOf7aw%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CADe59C-Sau_rAhxLJQKBmMcHDMxq_Uc12aTVo%2BRL4YoSdOf7aw%40mail.gmail.com?utm_medium=email_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"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/F91210CE-9D66-4C64-A1A0-1C6EA001DD67%40hotmail.com.


Re: I have created a application in which i want to filter table between dates (from and to date) but i am not getting desired out put... Please guide me

2021-02-16 Thread Jim Illback
Neha, try changing your template for loop from:
{% for results in formdata %}

To:
{% for results in search %}

The name of your queryset in your context (d = {'search': search, 'fd': fd, 
'td': td}) is search, not formdata.

Also, I’d recommend improving your names. Things like “data”  and “results” are 
not the most meaningful names to use.


Good luck!
Jim


On Feb 16, 2021, at 1:57 AM, neha bhurke 
mailto:bhurkene...@gmail.com>> wrote:

hi Everyone ,

I have created a application in which I want to  filter table between dates 
(from and to)dates
But not getting a desired output .

This is my models.py

class data(models.Model):
machinename = models.CharField(max_length=100)
activity = models.CharField(max_length=255)
description = models.CharField(max_length=500)
datetime = models.DateField()


This is my html page


{% csrf_token %}






>From :
To :








Datetime
Machine Name
Activity
Description




{% for results in formdata %}

{{results.datetime}}
{{results.machinename}}
{{results.activity}}
{{results.description}}

{% endfor %}






This is my views.py

def showresults(request):
if request.method == "POST":
fd = request.POST.get['fromdate']
td = request.POST.get['todate']
search = data.objects.filter(Q(datetime__gte=fd) & Q(datetime__lte=td))
d = {'search': search, 'fd': fd, 'td': td}
return render(request, 'dashboard.html', d)
else:
result = data.objects.all()
return render(request, 'dashboard.html', {'formdata': result})


Please help me..
Thank You !!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/11780FCE-6C09-4B48-A61D-42B3FA7FCCD7%40hotmail.com.


Re: Show FK as input instead of drop down in admin

2021-01-27 Thread Jim Illback
I think Kevin’s issue is that it takes a huge amount of runtime to create the 
FK’s select HTML tag - Django having to go through 1M rows before displaying 
the page. This issue is true in UpdateView CBVs as well. 

Changing the situation slightly - I’m talking about just primary keys from here 
on, not all FK’s. Is there some justification for Django forcing UpdateViews 
(and admin pages) to have to have the entire set of primary keys displayed and 
able to be changed? I believe the real world doesn’t operate like that. In SAP 
or Oracle apps or any other business process, you can’t change the primary key 
value willy nilly. For example, should an admin at Amazon be able to take my 
prime order and re-assign it to some other random person? No.

And, even if this is a specific business requirement (for example, one 
subsidiary needs their purchase order transferred to their peer subsidiary), 
that should be done via a unique exception process that checks all the business 
rules and circumstances, such as ensuring both companies belong to the same 
corporation. However, those are exception transactions, not the forced norm. 

To make this situation work today in Django updates, all applications using an 
update with a primary key to a large table has to write special form or view 
__init__() methods to limit primary key or keys shown. Otherwise, you have to 
wait for the page to build enormous primary key select tags. Why?

Jim

> On Jan 27, 2021, at 7:07 PM, Mike Dewhirst  wrote:
> 
> On 28/01/2021 12:33 am, Kevin Olbrich wrote:
>> Hi!
>> 
>> Is it possible to disable fetching of related models for admin pages?
>> I have a field that links to a table containing more than 1M rows which 
>> django tries to fetch and build the drop down. For my purpose, it is 
>> sufficient if it is a simple input containing the id instead.
> 
> Couple of options ...
> 
> 1. If there is a subset of 1M rows which apply you can filter the drop down 
> list to just a few - or
> 
> 2. Avoid the issue altogether
> 
> - make the fk field in the model null=True and blank=True
> 
> - make the fk field in the admin readonly
> 
> - add a new integer field for the user-entered value of the desired id
> 
> - in the model save() method[1] find the desired instance from the 1M 
> rows and put it into the real fk field
> 
> Might work but not tested. This is a thought experiment.
> 
> Mike
> 
> [1]
> def save(self, *args, **kwargs):
> # might need some adjusting for safety, business rules etc
> self.onem = OneM.objects.get(id=self.pseudo_fk)
> super().save(*args, **kwargs)
> 
>> 
>> How can I accomplish this?
>> 
>> Thank you!
>> 
>> Kind regards
>> Kevin
>> -- 
>> You received this message because you are subscribed to the Google 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 view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/12a7c928-a960-4c48-b631-93153260adbfn%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/12a7c928-a960-4c48-b631-93153260adbfn%40googlegroups.com?utm_medium=email_source=footer>.
> 
> 
> -- 
> Signed email is an absolute defence against phishing. This email has
> been signed with my private key. If you import my public key you can
> automatically decrypt my signature and be sure it came from me. Just
> ask and I'll send it to you. Your email software can handle signing.
> 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "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/24a0de08-f460-5dea-47d4-df77a5d6170d%40dewhirst.com.au.

-- 
You received this message because you are subscribed to the Google Groups 
"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/9401C7F2-0042-4605-AA9A-E958D2AF0AE5%40hotmail.com.


Re: Symmetrical, Self-referencing ManyToManyField with Through Table

2020-06-25 Thread Jim Shepherd
Nice solution. Thanks!

On Thursday, June 25, 2020 at 5:49:23 PM UTC-4, Dan Madere wrote:
>
> I don't know of a way to configure the admin do that, but one solution 
> would be to use signals to notice when one-way records are created, then 
> automatically create the record for reverse relationship. We need to notice 
> when records are deleted as well. This approach would allow showing one 
> inline that shows the combined results. I was able to get it working with 
> this: https://gist.github.com/dgmdan/e7888a73c14446dccd7ad9aaf5055b10
> Hope this helps!
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/d9cd8467-74c5-4915-a452-15f4fc2d03bfo%40googlegroups.com.


Re: Symmetrical, Self-referencing ManyToManyField with Through Table

2020-06-25 Thread Jim Shepherd
After reviewing the tests, I think I now understand what is going on.

Basically, for symmetric ManyToManyField, Django creates entries for both 
directions automatically if the correct interface is used. From the test 
models:

class PersonSelfRefM2M(models.Model):
name = models.CharField(max_length=5)
sym_friends = models.ManyToManyField('self', 
through='SymmetricalFriendship', symmetrical=True)


class SymmetricalFriendship(models.Model):
first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE)
second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, 
related_name='+')
date_friended = models.DateField()


And the tests:

def test_self_referential_symmetrical(self):
tony = PersonSelfRefM2M.objects.create(name='Tony')
chris = PersonSelfRefM2M.objects.create(name='Chris')
SymmetricalFriendship.objects.create(
first=tony, second=chris, date_friended=date.today(),
)
self.assertSequenceEqual(tony.sym_friends.all(), [chris])
# Manually created symmetrical m2m relation doesn't add mirror entry
# automatically.
self.assertSequenceEqual(chris.sym_friends.all(), [])
SymmetricalFriendship.objects.create(
first=chris, second=tony, date_friended=date.today()
)
self.assertSequenceEqual(chris.sym_friends.all(), [tony])

def test_add_on_symmetrical_m2m_with_intermediate_model(self):
tony = PersonSelfRefM2M.objects.create(name='Tony')
chris = PersonSelfRefM2M.objects.create(name='Chris')
date_friended = date(2017, 1, 3)
tony.sym_friends.add(chris, through_defaults={'date_friended': 
date_friended})
self.assertSequenceEqual(tony.sym_friends.all(), [chris])
self.assertSequenceEqual(chris.sym_friends.all(), [tony])
friendship = tony.symmetricalfriendship_set.get()
self.assertEqual(friendship.date_friended, date_friended)


So the tests show that the add() method needs to be used to create both 
sides of the relationship. I assume that the Admin page does not use the 
add method, but creates the intermediate entries which would require both 
the be added for each entry.

Is it possible to configure the Admin models to use add() or to create both 
directions automatically?

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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3ad9f7f2-539f-4b66-9717-863d5f412ef4o%40googlegroups.com.


Re: Symmetrical, Self-referencing ManyToManyField with Through Table

2020-06-25 Thread Jim Shepherd
On Thursday, June 25, 2020 at 10:26:25 AM UTC-4, Dan Madere wrote:
>
> I tried out the example code, and can replicate this. What's interesting 
> is that if I try removing the ContactConnection model, and the "through" 
> attribute, this allows Django to create the intermediate table on its own, 
> and then your get_connections() method works as expected! It seems like 
> using a custom through table is causing this somehow. I haven't found a fix 
> but will keep looking.


 Dan, thanks for looking into this issue.

I found the unit tests for this capability in 
https://github.com/django/django/tree/master/tests/m2m_through which seems 
to indicate that it does work.

I updated my version of Django to 3.1.b1 and copied the models and tests 
into my code. Neither the admin nor queries on the ManyToManyField return 
the full "symmetric" results.

Any other ideas?

Thanks!

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/05819cd1-7c67-4c64-bfce-69934315782eo%40googlegroups.com.


Re: Symmetrical, Self-referencing ManyToManyField with Through Table

2020-06-25 Thread Jim Shepherd
Mike, Thanks for your suggestions. 

Just a stab in the dark - have you tried giving from_contact a 
> related_name? 
>

Yes, I have tried a few different combinations of providing a single 
related_name and various naming conventions when providing related_name on 
both ForeignKey fields without success.
 

> Another stab ... maybe you could just display the 
> ContactConnectionAdmin(admin.ModelAdmin) with model=ContactConnection? 
>
>
Yes, adding a ModelAdmin for the through table will show all of the 
relationships, but it still requires searching both ForeignKey fields to 
capture all of the relationships, regardless of which Contact hey were 
created on.

Workarounds are to add two Inlines, one for each through table foreign key, 
or perform a compound query to combine the two results. I just figured that 
since the capability was added in Django 3.0, that the symmetric queries 
were included as well. My guess is that it is possible with the correct 
configuration / naming conventions. I'll dive into the code to see if 
anything pops up.

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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1f730af3-11cb-49c6-a62f-e147107233a0o%40googlegroups.com.


Symmetrical, Self-referencing ManyToManyField with Through Table

2020-06-24 Thread Jim Shepherd
I am unable to get a symmetrical, self-referencing ManyToManyField with a 
through table to actually be symmetrical, at least through the Admin 
interface. I am using Django 3.0 so it looks like the capability is 
supported.

Models:


class Contact(models.Model):
last_name = models.TextField(default='', blank=True)
connections = models.ManyToManyField('self',
 through='ContactConnection',
 symmetrical=True,
 blank=True)

def get_connections(self):
return ', '.join([str(p.last_name) for p in self.connections.all()])


class ContactConnection(models.Model):
to_contact = models.ForeignKey(Contact,
   related_name='contacts',
   on_delete=models.CASCADE,
   null=False)
from_contact = models.ForeignKey(Contact,
 on_delete=models.CASCADE,
 null=False)
comments = models.TextField(default='', blank=True)




Admin:

class ContactConnectionInline(admin.TabularInline):
model = Contact.connections.through
fk_name = 'from_contact'
extra = 0

@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
ordering = ('last_name',)
list_display = ['last_name', 'get_connections']
inlines = (ContactConnectionInline)


 
>From the Admin page, when viewing a Contact, only one-direction of the 
ContactConnection relationship is shown which makes sense due to the 
fk_name='from_contact attribute fixing the direction.
But it seems that at least the get_connections() method would get both 
sides.

Is there a way either through a query or preferably an Inline to show the 
Contacts on both sides of the ContactConnection?

Thanks,
Jim

-- 
You received this message because you are subscribed to the Google Groups 
"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/91dad4bc-7eba-461d-89f1-aaf173e80831o%40googlegroups.com.


Re: HOW TO PROTECT SOURCE CODE DEPLOYED TO A REMOTE SERVER

2020-05-18 Thread Jim Armstrong
When I work on client projects, I deploy to a test server that is under my 
control. Once the project is complete and they have paid the invoice, I 
deploy to the production server under their control. At that point, I don't 
care if they have access to the code - my contracts give the clients all 
rights to the project code upon completion of the project.


On Friday, May 15, 2020 at 9:22:33 AM UTC-4, Sunday Iyanu Ajayi wrote:
>
> I am working for a client that wants to deploy a project I am working on 
> in a remote server and I will like to project my source code when deployed 
> so that they will not be able to mess with it. 
>
> How can  I  go about it please? 
>
> *AJAYI Sunday *
> (+234) 806 771 5394
> *sunne...@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...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/636f0636-30df-4ce2-8629-2be8b208ec37%40googlegroups.com.


Re: Multiple submit for same form refresh the page

2020-05-09 Thread Jim Illback
Nirantar, I think you could do this in your class (or even in your function if 
you use that instead):
  - Override (or use) the get() method
  - Add a conditional such as this in that get() method:
if request.GET.get(‘wordcloud’):

elif request.GET.get(‘bar’):

…

Good luck!
Jim Illback


> On May 9, 2020, at 6:15 AM, Nirantar Kulkarni  wrote:
> 
> html template
>  name="sub_form">
> {% csrf_token %}
>   {{name}}
>"wordcloud">WordCloud
>"bar">Text_Analysis
>   Sentiment 
> Analysis
>  
> 
> I have multiple submit buttons for same form and each button refreshes the 
> page 
> I don't want it to refresh as it removes all changes made by one button to 
> perform changes made by another please help me
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com 
> <mailto:django-users+unsubscr...@googlegroups.com>.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/14a8c9f5-c949-4caa-a3dd-87af0d4d39c4%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/14a8c9f5-c949-4caa-a3dd-87af0d4d39c4%40googlegroups.com?utm_medium=email_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"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/CY4PR04MB11914DFB0F50E1AEB0E25B0A9DA30%40CY4PR04MB1191.namprd04.prod.outlook.com.


how to request a feature

2020-02-17 Thread Jim
I found an app called redirects that gives me a way to create redirects via 
the admin UI.

It works great, but I noticed that it doesn't support passing along the URL 
parameters to the new redirect target. It seems that this would be a good 
idea.

I found that someone posted a snippet of code that adds this 

.

Where might I go to request that this get added as a feature to the 
shipping django?

Is this something people would use, or would they do redirects at a more 
low-level inside of views or something -- this post about that style seems 
way more popular 

.

Thanks for letting me know. I'm a bit of a nube.

-- 
You received this message because you are subscribed to the Google Groups 
"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/a9ab37c2-d2cc-4a90-b1fd-24a5c3a203aa%40googlegroups.com.


Re: Directly Accessing Dictionary Values

2019-11-21 Thread Jim Illback
Check out this URL and the embedded Django link in the answers: 
https://stackoverflow.com/questions/1700661/how-to-access-array-elements-in-a-django-template.


On Nov 20, 2019, at 10:25 AM, Andrew Stringfield 
mailto:loneso...@gmail.com>> wrote:

I have not!  I did see something about that on a website.  Would it go 
something like: dictionary_name.fieldname.0 ?  I will try it out later today.

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to 
django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f1615df3-04bc-4a28-9914-535c51f13268%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 on the web visit 
https://groups.google.com/d/msgid/django-users/2ACBD58F-2A6D-4E23-AD31-2636D22C9C0A%40hotmail.com.


Re: Directly Accessing Dictionary Values

2019-11-20 Thread Jim Illback
Have you tried  for the first element, and so forth? Of 
course, you have to keep track of the number of entries.


> On Nov 20, 2019, at 5:57 AM, Andrew Stringfield  wrote:
> 
> Okie-dokie.  Thank you.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/83187d02-2f28-4652-8986-83dfcd65108e%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 on the web visit 
https://groups.google.com/d/msgid/django-users/38AB6CE6-A1D1-4E9F-90F7-0DA1417B76BF%40hotmail.com.


Django 2.2.2 having problems with daylight savings time

2019-11-08 Thread Jim Illback
Is anyone else having an issue with Django (2.2.2), giving an error for a date 
time within the daylight savings change over period (11/3/2019 01:00 to 
11/3/2019 02:00)? 

My settings have TIME_ZONE = ‘America/Los_Angeles’. However, a transactional 
time such as ‘2019-11-03 01:18:34:12345-08’ gives the error message: 
“2019-11-03 01:18:34 couldn’t be interpreted in time zone America/Los_Angeles; 
it may be ambiguous or it may not exist.” 

Why doesn’t Django understand that this is in the conversion from Pacific 
Daylight Time (PDT) to Pacific Standard Time (PST) and specifically, it is PST 
at 01:18:34? The -08 timezone designation proves that easily. Isn’t this a bug 
in Django? Is it limited to just version 2.2.2?


Thanks for any help with this issue,
Jim Illback

-- 
You received this message because you are subscribed to the Google Groups 
"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/CC69DCB8-9CFD-40B4-8AD8-45E618CF5463%40hotmail.com.


Re: New user question: Where to put non-form validation code?

2019-07-24 Thread Jim Illback
I had a slight variation on this thread - where to put some M2M field 
validation/deletion logic.

I have a purely model-based form where a checkbox’s value determines whether 
another field (it’s a M2M field) in the form should be NULL or keep its values 
to be saved in the database. So, following the appropriate separation of 
concerns as advocated below, I added logic in both the models' clean and save 
override methods. Neither approach set the other field to NULL when it should 
have been. The reason is the form still contained M2M values even though the 
model said to delete them (delete the set, actually).

After a lot of trial and error, it turns out that the model’s save seems to be 
run BEFORE the form’s save. To me, that seems backwards. Shouldn’t the model’s 
processes (which are directly relate to the database, the ultimate data source) 
occur last and well before the form’s (which are merely an interaction with the 
user)? What was happening was my model’s delete actually did the deletions 
(those IDs were gone), but then the form’s processing came along afterwards and 
re-inserted them again (with brand new IDs).

Can someone help me understand why Django has chosen this seemingly “inversion” 
of processing - first models’ processes, then forms’? And, perhaps more 
importantly, where should this either/or logic should be placed so it will take 
effect?

Thanks very much,
Jim Illback

On Jul 13, 2019, at 11:48 PM, Mike Dewhirst 
mailto:mi...@dewhirst.com.au>> wrote:

Well yes it could be called multifaceted.

Usually but not always the interface with the user is the form. You can have 
non-database fields as well as model fields so either way there has to be a 
full suite of validation functionality available in both types of forms. 
Luckily, model forms automatically call model.clean() for you.

Unit tests don't though. You have deliberately call obj.clean() if you want to 
test things. obj.save() doesn't call obj.clean().

Actually, I also do a bit in view code too especially if there are non-database 
or hidden fields in the form. I know you are not supposed to validate data in a 
view for proper separation of concerns but it does keep my forms neater.

The bottom line for me is that if I can imagine non-form access ... eg through 
an API ... then all validation possible has to be via model.clean() and the API 
has to remember to call clean() before saving every time there is a POST

Hence I always put business rules validation in model.clean() and leave 'local' 
validation for the form.

You are right. There are quite a few moving parts 

Connected by Motorola


Dean Karres mailto:dean.kar...@gmail.com>> wrote:

Thank you. There are way more parts to this than I would have imagined.



On Sat, Jul 13, 2019, 8:01 PM Mike Dewhirst 
mailto:mi...@dewhirst.com.au>> wrote:
On 14/07/2019 10:37 am, Dean Karres wrote:
Hi,

I am learning Django.  I am using CBVs.  My default "index.py" view is 
basically a dashboard for the app I am playing with.  As my models and views 
become more complicated I want to be able to ask, for any model instance, is 
this instance "valid" or "complete".  Valid means that all Required elements 
are present and have reasonable values.  "Complete" means that an instance is 
"valid" but also some specific bits of additional info are also ok.

For example I have a Student model that has name and address info.  There is a 
ManyToMany relation to the Class(es) in which that Student is enrolled.  A 
"student" instance is valid if the name and address fields are filled.  A 
student is "complete" if the student is valid and has signed up for one or more 
classes.

So, my question is: where should the valid and complete methods live?  Should 
they be in the Student model or CBV?  Someplace else?  Does it matter?

I like to put that sort of stuff into model methods then add model.clean() to 
call them and raise whatever error may be appropriate if they fail.

https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#interaction-with-model-validation

and

https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects

and

https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model.clean

You can raise your own errors which inherit from ValidationError to fine tune 
the process. For example, I differentiate between BusinessRuleViolation and 
InvalidToken and a couple of others where that delivers better control.



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

Re: How to use permissions on a CreateView class?

2019-05-28 Thread Jim Illback
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 
mailto:jreitma...@gmail.com>> 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_required
from django.utils.decorators import method_decorator
from 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
Blog: http:www.fellipeh.eti.br<http://www.fellipeh.eti.br/>
GitHub: 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-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/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_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/B5E64E45-C1C3-455F-AEC7-167852FE17C7%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Error during template rendering

2019-05-23 Thread Jim Illback
This error comes when there is a {% url %} tag that is not set up properly - 
like the views.py line highlighted below. So, I suspect you have such a tag say 
tied to a button on the html page, but it isn’t included in this thread.

There’s another error in the code not related to your reverse error - the view 
passes in ‘posts’ as the context name but the template processes ‘post’: 
post.title, post., etc. Those have to match in order for the DB values to 
be displayed.

I’d go back through the djangogirls tutorial again and be positive everything 
is typed in correctly. That should fix it.

Jim

On May 23, 2019, at 12:23 PM, cixtus anyanwu 
mailto:sikky...@gmail.com>> wrote:

Still got this erorr. thanks
  File 
"C:\Users\ANYANWU\djangogirls\myvenv\lib\site-packages\django\urls\resolvers.py",
 line 634, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'post_details' with keyword 
arguments '{'pk': 3}' not found. 1 pattern(s) tried: ['posts//$']

On Thursday, May 23, 2019 at 7:29:57 PM UTC+1, subaru_87 wrote:
Below, post is a DB row, not an ID as the URL.py requires.

Change the view as:
return render(request, ‘blog/post_details.html’, {‘pk’: posts[‘id’]})


Jim


On May 23, 2019, at 11:10 AM, Rock N Roll Mühlbacher  
wrote:

Am Donnerstag, 23. Mai 2019 20:06:31 UTC+2 schrieb cixtus anyanwu:
Guys am following the django girls pdf tutoril but am stuck here. Its saying:



django.urls.exceptions.NoReverseMatch: Reverse for 'post_details' with keyword 
arguments '{'pk': 3}' not found. 1 pattern(s) tried: ['posts//$']
[23/May/2019 18:13:22] "GET / HTTP/1.1" 500 153773
my views.py is below:




from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post


# Create your views here.
def post_list(request):
 posts = Post.objects.filter(title__contains='post')
 return render(request, 'blog/post_list.html', {'posts':posts})
def post_details(request, pk):
 posts = get_object_or_404(Post, pk)
 return render(request, 'blog/post_details.html', {'posts': posts})




urls.py




from django.urls import path
from . import views


urlpatterns = [
 path('', views.post_list, name='post_list'),
 path('posts//', views.post_details, name='post_details')
]




base.html




{% load static %}


 Django reloaded
 


 Django Girls Blog 
 {% block content %}
 {% endblock %}






post_details.html




{% extends 'blog/base.html' %}
{% block content %}
 {% if post.published_date %}
 {{post.title}}
 {% endif %}
 
 {{post.body}}
 {{post.published_date}}
 
 }
{% endblock %}




I have tried everything i can. Pls help me out guys.

--
You received this message because you are 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/92d0fe6d-dc88-4423-9645-402284ac9877%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<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/0a4369bc-2538-4bf7-aaf7-b09be339abec%40googlegroups.com<https://groups.google.com/d/msgid/django-users/0a4369bc-2538-4bf7-aaf7-b09be339abec%40googlegroups.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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


Re: Error during template rendering

2019-05-23 Thread Jim Illback
Below, post is a DB row, not an ID as the URL.py requires.

Change the view as:
return render(request, ‘blog/post_details.html’, {‘pk’: posts[‘id’]})


Jim


On May 23, 2019, at 11:10 AM, Rock N Roll Mühlbacher 
mailto:chmuhlbache...@gmail.com>> wrote:

Am Donnerstag, 23. Mai 2019 20:06:31 UTC+2 schrieb cixtus anyanwu:
Guys am following the django girls pdf tutoril but am stuck here. Its saying:



django.urls.exceptions.NoReverseMatch: Reverse for 'post_details' with keyword 
arguments '{'pk': 3}' not found. 1 pattern(s) tried: ['posts//$']
[23/May/2019 18:13:22] "GET / HTTP/1.1" 500 153773
my views.py is below:




from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post


# Create your views here.
def post_list(request):
 posts = Post.objects.filter(title__contains='post')
 return render(request, 'blog/post_list.html', {'posts':posts})
def post_details(request, pk):
 posts = get_object_or_404(Post, pk)
 return render(request, 'blog/post_details.html', {'posts': posts})




urls.py




from django.urls import path
from . import views


urlpatterns = [
 path('', views.post_list, name='post_list'),
 path('posts//', views.post_details, name='post_details')
]




base.html




{% load static %}


 Django reloaded
 


 Django Girls Blog 
 {% block content %}
 {% endblock %}






post_details.html




{% extends 'blog/base.html' %}
{% block content %}
 {% if post.published_date %}
 {{post.title}}
 {% endif %}
 
 {{post.body}}
 {{post.published_date}}
 
 }
{% endblock %}




I have tried everything i can. Pls help me out guys.

--
You received this message because you are subscribed to the Google 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/92d0fe6d-dc88-4423-9645-402284ac9877%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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6941BD09-766A-4793-8F9F-0AC9890EA343%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is it possible to value based on another aggregation?

2019-05-21 Thread Jim Illback
Sorry this is late.

I’d use the annotate to get the Max of one FK. Then, do a query on the other FK 
table with inverted order_by and use the [0] notation to just retrieve the 
latest row. It is 2 queries, but FK processes are indexed and should be fast.

Hope this helps.

Jim Illback

On Apr 23, 2019, at 7:47 PM, Kenny Loveall 
mailto:ke...@kennyloveall.com>> wrote:

Right, so that works for getting the most recently updated at time (I can just 
do 
`.values('foreign_key_id').annotate(most_recently_updated_at=Max('created_at')`).
 But how can I get the user that created that record? Max('user_id') gives me 
just the highest ID.



On Tue, Apr 23, 2019 at 2:13 PM Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:
Use annotate.
https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset




From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com<mailto:django-users@googlegroups.com>] On 
Behalf Of Kenny Loveall
Sent: Tuesday, April 23, 2019 12:58 PM
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Subject: Is it possible to value based on another aggregation?

Hi everyone,

I'm trying to figure out if it's possible to get a value for one field based on 
the aggregation of another? Specifically, I've got a model with a created_at 
timestamp, a foreign key, and a created_by user foreign key. I want to group 
the objects based on the foreign key and get the time and user of the most 
recently created object.

I know how to do this with a subquery and how to get the most recently created 
timestamp for each group of objects without a subquery, but I'm not sure how to 
get the user without using a subquery. Is this possible?

Thanks,
Kenny
--
You received this message because you are subscribed to the Google 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/CAGABHYC3S-9o_ay1%2BPiANm6vv5py7tFBKyuUCzT1%2Bz49Z%2BpAnA%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CAGABHYC3S-9o_ay1%2BPiANm6vv5py7tFBKyuUCzT1%2Bz49Z%2BpAnA%40mail.gmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to 
django-users+unsubscr...@googlegroups.com<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/f1b62c769d1248a283e4bae3c904a5db%40iss2.ISS.LOCAL<https://groups.google.com/d/msgid/django-users/f1b62c769d1248a283e4bae3c904a5db%40iss2.ISS.LOCAL?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/14B298C7-4E64-43E0-A10D-490DFA51014E%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: formfield_overrides doesn't work

2019-05-12 Thread Jim Illback
Tim, this won’t help you to use or solve the formfield_overrides issues, but 
maybe it will be helpful. I’ve not tried this for a CharField, but it works 
great on a TextField (which has no max_length, so model size isn’t impacted):

1. Install  widget tweaks and add {% load widget_tweaks %} at the top of your 
HTML page.
2. On your HTML page, instantiate the field using this format: {{ 
form.notes|attr:"rows:20"|attr:"cols:50" }} - you can use either row/cols or 
both as in this case, and any char size.

Here’s a great usage example on widget tweaks: 
https://simpleisbetterthancomplex.com/2015/12/04/package-of-the-week-django-widget-tweaks.html.

I hope this is useful for you.

Jim Illback


On May 12, 2019, at 3:03 PM, Tim Johnson 
mailto:t...@akwebsoft.com>> wrote:

* Joe Reitman mailto:jreitma...@gmail.com>> [190512 
13:34]:
Tim,

I found this in the Django source code on Github searching for
'formfield_overrides'. It is in a test module testing formfield_overrides
functionality. I'm assuming you imported TextInput from forms? This should
work to change your *admin* display. Are trying to change your Admin panel
form or a form going out to the user?


class BandAdmin(admin.ModelAdmin):
formfield_overrides = {
CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
}
 I am trying to change a form going to the user.
 The form in the admin page __does__ show the size attribute in
 the HTML source code for input/text.

 So it appears that formfield_overrides only affects the admin
 page.

 I'm going to call this solved - given that I can "widen" the field
 with css.

 Thanks again Joe. You've been a great help and I've learned a lot.
 cheers

--
Tim Johnson
http://www.tj49.com

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/20190512220300.GF2372%40mail.akwebsoft.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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/8AA27AC7-87A9-4857-BFD3-929386B4EEE2%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why isn't user.photo being saved in UpdateView?

2018-12-01 Thread Jim Wombles
I solved the problem after digging around in the Django Forms related to 
ImageFields and FileFields.  I needed to add the  attribute in order for Django to process 
forms that contain ImageFields and/or FileFields.
#user_form.html

{% extends "base.html" %}
{% load crispy_forms_tags %}


{% block title %}{{ user.username }}{% endblock %}


{% block content %}

  {{ user.username }}
  
{% csrf_token %}
{{ form|crispy }}

  
Update
  

  

{% endblock %}




On Friday, November 30, 2018 at 5:06:33 PM UTC-5, Jim Wombles wrote:
>
> For some reason, the updateview will save all of the other user fields 
> (and update them if changed) to the database.  Do I need to handle the 
> user.photo field differently? 
>
> # views.py
> class UserUpdateView(LoginRequiredMixin, UpdateView):
>
> model = User
> fields = ["name", "photo", "city", "experience", "domain", "bio"]
>
> def get_success_url(self):
> return reverse("users:detail", kwargs={"username": self.request.
> user.username})
>
> def get_object(self):
> return User.objects.get(username=self.request.user.username)
>
> user_update_view = UserUpdateView.as_view()
>
>
> The form:
> # form.py
> from django.contrib.auth import get_user_model, forms
> from django.core.exceptions import ValidationError
> from django.utils.translation import ugettext_lazy as _
>
>
> User = get_user_model()
>
> class UserChangeForm(forms.UserChangeForm):
>
> class Meta(forms.UserChangeForm.Meta):
> model = User
>
>
>
>
> It does save the photo though in the Admin.
> # admin.py
> from django.contrib import admin
> from django.contrib.auth import admin as auth_admin
> from django.contrib.auth import get_user_model
>
> from lexpy.users.forms import UserChangeForm, UserCreationForm
>
> User = get_user_model()
>
> @admin.register(User)
> class UserAdmin(auth_admin.UserAdmin):
>
>
> form = UserChangeForm
> add_form = UserCreationForm
> fieldsets = (("User", {"fields": ("name", "photo", "height_field", 
> "width_field",
> "city", "experience", "domain", "bio")}),) + auth_admin.
> UserAdmin.fieldsets
> list_display = ["username", "name", "is_superuser"]
> search_fields = ["name"]
> Enter code here...
>
>
> My Models:
>
> # models.py
> from datetime import date
>
>
> from django.contrib.auth.models import AbstractUser
> from django.db import models
> from django.urls import reverse
> from django.utils.translation import ugettext_lazy as _
>
>
> def user_directory_path(instance, filename):
> #file will be uploaded to MEDIA_ROOT/user_/
> return 'user_{0}/{1}'.format(instance.username, filename)
>
>
> class User(AbstractUser):
> EXPERIENCE_BEGINNER = 'B'
> EXPERIENCE_BEGINT = 'BI'
> EXPERIENCE_INTERMEDIATE = 'I'
> EXPERIENCE_INTERVANCED = 'IA'
> EXPERIENCE_ADVANCED = 'A'
> DOMAIN_WEB_DEVELOPMENT = 'WD'
> DOMAIN_SCIENTIFIC_AND_NUMERIC = 'SN'
> DOMAIN_EDUCATION = 'E'
> DOMAIN_DESKTOP_GUIS = 'DG'
> DOMAIN_GAME_DEVELOPMENT = 'GD'
> DOMAIN_SOFTWARE_DEVELOPMENT = 'SD'
> DOMAIN_SCRIPTING = 'S'
>
>
> EXPERIENCE_CHOICES = (
> (EXPERIENCE_BEGINNER, 'Beginner'),
> (EXPERIENCE_BEGINT, 'Beginner to Intermediate'),
> (EXPERIENCE_INTERMEDIATE, 'Intermediate'),
> (EXPERIENCE_INTERVANCED, 'Intermediate to Advanced'),
> (EXPERIENCE_ADVANCED, 'Advanced / Professional'),
> )
>
>
> DOMAIN_CHOICES = (
> (DOMAIN_WEB_DEVELOPMENT, "Web Applications"),
> (DOMAIN_SCIENTIFIC_AND_NUMERIC, "Scientific or Numeric 
> Applications"),
> (DOMAIN_EDUCATION, "Education"),
> (DOMAIN_DESKTOP_GUIS, "Desktop Software (GUI's)"),
> (DOMAIN_GAME_DEVELOPMENT, "Game Development"),
> (DOMAIN_SOFTWARE_DEVELOPMENT, "Support Software"),
> (DOMAIN_SCRIPTING, "Scripting"),
> )
>
>
> # First Name and Last Name do not cover name patterns
> # around the globe.
> name = models.CharField(_("Name of User"), blank=True, max_length=255)
> photo = models.ImageField(upload_to=user_directory_path,
> blank=True,
> width_field="width_field",
> height_field="height_field")
> height_field = models.IntegerField(default=0)
> width

Why isn't user.photo being saved in UpdateView?

2018-11-30 Thread Jim Wombles
For some reason, the updateview will save all of the other user fields (and 
update them if changed) to the database.  Do I need to handle the 
user.photo field differently? 

# views.py
class UserUpdateView(LoginRequiredMixin, UpdateView):

model = User
fields = ["name", "photo", "city", "experience", "domain", "bio"]

def get_success_url(self):
return reverse("users:detail", kwargs={"username": self.request.user
.username})

def get_object(self):
return User.objects.get(username=self.request.user.username)

user_update_view = UserUpdateView.as_view()


The form:
# form.py
from django.contrib.auth import get_user_model, forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _


User = get_user_model()

class UserChangeForm(forms.UserChangeForm):

class Meta(forms.UserChangeForm.Meta):
model = User




It does save the photo though in the Admin.
# admin.py
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model

from lexpy.users.forms import UserChangeForm, UserCreationForm

User = get_user_model()

@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):


form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "photo", "height_field", 
"width_field",
"city", "experience", "domain", "bio")}),) + auth_admin.
UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser"]
search_fields = ["name"]
Enter code here...


My Models:

# models.py
from datetime import date


from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _


def user_directory_path(instance, filename):
#file will be uploaded to MEDIA_ROOT/user_/
return 'user_{0}/{1}'.format(instance.username, filename)


class User(AbstractUser):
EXPERIENCE_BEGINNER = 'B'
EXPERIENCE_BEGINT = 'BI'
EXPERIENCE_INTERMEDIATE = 'I'
EXPERIENCE_INTERVANCED = 'IA'
EXPERIENCE_ADVANCED = 'A'
DOMAIN_WEB_DEVELOPMENT = 'WD'
DOMAIN_SCIENTIFIC_AND_NUMERIC = 'SN'
DOMAIN_EDUCATION = 'E'
DOMAIN_DESKTOP_GUIS = 'DG'
DOMAIN_GAME_DEVELOPMENT = 'GD'
DOMAIN_SOFTWARE_DEVELOPMENT = 'SD'
DOMAIN_SCRIPTING = 'S'


EXPERIENCE_CHOICES = (
(EXPERIENCE_BEGINNER, 'Beginner'),
(EXPERIENCE_BEGINT, 'Beginner to Intermediate'),
(EXPERIENCE_INTERMEDIATE, 'Intermediate'),
(EXPERIENCE_INTERVANCED, 'Intermediate to Advanced'),
(EXPERIENCE_ADVANCED, 'Advanced / Professional'),
)


DOMAIN_CHOICES = (
(DOMAIN_WEB_DEVELOPMENT, "Web Applications"),
(DOMAIN_SCIENTIFIC_AND_NUMERIC, "Scientific or Numeric Applications"
),
(DOMAIN_EDUCATION, "Education"),
(DOMAIN_DESKTOP_GUIS, "Desktop Software (GUI's)"),
(DOMAIN_GAME_DEVELOPMENT, "Game Development"),
(DOMAIN_SOFTWARE_DEVELOPMENT, "Support Software"),
(DOMAIN_SCRIPTING, "Scripting"),
)


# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_("Name of User"), blank=True, max_length=255)
photo = models.ImageField(upload_to=user_directory_path,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
city = models.CharField(max_length=50, blank=True)
# Fix default
experience = models.CharField(max_length=2, choices=EXPERIENCE_CHOICES, 
blank=True, null=True)
domain = models.CharField(max_length=2, choices=DOMAIN_CHOICES, blank=
True, null=True)
bio = models.TextField(max_length=500, blank=True)


def get_absolute_url(self):
return reverse("users:detail", kwargs={"username": self.username})






 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/9a0c73a2-3e4c-41b8-b905-bb75639a16cf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


unable to do migrate when defining custom user model

2018-11-26 Thread Jim Lamb
Send us some code

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/da93fe62-c3d4-41c3-9e59-cad67c0ed80f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Logging a button click

2018-11-26 Thread Jim Lamb
I am trying to log a button click from a template. 
Can someone please help???
view.py

from django.shortcuts import render
from .models import UploadFile
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import logging
logger = logging.getLogger('download_user')


@login_required
def index(request):
client_ip = request.META['REMOTE_ADDR']
upload_list = UploadFile.objects.all().order_by('file')
filename = ''
for filename in upload_list:
print(filename.file)

if 'download' in request.POST:
logger.debug('user: {} |ip address: {} |downloaded file: 
{}'.format(request.user, client_ip, filename.file))

# for f in request.FILES.getlist('upload_list.file'):
# filename = f.name

page = request.GET.get('page', 1)
paginator = Paginator(upload_list, 20)
try:
uploads = paginator.page(page)
except PageNotAnInteger:
uploads = paginator.page(1)
except EmptyPage:
uploads = paginator.page(paginator.num_pages)
context = {
'uploads': uploads,
}
return render(request, 'uploads/index.html', context)

index.html

{% extends 'base.html' %}
{% block title %}Download Source Code{% endblock %}

{% block content %}
{% if user.is_authenticated %}



Download Source Code





Product
Name
File
Description
MD5 Hash
SHA256
Download




{% for upload in uploads %}
{% if upload.verified_by %}

{{ upload.products }}
{{ upload.name }}
{{ upload.file 
}}
{{ upload.description }}
{{ upload.md5sum }}
{{ upload.sha256sum }}

{% csrf_token %}

{##}
Download Software



{% endif %}
{% endfor %}


{% if uploads.has_other_pages %}
 
{% if uploads.has_previous %}

{% else %}

{% endif %}
{% for i in uploads.paginator.page_range %}
{% if uploads.number == i %}
{{ i }} (current)
{% else %}
{{ i }}
{% endif %}
{% endfor %}
{% if downloads.has_next %}

{% else %}

{% endif %}

{% endif %}





{% else %}


You are logged in.



{% endif %}


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/8223bd96-1989-4cc1-b75d-14cd0f9b4b4b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django performance issue that's troubling

2018-08-24 Thread Jim Illback
Thanks much, Tim. I’ll check it out - probably will need even more tuning down 
the road...

On Aug 24, 2018, at 1:00 PM, Tim Vogt (Tim Vogt) 
mailto:timtv...@gmail.com>> wrote:

Also found this perhaps helpfull
https://blog.labdigital.nl/working-with-huge-data-sets-in-django-169453bca049

Op 24 aug. 2018, om 21:28 heeft Jim Illback 
mailto:subaru...@hotmail.com>> het volgende geschreven:

Vijay, your suggestion worked. I had tried this previously but it was using a 
FBV and it didn’t work. But with this CBV app, it works perfectly. Thanks.

Matthew, I’ll definitely keep your suggestion in mind - maybe back on my FBV 
application if I refactor!

Thanks much to both of you!
Jim

On Aug 24, 2018, at 11:19 AM, Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:

It’s important that you set the widget to a HiddenInput.  It only has to render 
it with the current value.  If you are keeping the widget to be a Select widget 
and then setting a CSS class to make it hidden, the system will still have to 
load all 37K values.  I guess I’m missing something in your explanation.

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, August 24, 2018 1:16 PM
To: Django users
Subject: Re: Django performance issue that's troubling

Matthew, thanks - that was my original code, but even hidden, it has to fill in 
all possible values - 37K - so it takes multiple seconds.

Vijay, I’ll try your suggestion.

Thanks much,
Jim


On Aug 24, 2018, at 11:01 AM, Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:

You can keep the field, but change its widget to a HiddenInput.
https://stackoverflow.com/questions/6862250/change-a-django-form-field-to-a-hidden-field



From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Vijay Khemlani
Sent: Friday, August 24, 2018 12:59 PM
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Subject: Re: Django performance issue that's troubling

Please reply to the user group

"But, in order to have the update work, it needs the ForeignKey to the parent 
in the form"

As far as I know, it doesn't need to (if the entry already exists in the 
database and you are just editing it), you just need to set up the fields that 
you want to be editable by the user


On Fri, Aug 24, 2018 at 2:06 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, think of this is a parent - child relationship. I have 37K parents. Now 
I want to update a child of one of the parents. But, in order to have the 
update work, it needs the ForeignKey to the parent in the form. However, to add 
that key, Django must then allow it to update that field and thus has to fill 
in all 37K entries. Is there no way to tell Django that the FK relationship can 
not be changed? If I leave it off of the form, the update fails because it is a 
required field. If I add it to the form, Django has to allow all potential 
update values to be shown. What’s the way out of this mess?

Thanks,
Jim




Begin forwarded message:

From: Vijay Khemlani mailto:vkhem...@gmail.com>>
Subject: Re: Django performance issue that's troubling
Date: August 24, 2018 at 5:07:07 AM PDT
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Reply-To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>

To tell you the truth I couldn't understand some parts of your message, but if 
your AddictionForm is a ModelForm then you should be able to limit its fields 
to just the ones you want your users to be able to update.

https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/

Regards!



On Thu, Aug 23, 2018 at 8:19 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, you are exactly correct. Thank you much!

Now, knowing the problem, I still don’t have a great solution. Here’s how it is 
supposed to work.

Someone chooses a client from the list or a search. All the possible support 
records are shown, whether they exist or not, on a screen to hyperlink to one 
of them. If the record exists, the URL includes the PK and transfers to the 
UpdateView. This is similar for an AddView if the record does not exist. 
However, in the Update or Add, I don’t want the primary key changed. So, I hid 
the field (and thus all the records were read). However, now I can’t limit that 
field to only one value. If I format the entire SELECT tag with only one 
OPTION, Django gives an invalid expression for the ID or Name because it is 
based on my query set I passed in that fills out the values (ID and name). If I 
use the form’s field value, all the fields are read. Especially on an Add, I 
don’t know a way to fill the client ID field in such a way that Django will 
take it as valid.

My thoughts on possible solutions:
1. Override the get query set method to only 

Re: Django performance issue that's troubling

2018-08-24 Thread Jim Illback
Vijay, your suggestion worked. I had tried this previously but it was using a 
FBV and it didn’t work. But with this CBV app, it works perfectly. Thanks.

Matthew, I’ll definitely keep your suggestion in mind - maybe back on my FBV 
application if I refactor!

Thanks much to both of you!
Jim

On Aug 24, 2018, at 11:19 AM, Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:

It’s important that you set the widget to a HiddenInput.  It only has to render 
it with the current value.  If you are keeping the widget to be a Select widget 
and then setting a CSS class to make it hidden, the system will still have to 
load all 37K values.  I guess I’m missing something in your explanation.

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, August 24, 2018 1:16 PM
To: Django users
Subject: Re: Django performance issue that's troubling

Matthew, thanks - that was my original code, but even hidden, it has to fill in 
all possible values - 37K - so it takes multiple seconds.

Vijay, I’ll try your suggestion.

Thanks much,
Jim


On Aug 24, 2018, at 11:01 AM, Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:

You can keep the field, but change its widget to a HiddenInput.
https://stackoverflow.com/questions/6862250/change-a-django-form-field-to-a-hidden-field



From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Vijay Khemlani
Sent: Friday, August 24, 2018 12:59 PM
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Subject: Re: Django performance issue that's troubling

Please reply to the user group

"But, in order to have the update work, it needs the ForeignKey to the parent 
in the form"

As far as I know, it doesn't need to (if the entry already exists in the 
database and you are just editing it), you just need to set up the fields that 
you want to be editable by the user


On Fri, Aug 24, 2018 at 2:06 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, think of this is a parent - child relationship. I have 37K parents. Now 
I want to update a child of one of the parents. But, in order to have the 
update work, it needs the ForeignKey to the parent in the form. However, to add 
that key, Django must then allow it to update that field and thus has to fill 
in all 37K entries. Is there no way to tell Django that the FK relationship can 
not be changed? If I leave it off of the form, the update fails because it is a 
required field. If I add it to the form, Django has to allow all potential 
update values to be shown. What’s the way out of this mess?

Thanks,
Jim




Begin forwarded message:

From: Vijay Khemlani mailto:vkhem...@gmail.com>>
Subject: Re: Django performance issue that's troubling
Date: August 24, 2018 at 5:07:07 AM PDT
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Reply-To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>

To tell you the truth I couldn't understand some parts of your message, but if 
your AddictionForm is a ModelForm then you should be able to limit its fields 
to just the ones you want your users to be able to update.

https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/

Regards!



On Thu, Aug 23, 2018 at 8:19 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, you are exactly correct. Thank you much!

Now, knowing the problem, I still don’t have a great solution. Here’s how it is 
supposed to work.

Someone chooses a client from the list or a search. All the possible support 
records are shown, whether they exist or not, on a screen to hyperlink to one 
of them. If the record exists, the URL includes the PK and transfers to the 
UpdateView. This is similar for an AddView if the record does not exist. 
However, in the Update or Add, I don’t want the primary key changed. So, I hid 
the field (and thus all the records were read). However, now I can’t limit that 
field to only one value. If I format the entire SELECT tag with only one 
OPTION, Django gives an invalid expression for the ID or Name because it is 
based on my query set I passed in that fills out the values (ID and name). If I 
use the form’s field value, all the fields are read. Especially on an Add, I 
don’t know a way to fill the client ID field in such a way that Django will 
take it as valid.

My thoughts on possible solutions:
1. Override the get query set method to only pass in the single record - will 
that work?
2. I’ve been trying to show the field in a  tag and override the View’s post 
method by aftering is_valid(), but it always returns invalid expression errors.

What am I missing?

Thanks much again -
Jim




On Aug 23, 2018, at 3:48 PM, Vijay Khemlani 
mailto:vkhem...@gmail.com>> wrote:

Maybe your update form has a field related to a model with thousands of 
r

Re: Django performance issue that's troubling

2018-08-24 Thread Jim Illback
Matthew, thanks - that was my original code, but even hidden, it has to fill in 
all possible values - 37K - so it takes multiple seconds.

Vijay, I’ll try your suggestion.

Thanks much,
Jim

On Aug 24, 2018, at 11:01 AM, Matthew Pava 
mailto:matthew.p...@iss.com>> wrote:

You can keep the field, but change its widget to a HiddenInput.
https://stackoverflow.com/questions/6862250/change-a-django-form-field-to-a-hidden-field



From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Vijay Khemlani
Sent: Friday, August 24, 2018 12:59 PM
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Subject: Re: Django performance issue that's troubling

Please reply to the user group

"But, in order to have the update work, it needs the ForeignKey to the parent 
in the form"

As far as I know, it doesn't need to (if the entry already exists in the 
database and you are just editing it), you just need to set up the fields that 
you want to be editable by the user


On Fri, Aug 24, 2018 at 2:06 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, think of this is a parent - child relationship. I have 37K parents. Now 
I want to update a child of one of the parents. But, in order to have the 
update work, it needs the ForeignKey to the parent in the form. However, to add 
that key, Django must then allow it to update that field and thus has to fill 
in all 37K entries. Is there no way to tell Django that the FK relationship can 
not be changed? If I leave it off of the form, the update fails because it is a 
required field. If I add it to the form, Django has to allow all potential 
update values to be shown. What’s the way out of this mess?

Thanks,
Jim



Begin forwarded message:

From: Vijay Khemlani mailto:vkhem...@gmail.com>>
Subject: Re: Django performance issue that's troubling
Date: August 24, 2018 at 5:07:07 AM PDT
To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>
Reply-To: django-users@googlegroups.com<mailto:django-users@googlegroups.com>

To tell you the truth I couldn't understand some parts of your message, but if 
your AddictionForm is a ModelForm then you should be able to limit its fields 
to just the ones you want your users to be able to update.

https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/

Regards!



On Thu, Aug 23, 2018 at 8:19 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
Vijay, you are exactly correct. Thank you much!

Now, knowing the problem, I still don’t have a great solution. Here’s how it is 
supposed to work.

Someone chooses a client from the list or a search. All the possible support 
records are shown, whether they exist or not, on a screen to hyperlink to one 
of them. If the record exists, the URL includes the PK and transfers to the 
UpdateView. This is similar for an AddView if the record does not exist. 
However, in the Update or Add, I don’t want the primary key changed. So, I hid 
the field (and thus all the records were read). However, now I can’t limit that 
field to only one value. If I format the entire SELECT tag with only one 
OPTION, Django gives an invalid expression for the ID or Name because it is 
based on my query set I passed in that fills out the values (ID and name). If I 
use the form’s field value, all the fields are read. Especially on an Add, I 
don’t know a way to fill the client ID field in such a way that Django will 
take it as valid.

My thoughts on possible solutions:
1. Override the get query set method to only pass in the single record - will 
that work?
2. I’ve been trying to show the field in a  tag and override the View’s post 
method by aftering is_valid(), but it always returns invalid expression errors.

What am I missing?

Thanks much again -
Jim



On Aug 23, 2018, at 3:48 PM, Vijay Khemlani 
mailto:vkhem...@gmail.com>> wrote:

Maybe your update form has a field related to a model with thousands of 
records? like rendering a select combo box with thousands of choices?

On Thu, Aug 23, 2018 at 5:30 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
I have a Django app in development that performed perfectly with about 20 
client records. Each client could have one or more support records and there 
are 40 potential support records, connected to the client with a ForeignKey 
(client_id). Then, I loading about 37K client records. Search queries perform 
almost instantaneously. A paginated list of support records with 40 pages and 
10 clients per page comes back in half a second. Great performance.

However, when I click on any record in the list to go to update a specific 
support record for that specific client (it uses the PK in the URL so is a 
direct call to the UpdateView routine), I get about 10 second response times 
and these kind of statistics from Django-debug-toolbar:
SQL: 5 queries, 20ms (so clearly not a DB related pe

Re: Django performance issue that's troubling

2018-08-23 Thread Jim Illback
Vijay, you are exactly correct. Thank you much!

Now, knowing the problem, I still don’t have a great solution. Here’s how it is 
supposed to work.

Someone chooses a client from the list or a search. All the possible support 
records are shown, whether they exist or not, on a screen to hyperlink to one 
of them. If the record exists, the URL includes the PK and transfers to the 
UpdateView. This is similar for an AddView if the record does not exist. 
However, in the Update or Add, I don’t want the primary key changed. So, I hid 
the field (and thus all the records were read). However, now I can’t limit that 
field to only one value. If I format the entire SELECT tag with only one 
OPTION, Django gives an invalid expression for the ID or Name because it is 
based on my query set I passed in that fills out the values (ID and name). If I 
use the form’s field value, all the fields are read. Especially on an Add, I 
don’t know a way to fill the client ID field in such a way that Django will 
take it as valid.

My thoughts on possible solutions:
1. Override the get query set method to only pass in the single record - will 
that work?
2. I’ve been trying to show the field in a  tag and override the View’s post 
method by aftering is_valid(), but it always returns invalid expression errors.

What am I missing?

Thanks much again -
Jim


On Aug 23, 2018, at 3:48 PM, Vijay Khemlani 
mailto:vkhem...@gmail.com>> wrote:

Maybe your update form has a field related to a model with thousands of 
records? like rendering a select combo box with thousands of choices?

On Thu, Aug 23, 2018 at 5:30 PM Jim Illback 
mailto:subaru...@hotmail.com>> wrote:
I have a Django app in development that performed perfectly with about 20 
client records. Each client could have one or more support records and there 
are 40 potential support records, connected to the client with a ForeignKey 
(client_id). Then, I loading about 37K client records. Search queries perform 
almost instantaneously. A paginated list of support records with 40 pages and 
10 clients per page comes back in half a second. Great performance.

However, when I click on any record in the list to go to update a specific 
support record for that specific client (it uses the PK in the URL so is a 
direct call to the UpdateView routine), I get about 10 second response times 
and these kind of statistics from Django-debug-toolbar:
SQL: 5 queries, 20ms (so clearly not a DB related performance issue)
TIME:  Resource usage:
User CPU time 8827 msec
System CPU time 137 msec
Elapsed time 9003 msec
Context switches 1 voluntary, 9639 involuntary
Browser timing:
domLoading 9026 (+52130) msec

CACHE: 0 calls in 0.00ms (so clearly not a cache issue either)

Here are some details: Django 2.1, python 3.6.3
Hardware: iMac with 32GB, i7 quad core
Installed apps: Bootstrap3 v9.1.0, crispy forms v1.7.0, easyPDF v0.1.1, 
registration-redux v2.2, Pillow v4.3.0

Here’s one of the specific UpdateView routines being executed - there are only 
5 fields in the AddictionForm plus the prime key (no image or file attachments).

class AddictionUpdate(PermissionRequiredMixin, UpdateView):
model = Addiction
form_class = AddictionForm
template_name = 'addiction_update.html'
permission_required = 'clientapp.change_addiction'

The slow response appears to be on UpdateView pages only, even though all 
updates are called with the prime key (ID) in the URL. Can anyone give me 
guidance where to look for improving the performance? Why all the involuntary 
context switches? Why the large domLoading time?

Thanks in advance -
Jim

--
You received this message because you are subscribed to the Google 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/76F251D2-A429-4700-9F69-053673BDB91F%40hotmail.com<https://groups.google.com/d/msgid/django-users/76F251D2-A429-4700-9F69-053673BDB91F%40hotmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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

Django performance issue that's troubling

2018-08-23 Thread Jim Illback
I have a Django app in development that performed perfectly with about 20 
client records. Each client could have one or more support records and there 
are 40 potential support records, connected to the client with a ForeignKey 
(client_id). Then, I loading about 37K client records. Search queries perform 
almost instantaneously. A paginated list of support records with 40 pages and 
10 clients per page comes back in half a second. Great performance.

However, when I click on any record in the list to go to update a specific 
support record for that specific client (it uses the PK in the URL so is a 
direct call to the UpdateView routine), I get about 10 second response times 
and these kind of statistics from Django-debug-toolbar:
SQL: 5 queries, 20ms (so clearly not a DB related performance issue)
TIME:  Resource usage:
User CPU time 8827 msec
System CPU time 137 msec
Elapsed time 9003 msec
Context switches 1 voluntary, 9639 involuntary
Browser timing:
domLoading 9026 (+52130) msec

CACHE: 0 calls in 0.00ms (so clearly not a cache issue either)

Here are some details: Django 2.1, python 3.6.3
Hardware: iMac with 32GB, i7 quad core
Installed apps: Bootstrap3 v9.1.0, crispy forms v1.7.0, easyPDF v0.1.1, 
registration-redux v2.2, Pillow v4.3.0

Here’s one of the specific UpdateView routines being executed - there are only 
5 fields in the AddictionForm plus the prime key (no image or file attachments).

class AddictionUpdate(PermissionRequiredMixin, UpdateView):
model = Addiction
form_class = AddictionForm
template_name = 'addiction_update.html'
permission_required = 'clientapp.change_addiction'

The slow response appears to be on UpdateView pages only, even though all 
updates are called with the prime key (ID) in the URL. Can anyone give me 
guidance where to look for improving the performance? Why all the involuntary 
context switches? Why the large domLoading time?

Thanks in advance -
Jim

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/76F251D2-A429-4700-9F69-053673BDB91F%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django DateField

2018-07-05 Thread Jim Illback
Add another field, say asap = model.BooleanField(default=False), sort by asap, 
date in reverse. The field asap True values will be sorted first, then the asap 
False will be sorted by date. You may want to ensure asap = False only if date 
is not None.

On Jul 5, 2018, at 10:05 AM, 'dtdave' via Django users 
mailto:django-users@googlegroups.com>> wrote:

I have a model that contains a datefield which signifies the start date for a 
task.
My modelmanager filters the tasks by the start date and the template lists them 
in the date descending order. Everything is fine with this.

However, now I have been asked to change this so that some projects have a 
start date of ASAP and others have date.
These then need to be listed in my template with ASAP tasks coming first and 
then those with a start date coming in descending order.

I am at a loss as to how to achieve this so would welcome any pointers or ideas.
Thanks

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to 
django-users+unsubscr...@googlegroups.com.
To post to this group, send email to 
django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fd2be4aa-408f-4221-9950-ba7a9af96e9c%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 https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/BE01C11E-498D-486E-88F8-AD96C67D571A%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


django.contrib.admin

2018-06-29 Thread Jim Lamb
How can I override the list_display to add fields in my admin console for 
users?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/e7613363-d11a-43cb-9849-7af5ef864f04%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

2018-04-30 Thread Jim Illback
If anyone is interested in a solution I found, it is at 
www.webforefront.com/django/formprocessing.html<http://www.webforefront.com/django/formprocessing.html>.
 Great documentation there, and you can read why it works, too.

Here are some code snippets used to test my situation.

In forms.py and in a unique form for update (not create) - JimtestUpdateForm:
def __init__(self, *args, **kwargs):
super(JimtestUpdateForm, self).__init__(*args, **kwargs) # invoke the 
default first
initial_arguments = kwargs.get('initial', None)
if initial_arguments:
ci_id = initial_arguments.get('ci_id', None)
if ci_id:
assign_qs = 
Checkin.objects.values('choretime').filter(choretime_id__isnull=False)
unassign_qs = ChoreTime.objects.exclude(pk__in=assign_qs)
ci_qs = Checkin.objects.get(id=ci_id)
ct_qs = ChoreTime.objects.filter(id=ci_qs.choretime_id)
new_qs = unassign_qs | ct_qs # union unassigned with the 
client’s single assignment
self.fields['choretime'].queryset = new_qs # update the choices 
shown
self.fields['choretime'].widget.choices = 
self.fields['choretime'].choices # update the widget (may not need this - just 
a hunch - not tested omitting it yet

In views.py under the CB dispatch method:
if request.method == ‘GET’:
form = JimtestUpdateForm(instance=checkin, initial={'ci_id': checkinid}) # pass 
in the value(s) needed in __init__()
...

That is pretty much it - simple if you have the proper documentation on how to 
initialize forms.

Jim

On Apr 27, 2018, at 11:39 AM, Jim Illback 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:

Absolutely agree. The “instance” (your note) is for Checkin and it includes a 
ForeignKey field to ChoreTime, which is a selection (choice field). But, I want 
that choice field to be limited for the forms to be only what has been not 
assigned yet. That way the user on the page will know that any shown pick is 
available. Otherwise, there are over 100 choices and no guidance as to what is 
truly available or already filled.

I have to alter the query set for that field. On a CreateView, I have it 
working perfectly (it’s shown below). However, on an UpdateView, the person’s 
choice is one of the “unavailable”. So, I’m trying to add just that one choice 
back into the query set before showing it on the form. Therefore, I need both 
the URL (to get the update’s choice) and the pre-form display method override 
(to exclude assigned entries) where I can override the field’s query set.

Thanks for the inputs, Matthew. I hope I’ve made it clearer. If you think 
there’s a better overall approach, I’m all ears!
Jim

On Apr 27, 2018, at 11:01 AM, Matthew Pava 
<matthew.p...@iss.com<mailto:matthew.p...@iss.com>> wrote:

That ID in the URL should be taken care of in the view, not the form.  You pass 
the object in as keyword instance to instantiate the form.  How are you 
defining your form in the view?

Typically, you would do something like this:

instance = CheckIn.objects.get(pk=self.kwargs.get(‘pk’))
form = CheckInForm(request.POST or None, instance=instance)

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, April 27, 2018 11:33 AM
To: Django users
Subject: Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

I also need to have the specific ID specified in the URL, so that is the other 
part needed. I’ve successfully done your suggestion for CreateView. Now, I just 
can’t seem to get UpdateView to work properly.

Thanks much!
Jim


On Apr 27, 2018, at 9:20 AM, Matthew Pava 
<matthew.p...@iss.com<mailto:matthew.p...@iss.com>> wrote:

In the form’s __init__ method, you’ll have to modify the queryset of the field.

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[‘choretime’].queryset |= 
ChoiceTime.objects.filter(pk=self.instance.pk)

I hope that helps!

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, April 27, 2018 11:16 AM
To: Django users
Subject: Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

To make this easier, here is just a simple question.

Does Django give a method that can be overridden while processing a form which 
has access to the incoming URL parameters and precedes the display of the 
form’s fields, specifically being able to alter the fields’s query set before 
it is displayed?

Thanks for any help to answer this question.

Jim Illback



On Apr 25, 2018, at 10:41 AM, Jim Illback 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:

I wondered if anyone has had to alter the queryset behind a model form’s 
foreign

Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

2018-04-27 Thread Jim Illback
Absolutely agree. The “instance” (your note) is for Checkin and it includes a 
ForeignKey field to ChoreTime, which is a selection (choice field). But, I want 
that choice field to be limited for the forms to be only what has been not 
assigned yet. That way the user on the page will know that any shown pick is 
available. Otherwise, there are over 100 choices and no guidance as to what is 
truly available or already filled.

I have to alter the query set for that field. On a CreateView, I have it 
working perfectly (it’s shown below). However, on an UpdateView, the person’s 
choice is one of the “unavailable”. So, I’m trying to add just that one choice 
back into the query set before showing it on the form. Therefore, I need both 
the URL (to get the update’s choice) and the pre-form display method override 
(to exclude assigned entries) where I can override the field’s query set.

Thanks for the inputs, Matthew. I hope I’ve made it clearer. If you think 
there’s a better overall approach, I’m all ears!
Jim

On Apr 27, 2018, at 11:01 AM, Matthew Pava 
<matthew.p...@iss.com<mailto:matthew.p...@iss.com>> wrote:

That ID in the URL should be taken care of in the view, not the form.  You pass 
the object in as keyword instance to instantiate the form.  How are you 
defining your form in the view?

Typically, you would do something like this:

instance = CheckIn.objects.get(pk=self.kwargs.get(‘pk’))
form = CheckInForm(request.POST or None, instance=instance)

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, April 27, 2018 11:33 AM
To: Django users
Subject: Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

I also need to have the specific ID specified in the URL, so that is the other 
part needed. I’ve successfully done your suggestion for CreateView. Now, I just 
can’t seem to get UpdateView to work properly.

Thanks much!
Jim


On Apr 27, 2018, at 9:20 AM, Matthew Pava 
<matthew.p...@iss.com<mailto:matthew.p...@iss.com>> wrote:

In the form’s __init__ method, you’ll have to modify the queryset of the field.

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[‘choretime’].queryset |= 
ChoiceTime.objects.filter(pk=self.instance.pk)

I hope that helps!

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, April 27, 2018 11:16 AM
To: Django users
Subject: Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

To make this easier, here is just a simple the question.

Does Django give a method that can be overridden while processing a form which 
has access to the incoming URL parameters and precedes the display of the 
form’s fields, specifically being able to alter the fields’s query set before 
it is displayed?

Thanks for any help to answer this question.

Jim Illback



On Apr 25, 2018, at 10:41 AM, Jim Illback 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:

I wondered if anyone has had to alter the queryset behind a model form’s 
foreign key field which presents as a model choice field?
Briefly, I have a client attribute table with the foreign key to a chore/time 
table. For an add of the client attribute table, I want to limit entries to 
unassigned chore/time combinations only. This works perfectly during my 
CreateView. Here are some extracts to show specifics:
Models.py:
class ChoreTime(models.Model):
chore = models.ForeignKey(Chore, on_delete=models.CASCADE)
time = models.ForeignKey(TimePeriod, on_delete=models.CASCADE)
priority = models.BooleanField(default=False)
…
class Checkin(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
choretime = models.ForeignKey(ChoreTime, on_delete=models.CASCADE)
…
Forms.py:
class CheckinForm(forms.ModelForm):
assigned_qs = 
Checkin.objects.values(‘choretime').filter(choretime_id__isnull=False)
choretime = 
forms.ModelChoiceField(queryset=ChoreTime.objects.exclude(pk__in=assigned_qs))
…
However, I cannot get the any design to work on an UpdateView form. Using the 
same form as above, the current value does not even show up – it is blank – 
because, of course, that entry is already assigned so is excluded.
What I’d like is to have the above exclusions BUT be able to also add in the 
single entry assigned to the client being updated – so the entry will show that 
specific assignment (as well as limiting any possible change options to 
unassigned values - just like on the Create).
The problems with various approaches I’ve tried are:

1. Anything done before the form is fully assembled won’t have the existing 
form’s Checkin ID value (which is part of the URL, just BTW). This is needed to 
look up and add the existing entry. So, having a database view won’t work 
without being able to

Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

2018-04-27 Thread Jim Illback
I also need to have the specific ID specified in the URL, so that is the other 
part needed. I’ve successfully done your suggestion for CreateView. Now, I just 
can’t seem to get UpdateView to work properly.

Thanks much!
Jim

On Apr 27, 2018, at 9:20 AM, Matthew Pava 
<matthew.p...@iss.com<mailto:matthew.p...@iss.com>> wrote:

In the form’s __init__ method, you’ll have to modify the queryset of the field.

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[‘choretime’].queryset |= 
ChoiceTime.objects.filter(pk=self.instance.pk)

I hope that helps!

From: django-users@googlegroups.com<mailto:django-users@googlegroups.com> 
[mailto:django-users@googlegroups.com] On Behalf Of Jim Illback
Sent: Friday, April 27, 2018 11:16 AM
To: Django users
Subject: Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

To make this easier, here is just a simple the question.

Does Django give a method that can be overridden while processing a form which 
has access to the incoming URL parameters and precedes the display of the 
form’s fields, specifically being able to alter the fields’s query set before 
it is displayed?

Thanks for any help to answer this question.

Jim Illback


On Apr 25, 2018, at 10:41 AM, Jim Illback 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:

I wondered if anyone has had to alter the queryset behind a model form’s 
foreign key field which presents as a model choice field?
Briefly, I have a client attribute table with the foreign key to a chore/time 
table. For an add of the client attribute table, I want to limit entries to 
unassigned chore/time combinations only. This works perfectly during my 
CreateView. Here are some extracts to show specifics:
Models.py:
class ChoreTime(models.Model):
chore = models.ForeignKey(Chore, on_delete=models.CASCADE)
time = models.ForeignKey(TimePeriod, on_delete=models.CASCADE)
priority = models.BooleanField(default=False)
…
class Checkin(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
choretime = models.ForeignKey(ChoreTime, on_delete=models.CASCADE)
…
Forms.py:
class CheckinForm(forms.ModelForm):
assigned_qs = 
Checkin.objects.values(‘choretime').filter(choretime_id__isnull=False)
choretime = 
forms.ModelChoiceField(queryset=ChoreTime.objects.exclude(pk__in=assigned_qs))
…
However, I cannot get the any design to work on an UpdateView form. Using the 
same form as above, the current value does not even show up – it is blank – 
because, of course, that entry is already assigned so is excluded.
What I’d like is to have the above exclusions BUT be able to also add in the 
single entry assigned to the client being updated – so the entry will show that 
specific assignment (as well as limiting any possible change options to 
unassigned values - just like on the Create).
The problems with various approaches I’ve tried are:

1. Anything done before the form is fully assembled won’t have the existing 
form’s Checkin ID value (which is part of the URL, just BTW). This is needed to 
look up and add the existing entry. So, having a database view won’t work 
without being able to communicate the existing person’s assignment ID to the 
view. Similarly, using an override queryset on the form, like done above for 
the Create, needs that ID, too.

2. If I do the queries in the class's GET method routine as ORM objects, I 
must use UNION (a union of the exclusions as above plus the existing update 
client’s assignment). That union option keeps giving an error that one of the 
ORM querysets is not a queryset. However, they are both using 
“.objects.filter…”. It seems like complex queries don’t work with the 
union command. If I use raw SQL, the query works but the assignment to the 
choretime field’s queryset fails.

Does anyone have experience with this sort of behavior and be willing to give 
guidance?

--
You received this message because you are subscribed to the Google 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/F0B95720-C669-4CE5-912E-5167E3B89DFE%40hotmail.com<https://groups.google.com/d/msgid/django-users/F0B95720-C669-4CE5-912E-5167E3B89DFE%40hotmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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

Re: Dynamically altering a (ForeignKey) ModelChoiceField’s values

2018-04-27 Thread Jim Illback
To make this easier, here is just a simple the question.

Does Django give a method that can be overridden while processing a form which 
has access to the incoming URL parameters and precedes the display of the 
form’s fields, specifically being able to alter the fields’s query set before 
it is displayed?

Thanks for any help to answer this question.

Jim Illback

On Apr 25, 2018, at 10:41 AM, Jim Illback 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:

I wondered if anyone has had to alter the queryset behind a model form’s 
foreign key field which presents as a model choice field?
Briefly, I have a client attribute table with the foreign key to a chore/time 
table. For an add of the client attribute table, I want to limit entries to 
unassigned chore/time combinations only. This works perfectly during my 
CreateView. Here are some extracts to show specifics:
Models.py:
class ChoreTime(models.Model):
chore = models.ForeignKey(Chore, on_delete=models.CASCADE)
time = models.ForeignKey(TimePeriod, on_delete=models.CASCADE)
priority = models.BooleanField(default=False)
…
class Checkin(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
choretime = models.ForeignKey(ChoreTime, on_delete=models.CASCADE)
…
Forms.py:
class CheckinForm(forms.ModelForm):
assigned_qs = 
Checkin.objects.values(‘choretime').filter(choretime_id__isnull=False)
choretime = 
forms.ModelChoiceField(queryset=ChoreTime.objects.exclude(pk__in=assigned_qs))
…
However, I cannot get the any design to work on an UpdateView form. Using the 
same form as above, the current value does not even show up – it is blank – 
because, of course, that entry is already assigned so is excluded.
What I’d like is to have the above exclusions BUT be able to also add in the 
single entry assigned to the client being updated – so the entry will show that 
specific assignment (as well as limiting any possible change options to 
unassigned values - just like on the Create).
The problems with various approaches I’ve tried are:

1. Anything done before the form is fully assembled won’t have the existing 
form’s Checkin ID value (which is part of the URL, just BTW). This is needed to 
look up and add the existing entry. So, having a database view won’t work 
without being able to communicate the existing person’s assignment ID to the 
view. Similarly, using an override queryset on the form, like done above for 
the Create, needs that ID, too.

2. If I do the queries in the class's GET method routine as ORM objects, I 
must use UNION (a union of the exclusions as above plus the existing update 
client’s assignment). That union option keeps giving an error that one of the 
ORM querysets is not a queryset. However, they are both using 
“.objects.filter…”. It seems like complex queries don’t work with the 
union command. If I use raw SQL, the query works but the assignment to the 
choretime field’s queryset fails.
Does anyone have experience with this sort of behavior and be willing to give 
guidance?

--
You received this message because you are subscribed to the Google 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/F0B95720-C669-4CE5-912E-5167E3B89DFE%40hotmail.com<https://groups.google.com/d/msgid/django-users/F0B95720-C669-4CE5-912E-5167E3B89DFE%40hotmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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


Dynamically altering a (ForeignKey) ModelChoiceField’s values

2018-04-25 Thread Jim Illback
I wondered if anyone has had to alter the queryset behind a model form’s 
foreign key field which presents as a model choice field?
Briefly, I have a client attribute table with the foreign key to a chore/time 
table. For an add of the client attribute table, I want to limit entries to 
unassigned chore/time combinations only. This works perfectly during my 
CreateView. Here are some extracts to show specifics:
Models.py:
class ChoreTime(models.Model):
chore = models.ForeignKey(Chore, on_delete=models.CASCADE)
time = models.ForeignKey(TimePeriod, on_delete=models.CASCADE)
priority = models.BooleanField(default=False)
…
class Checkin(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
choretime = models.ForeignKey(ChoreTime, on_delete=models.CASCADE)
…
Forms.py:
class CheckinForm(forms.ModelForm):
assigned_qs = 
Checkin.objects.values(‘choretime').filter(choretime_id__isnull=False)
choretime = 
forms.ModelChoiceField(queryset=ChoreTime.objects.exclude(pk__in=assigned_qs))
…
However, I cannot get the any design to work on an UpdateView form. Using the 
same form as above, the current value does not even show up – it is blank – 
because, of course, that entry is already assigned so is excluded.
What I’d like is to have the above exclusions BUT be able to also add in the 
single entry assigned to the client being updated – so the entry will show that 
specific assignment (as well as limiting any possible change options to 
unassigned values - just like on the Create).
The problems with various approaches I’ve tried are:

1. Anything done before the form is fully assembled won’t have the existing 
form’s Checkin ID value (which is part of the URL, just BTW). This is needed to 
look up and add the existing entry. So, having a database view won’t work 
without being able to communicate the existing person’s assignment ID to the 
view. Similarly, using an override queryset on the form, like done above for 
the Create, needs that ID, too.

2. If I do the queries in the class's GET method routine as ORM objects, I 
must use UNION (a union of the exclusions as above plus the existing update 
client’s assignment). That union option keeps giving an error that one of the 
ORM querysets is not a queryset. However, they are both using 
“.objects.filter…”. It seems like complex queries don’t work with the 
union command. If I use raw SQL, the query works but the assignment to the 
choretime field’s queryset fails.
Does anyone have experience with this sort of behavior and be willing to give 
guidance?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/F0B95720-C669-4CE5-912E-5167E3B89DFE%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Polls tutorial suggested mysite/mysite/urls.py improvement

2017-08-26 Thread Jim Fuqua
I agree.  Anyone experienced in Django would not be confused.  I have been 
away from Python for over ten years and totally new to Django.  There are a 
number of such issues in the tutorial that got me "off track".   

A useful feature for the total novice would be a link to a folder with 
a correct copy of all "mysite" files at the end of each section.  If the 
novice fails to include a file or made some other simple mistake they could 
get back "on track".  I did not get "off track" on this one but I did on 
several others. They were careless mistakes, but for a novice, the only way 
out is usually to completely start over.

The tutorial says "*When starting your first real project, however, you may 
want to use a more scalable database like PostgreSQL, to avoid 
database-switching headaches down the road.*". That is an invitation to the 
novice to simultaneously take a much more complex path.  A link to some 
basic PostgreSQL issues like how to drop the "mysite" PostgresSQL database 
and start over would be helpful.  With sqlite3 it is easy to 
erase everything and start over.  With Postgres, the changes to the 
database are not so easily undone. I finally figured out how to change the 
"mysite" user and drop the database, but it was not easy. A simple "DROP 
DATABASE "mysite"; does not do the job without changing the database owner 
and killing other users of the database before dropping the database.

Simple UX comments from novices concerning the Tutorial could make the life 
of those who follow much easier.  No expert is a good UX judge of any 
tutorial from the perspective of a novice.

jimfuqua

On Saturday, August 26, 2017 at 2:51:51 AM UTC-5, Mike Dewhirst wrote:
>
> A potential new Django user (a programmer of many decades experience) 
> tried Django at my suggestion and struck a problem. Eventually he 
> tracked me down and challenged me to prove the problem. 
>
> I found the problem and feel that the Polls tutorial docs can be easily 
> improved. 
>
> https://docs.djangoproject.com/en/1.11/intro/tutorial01/ 
>
> In the "Write your first view" section it says ... 
>
> The next step is to point the root URLconf at the |polls.urls| module. 
> In |mysite/urls.py|, add an import for |django.conf.urls.include| and 
> insert an |include()| 
>  
>
> in the |urlpatterns| list, so you have: 
>
> mysite/urls.py 
>
> from  django.conf.urls  import  include,  url from django.contrib  
> import  admin 
>
> urlpatterns  =  [ 
>   url(r'^polls/',  include('polls.urls')), 
>   url(r'^admin/',  admin.site.urls), 
> ] 
>
>
> The problem is we have two mysite dirs. The docs are helpful in 
> suggesting you copy code to paste into urls.py so the focus is on the 
> code rather than where to put it. On not finding a urls.py in the outer 
> mysite dir he created one. 
>
> The suggestion for improving the docs here is to change the heading line 
> above from 
>   mysite/urls.py 
> to 
>   mysite/mysite/urls.py 
>
> Alternatively, make a pointed reference to the earlier section in the 
> page where startproject created the *inner* mysite dir containing the 
> target urls.py. For example, by adding words to the effect that the 
> inner mysite/urls.py file will be instrumental in the "hello world" step 
> later in the tutorial. 
>
> Cheers 
>
> Mike 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/e613b227-cc88-46ce-927c-d635ac1c51f5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: A lot of Problems with Migrating (conceptual)

2017-08-18 Thread Jim Illback
Excellent - thanks much.

On Aug 18, 2017, at 4:02 PM, knbk 
<marten.k...@gmail.com<mailto:marten.k...@gmail.com>> wrote:

There are various reasons why you should never execute queries at startup. One 
you've seen: it makes it impossible to migrate a new database. Other reasons 
include that the choices are cached and are only renewed when the server 
restarts, and that when running tests, the query is executed before the test 
database is set up and will run on the main database.

The solution in this case is to use a ModelChoiceField[1], i.e.:

category = forms.ModelChoiceField(queryset=Category.objects.all(), 
required=False)

This allows to pass in a queryset which is evaluated whenever the field is used 
to make sure the values are up-to-date. Since querysets are lazy, this won't 
execute any queries on startup.

[1] https://docs.djangoproject.com/en/1.11/ref/forms/fields/#modelchoicefield

On Saturday, August 19, 2017 at 12:14:48 AM UTC+2, subaru_87 wrote:
Here’s a “problem” with migrations that I’ve had. It only occurs on a first 
time installation (like a first-time upload to Heroku, for example).

In forms.py, I have a field dependent upon a column in another table (Category):
category = forms.TypedChoiceField(required=False, 
choices=[(category.pk<http://category.pk/>, 
category.name<http://category.name/>) for category in Category.objects.all()])

Running makemigrations or migrate if there’s no pre-existing database with a 
table named “Category” gives an error saying as much. However, I’m expecting 
migrate to create the tables required. Therefore, it’s a catch-22.

Of course, the “easy” answer is to comment out the above code, add in:
 category = forms.CharField(max_length=12)
And run the initial migrations. Then, turn around and comment out that same 
code, uncomment the real code shown above, and run migrations again. It works, 
but it seems a bit awkward.

Has anyone else had this issue? Or am I doing something wrong?

Thanks much,
Jim Illback


On Aug 18, 2017, at 1:21 AM, James Bennett <ubern...@gmail.com> 
wrote:

On Thu, Aug 17, 2017 at 1:03 PM, Antonis Christofides 
<ant...@djangodeployment.com> wrote:

Second, just to make things clear, the word "migration" has two meanings. The 
original meaning of migration is to switch to another software system (e.g. 
migrate from MySQL to PostgreSQL, or migrate a repository from subversion to 
git). In Django, the term "migration" means something else: to update the 
database to the new schema. In my opinion this terminology is wrong and 
confusing (apparently it comes from Ruby on Rails, but I'm not certain), and a 
better one would have been "dbupdate" or something, but since it's migration 
we'll keep it and you'll have to understand which meaning is meant in each case.

An important thing worth knowing is that Django's migration framework does 
*not* only track the database schema. It also tracks the state of the Python 
classes which define the models, including options which do not affect the 
underlying DB schema, and making such changes to a model will create the need 
for a migration.

This is absolutely necessary, though, because the migration framework generates 
a frozen snapshot of the state at each migration, so that you can access the 
ORM to do things like data updates via the RunPython migration operator. If you 
were to change, say, the default ordering of a model without also generating a 
migration to record that change (even though it has no effect on the database 
schema), you could run into trouble if you later removed a field referenced by 
the old ordering, since one of the intermediate ORM snapshots would attempt to 
order queries by a now-nonexistent column.

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users...@googlegroups.com.
To post to this group, send email to djang...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAL13Cg_0p1pMtMR2y2eGry1UhQaSRpswntcnMWtHNdPgV1Ph9w%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CAL13Cg_0p1pMtMR2y2eGry1UhQaSRpswntcnMWtHNdPgV1Ph9w%40mail.gmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.


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

Re: A lot of Problems with Migrating (conceptual)

2017-08-18 Thread Jim Illback
Here’s a “problem” with migrations that I’ve had. It only occurs on a first 
time installation (like a first-time upload to Heroku, for example).

In forms.py, I have a field dependent upon a column in another table (Category):
category = forms.TypedChoiceField(required=False, choices=[(category.pk, 
category.name) for category in Category.objects.all()])

Running makemigrations or migrate if there’s no pre-existing database with a 
table named “Category” gives an error saying as much. However, I’m expecting 
migrate to create the tables required. Therefore, it’s a catch-22.

Of course, the “easy” answer is to comment out the above code, add in:
 category = forms.CharField(max_length=12)
And run the initial migrations. Then, turn around and comment out that same 
code, uncomment the real code shown above, and run migrations again. It works, 
but it seems a bit awkward.

Has anyone else had this issue? Or am I doing something wrong?

Thanks much,
Jim Illback


On Aug 18, 2017, at 1:21 AM, James Bennett 
<ubernost...@gmail.com<mailto:ubernost...@gmail.com>> wrote:

On Thu, Aug 17, 2017 at 1:03 PM, Antonis Christofides 
<anto...@djangodeployment.com<mailto:anto...@djangodeployment.com>> wrote:

Second, just to make things clear, the word "migration" has two meanings. The 
original meaning of migration is to switch to another software system (e.g. 
migrate from MySQL to PostgreSQL, or migrate a repository from subversion to 
git). In Django, the term "migration" means something else: to update the 
database to the new schema. In my opinion this terminology is wrong and 
confusing (apparently it comes from Ruby on Rails, but I'm not certain), and a 
better one would have been "dbupdate" or something, but since it's migration 
we'll keep it and you'll have to understand which meaning is meant in each case.

An important thing worth knowing is that Django's migration framework does 
*not* only track the database schema. It also tracks the state of the Python 
classes which define the models, including options which do not affect the 
underlying DB schema, and making such changes to a model will create the need 
for a migration.

This is absolutely necessary, though, because the migration framework generates 
a frozen snapshot of the state at each migration, so that you can access the 
ORM to do things like data updates via the RunPython migration operator. If you 
were to change, say, the default ordering of a model without also generating a 
migration to record that change (even though it has no effect on the database 
schema), you could run into trouble if you later removed a field referenced by 
the old ordering, since one of the intermediate ORM snapshots would attempt to 
order queries by a now-nonexistent column.

--
You received this message because you are subscribed to the Google 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/CAL13Cg_0p1pMtMR2y2eGry1UhQaSRpswntcnMWtHNdPgV1Ph9w%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CAL13Cg_0p1pMtMR2y2eGry1UhQaSRpswntcnMWtHNdPgV1Ph9w%40mail.gmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/A0879DE1-7EED-434F-8D71-3FFE1FB2755D%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django form needs pagination and saved data - how????

2017-07-31 Thread Jim Illback
Super advice - thanks very much, James! Appreciate your help.

Jim

On Jul 30, 2017, at 5:55 PM, James Schneider 
<jrschneide...@gmail.com<mailto:jrschneide...@gmail.com>> wrote:



On Jul 30, 2017 4:50 PM, "Jim Illback" 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:
Thanks for your reply, James. Appreciate it. BTW, if you check my template, the 
button is within the form tags, but you probably are right on the JS - I don’t 
know JS much at all so just copied other people’s code.

I thought that's how you're supposed to program in JS? Been doing it that way 
for years. ;-)


I may be mistaken, but I think the wizard link below requires a “static” or 
semi-static forms flow path (form1, form2, …, formlast). Generally, when you do 
pagination, there is no preset number of pages - it depends upon the data being 
requested or available. So, I think that option would not work. But, if I’m 
wrong, I’d love to know. Thanks.

By default, yes, it is expecting a known number of steps for more simple 
processes. However, it has all of the hooks necessary to create a fully dynamic 
flow. I did a dynamic flow back when this package was still in Django core, but 
I doubt the process has changed much.


And, as for using Java just so you can use Django, doesn’t that raise the 
obvious question - so why use Django?

I'm not sure what you're referring to here. I don't think that I mentioned Java 
specifically, nor would I have reason to.

Perhaps a mistaken interpretation of my reference to an SPA? This is what I 
meant:

https://en.m.wikipedia.org/wiki/Single-page_application


To try to illustrate that my issue is a common business issue, here’s a 
scenario that is exactly the same situation and one used by almost everyone:

A new car purchase site needs the user to pick the car and model. Then, that 
data stays static throughout the transaction. However, the user might want 
different options (tires, engines, transmission types, etc.). And, those 
options are always too many for one page, so they must be done using 
pagination. When all the options are reviewed - or maybe just one page of 
options or two or… - then the final idea is to show the user the car’s price, 
have all the selections chosen listed out for the user to review, and ask for 
further actions like "do you want to purchase this car?”.

Are these types of business scenarios just not in Django’s wheelhouse?


The level of dynamic content generation required for all of those steps will 
likely be complex, possibly even complicated, for any generic framework to 
handle. The Django formtools can handle the scenario you've listed, but your 
code organization and naming standard will need to be strongly enforced to keep 
the various steps separate.

The workflow you've mentioned isn't necessarily complicated at a high level, 
the step decisions are rather binary. Either a person wants to select different 
tires, or doesn't and accepts the default selection. The code in formtools for 
step selection is usually that simple "if they wanted different tires in a 
previous step, now show them this form for tires", almost a one-liner (for each 
step).

Honestly, the biggest issue will be displaying the multiple pages of options, 
which is somewhat a separate issue.

There are several strategies. You can display multiple form pages across 
multiple requests, keeping the results of each along the way, which complicates 
your back end code. Before the influx of JS and HTML5, this was rather common.

The newer approach is to use JS to pull all of the possible options, and handle 
the UI and pagination within JS, perhaps in a pop up modal window. The data is 
retrieved via an API call, and once a selection is made by the user, either a 
form is executed containing all of the possible options that the user selected.

Datatables.js might be a good option for this, as it can also handle the 
dynamic pagination of options surprisingly well, and plays excellent with 
Bootstrap. Heck, you can probably use DT with either strategy. It would 
definitely ease the logic for the server based form wizard, and likely save you 
a ton of JS scripting for an SPA-like display.

If it were me, I'd investigate Datatables.js with the Bootstrap integration and 
pagination. It's relatively easy to implement (I, like yourself, am averse to 
JS), and provides killer functionality with minimal custom JS (mostly single 
minimal function calls to control ordering of table columns). Once you have 
that working, try integrating the table with a form combined with pagination, I 
think that will be the silver bullet you're looking for.

https://datatables.net<https://datatables.net/>

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

Re: Django form needs pagination and saved data - how????

2017-07-30 Thread Jim Illback
Thanks for your reply, James. Appreciate it. BTW, if you check my template, the 
button is within the form tags, but you probably are right on the JS - I don’t 
know JS much at all so just copied other people’s code.

I may be mistaken, but I think the wizard link below requires a “static” or 
semi-static forms flow path (form1, form2, …, formlast). Generally, when you do 
pagination, there is no preset number of pages - it depends upon the data being 
requested or available. So, I think that option would not work. But, if I’m 
wrong, I’d love to know. Thanks.

And, as for using Java just so you can use Django, doesn’t that raise the 
obvious question - so why use Django?

To try to illustrate that my issue is a common business issue, here’s a 
scenario that is exactly the same situation and one used by almost everyone:

A new car purchase site needs the user to pick the car and model. Then, that 
data stays static throughout the transaction. However, the user might want 
different options (tires, engines, transmission types, etc.). And, those 
options are always too many for one page, so they must be done using 
pagination. When all the options are reviewed - or maybe just one page of 
options or two or… - then the final idea is to show the user the car’s price, 
have all the selections chosen listed out for the user to review, and ask for 
further actions like "do you want to purchase this car?”.

Are these types of business scenarios just not in Django’s wheelhouse?


On Jul 30, 2017, at 4:51 AM, James Schneider 
<jrschneide...@gmail.com<mailto:jrschneide...@gmail.com>> wrote:



On Jul 28, 2017 5:56 PM, "Jim Illback" 
<subaru...@hotmail.com<mailto:subaru...@hotmail.com>> wrote:
I use the latest versions of Django, python, bootstrap3, and crispy forms for 
this project.

I am trying to present a list of flashcards to a user, sorted by category 
(e.g., Math, Vocabulary, etc.). Then, I want the user to check either the full 
category or individual flashcards to be added to their practice account.

To maintain user inputted checkboxes on multiple pages, I must use POST. But, 
pagination only uses GET. So, a hack on pagination is to wrap the Next/Previous 
buttons in a sub-form and POST using the buttons. This works for pagination, 
but then my normal “I’m done, submit this session and process the updates” 
button - my submit button - does nothing: no GET, no POST, nothing.

How can I enable pagination, multiple screen data accumulation across pages, 
and final submission of the session when complete?

I can't speak to your submit button issue, other than either a piece of 
JavaScript is getting in the way, or the button is located outside of a  
tag.

As for the rest of your troubles, it really sounds like you need a form wizard 
framework, which is what I think you mean by "pagination". Django used to ship 
one as part of the contrib package, but has since moved it out to it's own 
separately maintained app.

https://django-formtools.readthedocs.io/en/latest/wizard.html

It handles keeping data state across multiple form submissions, along with 
dynamic form additions/omissions based on previous steps.

Another option you may consider is developing this process like a 
single-page-application, where all of the data and forms are managed via JS, 
and the final collection of data is submitted as a single blob to the server 
for permanent storage. That's obviously over simplified, but I hope you catch 
my meaning.

-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<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/CA%2Be%2BciVCh5oEr3rHLEUB4L%3Dpus_bL8H%2BxpmCev5syjes_XOBDg%40mail.gmail.com<https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVCh5oEr3rHLEUB4L%3Dpus_bL8H%2BxpmCev5syjes_XOBDg%40mail.gmail.com?utm_medium=email_source=footer>.
For more options, visit https://groups.google.com/d/optout.

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


Django form needs pagination and saved data - how????

2017-07-28 Thread Jim Illback
ay);
  }
  document.getElementById("crd").value = array;
  }

function valueRemove(obj, array) {
var hold = [];
var objLoc = array.indexOf(obj);
if (objLoc == -1) {
return array;
}
else {
  for (var i=(array.length-1); i >= 0; i--) {
if (i == a) {
array.pop();
}
else {
hold.push(array.pop());
}
}
return hold;
}
}

function strToArray(txt) {
var array = [];
var i = 0;
var j = 0;
var len = txt.length;
for (i=0; i < len; i++) {
if (txt[i] == ",") {
array.push(txt.substring(j, i));
j = i+1;
}
}
return array;
}


{% endblock content %}



Thanks for any help with this issue. Is there a much better approach using 
Django?

Jim Illback

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/19B75222-3C56-4886-9A92-386868495BC5%40hotmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: saving data from both a model and a derived model

2017-05-24 Thread Jim Anderson
Hi James,

I'm attaching the stacktrace as you requested.

The call to rs_template.save() is made from a django view.  rs_template is
an instance of a class RSTemplate which is derived from STemplate.
STemplate is derived from PriorityItemType. PriorityItemType is derived
from ItemType. ItemType is derived from models.Model. PriorityItemType and
ItemType are classes that are part of a library and which I have minimal
control over, so figure them as constants that cannot be changed.

Jim


The relevant code is as follows:

>From ItemType.py

[code]
class ItemType(models.Model):
...
name = models.CharField('Name', max_length=100, unique=True,
db_index=True)
[/code]

>From PriorityItemType.py

[code]
class PriorityItemType(ItemType):
   ...
   priority = models.IntegerField('Priority', default=1)
[/code]

>From STemplate.py

[code]
class STemplate(PriorityItemType):
...
backend = models.ForeignKey('siggy.SBackend', null=True, blank=True)
[/code]

>From RSTemplate.py

[code]
class RSTemplate(STemplate):
   ...
   role = models.CharField(max_length=50)
[code]

>From RSPrepView.py

[code]
class RSPrewView(View):
   ...

   for t in templates.templates:
try:
rs_template = RSTemplate.objects.get(name=t.filename)
except RSTemplate.DoesNotExist:
rs_template = RSTemplate()
rs_template.name = t.filename
rs_template.role = "RS Template"
rs_template.save()
[/code]



On Wed, May 24, 2017 at 3:36 AM, James Schneider <jrschneide...@gmail.com>
wrote:

>
>
> On Tue, May 23, 2017 at 3:44 PM, <jjanderson52...@gmail.com> wrote:
>
>> I have a model class, 'A_base', and a 2nd model class, 'A_derived'. When
>> I save an object of A_derived, I want the data from both my base and
>> derived class to be saved.
>>
>> Example code looks like this:
>>
>> class A_base(models.model):
>> name = models.CharField(max_length=50)
>>
>> class A_derived(A_base):
>> role = models.CharField(max_length=50)
>>
>>
>> So when I call save(), I want to save an instance of the derived object,
>> including the data in the base class into my sqlite3 database. I would like
>> my code to look like this:
>>
>> ...
>> derived_obj = A_derived.objects.get(name="john")
>> derived_obj.role = "parent"
>> derived_obj.save()
>> ...
>>
>> My question is whether the save method will save 'role' to the A_derived
>> table and save 'name' to the A_base table? Or do I have to override the
>> save method so that it saves 'role' and then calls the base class save
>> method to save 'name'?
>>
>>
> No, you have created two separate (but related) models. A_base has a model
> field of 'name', and A_derived has model fields 'name' and 'role'. Since
> you are inheriting from a non-abstract parent model, there is an implied
> OneToOne relationship between the two models, see the following:
> https://docs.djangoproject.com/en/1.11/topics/db/models/#multi-table-
> inheritance
>
> I'm not a big fan of this implied behavior, but it hasn't been problematic
> for me because I make heavy use of abstract model classes.
>
> If you do not want the implied relationship between the two models, create
> an abstract base class matching A_base and have both of your models inherit
> from it (A_base would be an empty model in this case, most likely).
>
> From a Django perspective, these two are completely independent
> models/entities (aside from the OneToOne relationship). A_derivied will
> have its own name and role. A_base also has it's own name, but will not be
> able to contain a role.
>
> To achieve the behavior you want, when A_derived is saved, you'll need to
> either create a new A_base object and set the 'name' field to the same
> value, or query for an existing A_base object and change/save the 'name'
> field. Keep in mind that the two values are not connected to each other.
> Changing the 'name' field on the same A_derived class later will NOT change
> the 'name' field on an A_base object automatically, you would need to
> provide such logic on one or both models, depending on the direction of the
> dependency you wish to create.
>
>
>> I tried doing this using the default save method and it created a stack
>> trace, so I'm guessing that I am expecting too much from the default save
>> method.
>>
>>
> Post the entire stack trace and we may be able to better illuminate the
> issue.
>
> -James
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit

Re: tutorial on using dbshell?

2017-05-23 Thread Jim Anderson
James,

Thank you, again.

I have install the sqlite command line package and all is working for me.

Jim A.

On Mon, May 22, 2017 at 6:35 PM, James Schneider <jrschneide...@gmail.com>
wrote:

>
>
> On May 22, 2017 3:07 PM, "Jim Anderson" <jjanderson52...@gmail.com> wrote:
>
> Hi James,
>
> I'm looking at the sqlite3 documentation now, but I'm still not quite sure
> how to run the dbshell. Once I am in the shell, I assume that I can run
> sqlite3 commands as needed. But when I enter:
>
> *% python manage.py dbshell*
>
> I get the following error messages:
>
>
>
> *setting.py: BASE_DIR =  /home/jja/...FINISHED settings.pyCommandError:
> You appear not to have the 'sqlite3' program installed or on your path.*
>
> Am I invoking it properly? Do I have to change my configuration?
>
>
> From a Django perspective, it looks correct. You'll need to install the
> sqlite3 management package do that Django has access to it. In most cases,
> if you are able to run the sqlite3 command by itself, Django should be able
> to find it. How you install it is going to be dependent on your OS. Linux
> distributions should have it really available in their package
> repositories, and the necessary package for Windows should be available on
> it's project page.
>
> -James
>
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/YYgAsqFhT8w/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/CA%2Be%2BciXENhSCg6w4YRfC6xpc5mg7BQmR
> k22ODqu%2BSCw%3DxEjLBQ%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CA%2Be%2BciXENhSCg6w4YRfC6xpc5mg7BQmRk22ODqu%2BSCw%3DxEjLBQ%40mail.gmail.com?utm_medium=email_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: tutorial on using dbshell?

2017-05-22 Thread Jim Anderson
Hi James,

I'm looking at the sqlite3 documentation now, but I'm still not quite sure
how to run the dbshell. Once I am in the shell, I assume that I can run
sqlite3 commands as needed. But when I enter:

*% python manage.py dbshell*

I get the following error messages:



*setting.py: BASE_DIR =  /home/jja/...FINISHED settings.pyCommandError: You
appear not to have the 'sqlite3' program installed or on your path.*

Am I invoking it properly? Do I have to change my configuration?

Jim A.


On Mon, May 22, 2017 at 5:28 PM, James Schneider <jrschneide...@gmail.com>
wrote:

>
>
> On May 22, 2017 2:20 PM, <jjanderson52...@gmail.com> wrote:
>
>
> I'm working with Django 1.10.3 and I'm trying to look at the database
> tables generated by Django using makemigrations and migrate. I was looking
> to use 'python manage.py sql', but it looks like that is no longer
> available. In a recent question to Django users, I was advised to use
> dbshell which I am planning to do, but thus fair I have not found and
> instructions or a tutorial on how to use deshell. Can someone point me to
> instructions?
>
>
> The dbshell command is simply a convenience command for opening the
> standard management console for your specific database. That interface will
> be different depending on the type of database you are using (MySQL,
> Postgres, or SQLite). You can find the commands for each database
> management tool by searching for " commands tutorial", as an
> example.
>
> -James
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/django-users/YYgAsqFhT8w/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/CA%2Be%2BciWZyW7Q_xzDYrEBFzAHSjDD_
> XBBD%2Bh2XGbOCoePcFLueA%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWZyW7Q_xzDYrEBFzAHSjDD_XBBD%2Bh2XGbOCoePcFLueA%40mail.gmail.com?utm_medium=email_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

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


Django Permissions

2017-03-06 Thread Jim Lamb
I am trying to give add to the django permissions  when you add a Type to a 
Source with the following models.py  I would like it to be 

from __future__ import unicode_literals

from django.db import models

"""Class for Data Sources"""
class Source(models.Model):
display_name = models.CharField(max_length=20)
code_name = models.CharField(max_length=20)

def __unicode__(self):
return self.display_name

list_display = ['display_name', 'code_name', ]
search_fields = ['display_name', 'code_name', ]

""" Class for Data Types"""
class Type(models.Model):
display_name = models.CharField(max_length=20)
code_name = models.CharField(max_length=20)
data_sources = models.ManyToManyField(DataSource)

for data_source in data_sources:

def __unicode__(self):
return self.display_name

list_display = ['display_name', 'code_name', ]
search_fields = ['display_name', 'code_name', ]


Do I need to have a views.py?  I would like it to be

auth|permsission|type


Thanks in advance

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


Django Permissions

2017-03-06 Thread Jim Lamb
I am trying to add django permissions when a type add a source iusing the 
following model

from __future__ import unicode_literals

from django.db import models

"""Class for Data Sources"""
class DataSource(models.Model):
display_name = models.CharField(max_length=20)
code_name = models.CharField(max_length=20)

def __unicode__(self):
return self.display_name

list_display = ['display_name', 'code_name', ]
search_fields = ['display_name', 'code_name', ]

""" Class for Data Types"""
class DataType(models.Model):
display_name = models.CharField(max_length=20)
code_name = models.CharField(max_length=20)
data_sources = models.ManyToManyField(DataSource)

for data_source in data_sources:

def __unicode__(self):
return self.display_name

list_display = ['display_name', 'code_name', ]
search_fields = ['display_name', 'code_name', ]


I want it to add auth|permission|type  Type equals what ever the type 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/18a9c567-0a76-4068-a787-c7553eac8fd0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


DateTimeField, auto_now_add, and makemigrations

2016-10-19 Thread Jim
Hello,

Having trouble with something on which the documentation seems clear to 
me.  I'd greatly appreciate any help.  

I wanted to add a field to a model showing when a user signed on.  I 
thought this is right.

  signup_datetime = models.DateTimeField(auto_now_add=True)  



But python3 ./manage.py makemigrations objected:
 

*You are trying to add the field 'signup_datetime' with 'auto_now_add=True' 
to tootuser without a default; the database needs something to populate 
existing rows*
Any suggestions?

(When I tried

signup_datetime = models.DateTimeField(default=datetime.datetime.now, blank=
True) 

it said this:



*/usr/local/lib/python3.4/dist-packages/django/db/models/fields/__init__.py:1430:
 
RuntimeWarning: DateTimeField TootUser.signup_datetime received a naive 
datetime (2016-10-19 13:48:14.145943) while time zone support is active.  
RuntimeWarning)*
but honestly, I can't figure out what is wrong with the first try.)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/e1764cbd-a492-4332-902f-aeb6d061a631%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: "Error creating new content types" with multiple DB router

2016-04-12 Thread Jim T
Carlton, we have the exact same issue you described.  It took a lot of 
searching to even find someone who has the same problem which led us to the 
conclusion that we just didn't understand how to perform migrations with DB 
Routers in play.  As you described, we have:

Database A - contains the schema for auth, sessions, content-type, models 
for app A
Database B - contains the models for app B

Migrations for app A function correctly.
Migrations for app B do not function correctly.

Our goal is the same as yours - to have models for app B (in Database B) 
store it's content-type in Database A, which is actually the point of 
having an "app" label in the content types table.  We follow the same 
suggestions and examples and yield the same error messages.

We are convinced the solution is some subtlety in the DB Router code that 
we missed and continue to investigate.  Did you ever find the solution to 
this?

Thanks
-Jim


On Tuesday, December 15, 2015 at 4:30:25 PM UTC-5, Carlton Gibson wrote:
>
> Hi, 
>
> Using multiple DBs, with most models in the "default" db but models for a 
> single app being stored in a second DB, I've more or less copied the example 
> from the docs 
> <https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#an-example> for 
> a custom database router. (My example is essentially identical to the 
> `AuthRouter` class given.)
>
> This works perfectly *except* when I run the migration on the second DB. 
>
> The app relations are all created but I then get an error creating the 
> ContentType...
>
> > RuntimeError: Error creating new content types. Please make sure 
> contenttypes is migrated before trying to migrate apps individually.
>
> This occurs because the relation "django_content_type" does not exist in 
> the second database — that's correct: I'm expecting content types to be 
> written only to the "default" db. 
>
> My question is why is this error occurring? 
>
> 1. As per the docs, in my router, I am returning "None if there is no 
> suggestion" for all the router methods — particularly `db_for_write`, which 
> seems relevant here. 
> 2. Looking at the source, the default router returns `DEFAULT_DB_ALIAS` if 
> all the custom routers return None. 
>
> So 3. I can't see the error. :-) — I'm expecting the content type to be 
> written to the default db. 
>
> I can work around the issue here — but I'd like to understand it. Can 
> anyone with experience of this explain what I've done wrong?
>
> Kind Regards,
>
> Carlton 
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/2b461815-8b7a-4507-b7a9-07e54bf6c497%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


sqlite3 “OperationalError: no such table” on threaded operation

2016-01-08 Thread Jim Bell


By everything I read in the docs, both Django and py-sqlite3 should be fine 
with threaded access. (Right?) But the attached code snippet fails for me. 
The operations in the main thread work, but not in the thread(s) I create. 
There I get:

File 
"C:\Python27\lib\site-packages\django-1.9-py2.7.egg\django\db\backends\sq 
lite3\base.py", line 323, in execute return Database.Cursor.execute(self, 
query, params)

*OperationalError: no such table*: thrtest_mymodel

What's the problem?


How do I go about tracking down exactly what's happening? The point of 
failure in Django is pretty indimidating. I can't tell how to see what 
tables it DOES see, or what differences to look for between main and other 
threads.


Here is DATABASES from settings.py:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:', # os.path.join(BASE_DIR, 'db.sqlite3'),
'TEST_NAME' : ':memory:',
},}


With respect to Django's ticket #12118, I get the same symptoms using 
':memory:' or a disk file (for TEST_NAME).


Django 1.9, Python 2.7.11.


Posted yesterday on stackoverflow 

.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 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/9409d2f4-5530-4261-b501-c6833f39c735%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
from django.db import models

# Super-simple model
class MyModel(models.Model):
   message   = models.CharField('Message', max_length=200, blank=True)

#Test
from django.test import TestCase

import time
import threading
import random


done = threading.Event()
nThreads = 1


def InsertRec(msg):
   rec = MyModel.objects.create(message=msg)
   rec.save()


def InsertThread():
   try:
  msgNum = 1
  thrName = threading.currentThread().name
  print 'Starting %s' % thrName
  while not done.wait(random.random() * 0.1):
 msgNum += 1
 msg = '%s: %d' % (thrName, msgNum)
 print msg
 InsertRec(msg)
   finally:
  done.set()
   pass


class ThreadTestRun(TestCase):

   def testRunIt(self):
  nThisThread = 10
  msgSet = set()
  for x in xrange(nThisThread):
 msg = 'Some message %d' % x
 InsertRec(msg) # From main thread: works!
 msgSet.add(msg)
  self.assertEqual(MyModel.objects.count(), nThisThread)
  # We use sets because .all() doesn't preserve the original order.
  self.assertEqual(msgSet, set([r.message for r in MyModel.objects.all()]))
  thrSet = set()
  for thrNum in xrange(nThreads):
 t = threading.Thread(name='Thread %d' % thrNum, target=InsertThread)
 t.start()
 thrSet.add(t)
  
  done.wait(10.)
  done.set()
  for t in thrSet:
 t.join()




Class Based Views tutorials

2015-01-06 Thread Jim Wombles
Two Scoops of Django is definitely the book you are looking for. I don't know 
if it's out for 1.7 yet, but I purchased the book for Django 1.6 and it covers 
l of the best practices that you won't read about just from the Django docs. 

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


Re: Access Model data from a ModelFormset form

2013-03-12 Thread Jim Kalafut
Thanks Tom & C. Kirby for the suggestions.  Pulling data off of .instance 
seems to work fine and is exactly what I'm looking for.

Regards,
Jim



On Tuesday, March 12, 2013 9:28:23 AM UTC-7, Tom Evans wrote:
>
> On Tue, Mar 12, 2013 at 2:24 PM, Jim Kalafut <kal...@gmail.com> 
> wrote: 
> > Hi, 
> > 
> > I often want to use a ModelFormset by showing some editable fields, and 
> then 
> > showing some static data that is from the related model instance. For 
> > example, I want to bulk edit a group of Person object phone numbers and 
> > email address, but I'd also like to show (not edit) the person's name by 
> > each form.  Is there a straightforward way to get at that data, or 
> configure 
> > the ModelFormset in a way that I can accomplish this?  My hack 
> approaches so 
> > far are ugly to the point that it is cleaner to just create a set of 
> > form/model pairs myself and send them to the template. 
> > 
> > Thanks, 
> > Jim 
> > 
>
> Hi Jim 
>
> In a ModelForm (also applies to the individual forms in a 
> ModelFormSet), the instance that the form corresponds to will be 
> aailable in the attribute 'instance'. Eg, in your template, you can do 
> something like this: 
>
> {% for form in formset %} 
>   {{ form.title }} 
>   {{ form.name }} 
>
>   {{ form.instance.name }} 
> {% endfor %} 
>
> The docs only say that forms bound to a particular instance will have 
> the attribute: 
>
>
> https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#overriding-the-clean-method
>  
>
> But from code inspection it seems that an empty instance would be 
> created for any non bound model form - its the first thing 
> BaseModelForm does when instantiated without a supplied instance. 
>
> Cheers 
>
> Tom 
>

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




Access Model data from a ModelFormset form

2013-03-12 Thread Jim Kalafut
Hi,

I often want to use a ModelFormset by showing some editable fields, and 
then showing some static data that is from the related model instance. For 
example, I want to bulk edit a group of Person object phone numbers and 
email address, but I'd also like to show (not edit) the person's name by 
each form.  Is there a straightforward way to get at that data, or 
configure the ModelFormset in a way that I can accomplish this?  My hack 
approaches so far are ugly to the point that it is cleaner to just create a 
set of form/model pairs myself and send them to the template.

Thanks,
Jim

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

2013-01-11 Thread Jim Thaxton
I'm not sure about your original problem but prefixing it with django will 
make use of Django's jquery namespace:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions

Django admin Javascript makes use of the jQuery  library. 
> To avoid conflicts with user-supplied scripts or libraries, Django's jQuery 
> is namespaced as django.jQuery. If you want to use jQuery in your own 
> admin JavaScript without including a second copy, you can use the 
> django.jQuery object on changelist and add/edit views.
> If you require the jQuery library to be in the global namespace, for 
> example when using third-party jQuery plugins, or need a newer version of 
> jQuery, you will have to include your own copy of jQuery.


On Friday, January 11, 2013 4:26:19 AM UTC-6, Daniele Procida wrote:
>
> I had a custom widget, which broke after some other things were updated. 
>
> It was saying: 
>
> TypeError: 'undefined' is not a function (evaluating '$('#id_conta 
> cts_and_people-phonecontact-content_type-object_id-0-label').combo 
> box()') 
>
> Last night, I finally managed to fix it, after noticing that this script 
> (which is injected into the HTML body as many times as required for each 
> widget) began: 
>
> $(document).ready(function(){ 
>
> while others I had seen began: 
>
> jQuery(document).ready(function($){ 
>
> Changing it to the latter form made it work. 
>
> The only thing is, I don't really understand what was wrong, or how doing 
> that fixed it. 
>
> I understand that a jQuery conflict of some kind meant that jQuery was 
> unable to find the function "combobox()" and that probably this was because 
> of the way the admin template was loading JavaScript files. 
>
> But I don't understand what the changes actually mean, or what they do. 
>
> I also found that: 
>
> django.jQuery(document).ready(function($){ 
>
> worked. Again, I don't know what that is doing. 
>
> If someone can explain what is going on in this example, that would be 
> really helpful. 
>
> More generally, this sort of thing (jQuery conflicts) seems to be an 
> almost constant issue for Django developers who create custom widgets. Is 
> there a more general strategy for dealing with it? 
>
> Thanks, 
>
> Daniele 
>
>

-- 
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/-/dd7dlwe4ZJcJ.
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: CSS not rendering on local server development

2012-10-02 Thread Jim Wombles
Well, your suggestion actually caused an error that helped me debug what 
was going on.  Silly mistake of forgetting the comma at the end of the 
tuple in staticfiles_dirs.  Cheers to you.

On Wednesday, October 3, 2012 12:07:33 AM UTC-4, JJ Zolper wrote:
>
> Off the top of my head I forget what kinks I ran into when trying to get 
> CSS to load on my development server. I'll try and come up with things I 
> remembered and let you know if I do.
>
> One thing in Chrome that I tend to have to do (probably why firefox is 
> better in this case) is I have to clear my browsing data. That way the 
> files propagate through to my browser. Here's how to do that:
>
> http://www.wikihow.com/Clear-Your-Browser's-Cache#Chrome_v10_.2B
>
> Did you run python manage.py collectstatic? and restart your local 
> development server with python manage.py runserver?
>
> Cheers,
>
> JJ
>
> On Tuesday, October 2, 2012 11:23:11 PM UTC-4, Jim Wombles wrote:
>>
>> Greetings,
>>
>> I am at a loss as to why local server is unable to render the css and js 
>> files.  I have the static_dirs setting correct and the href link to the 
>> files is correct, and the html file is rendering yet when I track what is 
>> going on with Chrome Dev Tools it is unable to find the CSS and JS files 
>> returning an Internal Server Error 500
>>
>> Any idea what may be going on ?
>>
>> Thanks for any advice.
>>
>> Jim
>> Fanbouts.com
>>  
>

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



CSS not rendering on local server development

2012-10-02 Thread Jim Wombles
Greetings,

I am at a loss as to why local server is unable to render the css and js
files.  I have the static_dirs setting correct and the href link to the
files is correct, and the html file is rendering yet when I track what is
going on with Chrome Dev Tools it is unable to find the CSS and JS files
returning an Internal Server Error 500

Any idea what may be going on ?

Thanks for any advice.

Jim
Fanbouts.com

-- 
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: convert str to datetime

2012-06-25 Thread Jim Thaxton
The parseutil module is very handy when converting a formatted string into 
a datetime object.

Here's the module:
http://labix.org/python-dateutil

And here is a stackoverflow post with a number of examples:
http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python

On Monday, June 25, 2012 3:42:27 AM UTC-5, armagan wrote:
>
> Hi,
>
> I'm trying to convert to str to datetime. "date object" must be datetime 
> object. Can you help me?
>
>  def item_pubdate(self, item): # Yayinlanma Tarihi
>
> if item.delivery_date:
>
> date = item.delivery_date
>
> dt = datetime.combine(date, time())
>
> return dt
>
> else:
>
> return ' '
>

-- 
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/-/TwagqVTzU-0J.
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: Admin user privilege elevation (how to prevent it)

2012-05-12 Thread jim
On Fri, May 11, 2012 at 10:11 PM, Josh Cartmell wrote:

> I work a lot with Mezzanine which is a CMS that uses Django.  A
> security issue was recently revealed where an admin user, lets call
> him A, (they can post rich content) could put a cleverly constructed
> javascript on a page such that if a superuser, let's call her B, then
> visited the page it would elevate A to superuser status (a more
> thorough explanation is here:
>
> http://groups.google.com/group/mezzanine-users/browse_thread/thread/14fde9d8bc71555b/8208a128dbe314e8?lnk=gst=security
> ).
> Apparently any django app which allowed admin users to post arbitrary
> html would be vulnerable.
>
> My first thought was that csrf protection should prevent this but alas
> that is not the case.  The only real solution found is to restrict
> admin users from posting any javascript in their content, unless you
> completely trust the admin users.
>
> My question is are there any other solutions to these sorts of
> problems?  It seems like allowing an admin user to post javascript is
> reasonable, what is unreasonable is for that javascript to be able to
> elevate a user's privilege.  Could improvements be made to the csrf
> mechanism to prevent this sort of user privilege elevation?
>
>
One way to do this would be to have the admin interface on a different
subdomain to any user-generated content. Then JS in user-generated content
that tries to access the admin interface will be foiled by the same-origin
policy.



> --
> 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: Sending data to the server

2012-03-26 Thread jim
Do you have CSRF protection enabled?

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

It will 403 POST requests unless they have the right token.

Jim

On Sun, Mar 25, 2012 at 11:24 PM, drk <darkiii...@gmail.com> wrote:
> Hi, so I have a application that works offline (with localStorage),
> and now I'm trying to get it to work in a server.
>
> I'm having a problem sending the data to server, I'm using jquery:
>
> $.ajax({
>
>    type: 'POST',
>    url: 'http://mysite.aa/logout/',
>    data: JSON.stringify( stuff ),
>    contentType: 'text/plain; charset=utf-8',
>    complete: function() { console.log('complete'); }
> });
>
> and I get a 403 error.
>
> In chrome's console:
>
> POST http://mysite.aa/logout/ 403 (FORBIDDEN)
> XHR finished loading: "http://myserver.aa/logout/;
>
> In server:
> [25/Mar/2012 17:20:43] "POST /logout/ HTTP/1.1" 403 2282
>
>
> Any ideas?
>
> --
> 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.



preventing data from getting saved to the backend database?

2011-12-27 Thread Jim
I'm a newbie reading documentation, and this question may well be
answered by something I havent read yet, but anyway...

My understanding so far is that django incorporates a back-end
database (in my case built in sql3 on windows) to which all model
related data from forms gets posted.

I'm trying to write an app whereby the user can upload 2 sets of alarm
files: a before and an after view, and then be able to filter and zoom
in detail appropriately. However, each alarm file upload might
comprise several hundred alarms.
I'm only really interested in comparing these 2 sets of alarms, but it
seems to me that by using django (and an alarm Class etc), that all
these alarms will be pasted into the database every time a report is
requested. That's not what I want, and at 2 x 200+ alarms per request,
I can imagine me clogging up my alarms database at some point (but
more importantly bloating with data I don't want to keep...).

I'm sure there is a solution, could someone please tell me their
thoughts? - what do I do with lots of data that I don't want to keep
after a specific session is finished?

-- 
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: Trying to create django app to view alarms

2011-12-27 Thread Jim


On Dec 23, 2:29 pm, Python_Junkie 
wrote:
> I think that building the python code that performs your logic is a
> great way to start, and not getting bogged down with django is a great
> way to get started.
>
> There are several (relatively straight forward) pieces of django that
> you will need to tie together.
>
> I will simply disucss the view.py components and the html template.
>
> Establish your python code as a module.
> Import the module in the view and use it in the view.py.
>
> def function_called_for_log_display(request):
>             ..call your python module
>             ...create a python dictionary with the information
> that is pulled back by your python module
>
>           .render the html template and pass the
> dictionary values to the template
>
>                  return render_to_response('polls/index.html',
> {'latest_poll_list': latest_poll_list})  #I took this from the django
> project tutorial
>
>  ...use the appropriate template tags/logic to display the
> results of the dictionary
>

Thanks Python-Junkie-

I've got a prototype working but it's really clunky and currently
involves a server submit whenever I want to filter or my alarm view.
I'm thinking about what to do and am sure will post another question
soon! :)

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



Trying to create django app to view alarms

2011-12-23 Thread Jim
Hi-

I'm new to Django and pretty basic with Python to be honest, but am
trying to write a web tool that will let me upload  'before' and
'after' files of alarm logs and analyse the differences as follows:

  * alarms cleared during the period (in before, but not after)
  * alarms raised during the period (in after, but not before)
  * historic alarms (exist with same timestamp in both before and
after lists)
  * existing alarms with activity (exist in before and after lists but
with differing timestamps)

Ball-park figure for the size of these alarm logs is about 200 KB (=
about 40 logs).

I've already written a standalone .py script that, takes as inputs the
filenames of the before and after alarm log files and from this
creates 6 lists of alarm objects: (before alarms, after alarms, and
the 4 lists described above).

What I'd like to do is to use Django to upload the alarm data and then
be able to view the alarms by list.

As a rough and ready starting point, I've created an html form with a
couple of textareas in, and I seem to be able to paste the entire
before and alarm files in these, so I can upload the alarms data to
Django in a form.

Can anyone suggest how best to implement my existing python code in
the .py file to create a Django solution?

Thanks for any advice.

Jim

-- 
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: urls.py?

2011-12-09 Thread Jim Byrnes

On 12/09/2011 03:06 AM, Reinout van Rees wrote:

On 09-12-11 01:28, Jim Byrnes wrote:

from django.conf.urls.defaults import *
from mysite import views
from mysite.views import hello, current_datetime, hours_ahead,
display_meta
from django.contrib import admin
from mysite.contact import views
from mysite.books import views

admin.autodiscover()

urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
(r'^admin/' , include(admin.site.urls)),
(r'^contact/$',views.contact),
(r'^search-form/$', views.search_form), #from mysite.books
(r'^search/$', views.search), # from mysite.books

)


mysite.contact.views might very well have a contact() method, but
mysite.books.views probably does not.

And you're importing 'views' a couple of times at the top. The last
"from mysite.books import views" is winning :-) You cannot have one
variable point to several things at the same time.

Best thing you can do:

import mysite.contact.views
import mysite.books.views
...
(r'^contact/$', mysite.contact.views.contact),




Reinout



That worked and your explanation gave me a better understanding of how 
the process works.



Thanks,  Jim

--
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: urls.py?

2011-12-08 Thread Jim Byrnes

On 12/08/2011 07:23 PM, Mario Gudelj wrote:

I think you have to add "from views import *" to urls.py and make sure you
have a method called contact in your view.

Cheers,


Thanks, but I added "from views import *" and there definitely is a 
method called contact in /mysite/contact and still get the error.


Regards, Jim


On 09/12/2011 12:10 PM, "Jim Byrnes"<jf_byr...@comcast.net>  wrote:


I am trying to learning django by working my way through The Definitive
Guide to django (vers 1.1). I am running django 1.1.1 on Ubuntu 10.04.

I get the following error when trying to import urls:


import urls

Traceback (most recent call last):
  File "", line 1, in
  File "/home/jfb/MyProgs/djcode/**mysite/urls.py", line 16, in
(r'^contact/$',views.contact),
AttributeError: 'module' object has no attribute 'contact'

Here is urls.py:

from django.conf.urls.defaults import *
from mysite import views
from mysite.views import hello, current_datetime, hours_ahead, display_meta
from django.contrib import admin
from mysite.contact import views
from mysite.books import views

admin.autodiscover()

urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
(r'^admin/' , include(admin.site.urls)),
(r'^contact/$',views.contact),
(r'^search-form/$', views.search_form), #from mysite.books
(r'^search/$', views.search),   # from mysite.books

)

If I comment out either the reference to importing contact and it's
pattern or books and it's pattern I get no error. Both books and contact
are directories at the same level under mysite.

Usually when I get in situations like this it is because I missed
something.  I've gone back a reviewed everything I have done and still
don't understand what is wrong.

I would appreciate any help you could give me in figuring this out.

Thanks,  Jim


--
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+unsubscribe@**
googlegroups.com<django-users%2bunsubscr...@googlegroups.com>.
For more options, visit this group at http://groups.google.com/**
group/django-users?hl=en<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.



urls.py?

2011-12-08 Thread Jim Byrnes
I am trying to learning django by working my way through The Definitive 
Guide to django (vers 1.1). I am running django 1.1.1 on Ubuntu 10.04.


I get the following error when trying to import urls:

>>> import urls
Traceback (most recent call last):
  File "", line 1, in 
  File "/home/jfb/MyProgs/djcode/mysite/urls.py", line 16, in 
(r'^contact/$',views.contact),
AttributeError: 'module' object has no attribute 'contact'

Here is urls.py:

from django.conf.urls.defaults import *
from mysite import views
from mysite.views import hello, current_datetime, hours_ahead, display_meta
from django.contrib import admin
from mysite.contact import views
from mysite.books import views

admin.autodiscover()

urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^time/$', current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
(r'^admin/' , include(admin.site.urls)),
(r'^contact/$',views.contact),
(r'^search-form/$', views.search_form), #from mysite.books
(r'^search/$', views.search),   # from mysite.books

)

If I comment out either the reference to importing contact and it's 
pattern or books and it's pattern I get no error. Both books and contact 
are directories at the same level under mysite.


Usually when I get in situations like this it is because I missed 
something.  I've gone back a reviewed everything I have done and still 
don't understand what is wrong.


I would appreciate any help you could give me in figuring this out.

Thanks,  Jim


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



Using request.POST.copy() to get hidden field in html template

2011-11-30 Thread jim
I'm trying to use request.POST.copy() to get a hidden field in an html
template.  The hidden field looks like:



I also tried:



In my view.py I have:

  postdata = request.POST.copy()
   url = str(postdata.get('url'))

The value of url is None.  Is there an additional trick to this?

Thanks
Jim

-- 
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: Detect runserver in settings.py?

2011-11-21 Thread Jim

On Nov 21, 5:29 pm, Simon Bächler <s...@feinheit.ch> wrote:
> if 'runserver' in sys.argv:

Thank you, Simon.

Jim

-- 
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: Detect runserver in settings.py?

2011-11-21 Thread Jim
> import socket
> if socket.gethostname() == '':
>      DEBUG = True
> else:
>      DEBUG = False

Thanks Mike, however I happening to be running it two different ways
on a single machine so the issue is not of determining the machine but
instead of determining on that machine the way that Django is running.

Regards,
Jim

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



An application for hierarchical tagging?

2011-10-10 Thread Jim
Is there an application that would characterize the data by hierarchy?

That is, I want a taxonomy for my data to go something like this.
  books
  books > fiction
  books > fiction > murder mysteries
and my data can be associated with one or more sub-branches of this
tree.

I'm using django-tagging but I also want the tree structure.  I looked
at django-taxonomy but the author says it is far from ready for
production and it has not been updated in some time.  I have also seen
advice to make up a tree of templates books.html, fiction.html, etc.
That solution might be OK for a size 10 tree, but I anticipate a
fairly large tree (a hundred branches, perhaps).

In the past when I needed to do this I used mptt and rolled my own.
That was a few years ago.  Googling didn't find me anything else.
Does anyone know if there of a more generic solution at this point?

Thank you,
Jim

-- 
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: spam in response to posting to this list

2011-08-29 Thread Jim Louis
Hello,

I am having the same issue with my google group. If someone who is a
manager of this group can email me. maybe we can see if the same email
address is on both our groups causing the problem.  My group is
completely different focus from This group.

j...@bestmeetings.com

Thank you,

Jim Louis, CMP
Founder/Wednesday Moderator of the Meetings Community (MeCo)


On Aug 10, 6:01 pm, Brian Bouterse <bmbou...@gmail.com> wrote:
> +1 to your suggestion of folks not overusing +1
>
> On Wed, Aug 10, 2011 at 5:51 PM, Michal Petrucha 
> <michal.petru...@ksp.sk>wrote:
>
>
>
>
>
>
>
>
>
> > On Thu, Aug 11, 2011 at 12:14:37AM +0300, Praveen Krishna R wrote:
> > > *+1
> > > *
> > > On Wed, Aug 10, 2011 at 7:32 PM, Kayode Odeyemi <drey...@gmail.com>
> > wrote:
>
> > > > I have been getting this too.
>
> > Please, people, be at least a little bit reasonable. Let's not make
> > this another completely pointless "+1, me too" thread with no
> > information at all. I bet most of the people posting to this mailing
> > list are getting that spam and it really does not help at all if we
> > all just start posting "+1" mails.
>
> > Michal
>
> --
> Brian Bouterse
> ITng Services

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



Tips for setting up multiple databases routing in Django

2011-08-24 Thread Jim
First of all, I would like to thank Reinout van Rees (
http://reinout.vanrees.org/) for his helpful suggestions. 

Suppose you have two databases, 'default' and 'test', and one app, 'books'. 
And you want to store the models in books in the database 'test'. 

According to the guide from Django 
doc, 
you may have something like this in your settings.py:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/path/to/default.sqlite',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
'test': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/path/to/test.sqlite',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}


And a routing file, say dbrouting.py, which has something like this:

class DBRouter(object):
def db_for_read(self, model, **hints):
label = model._meta.app_label
if label == 'books':
dbName = 'test' # dbName is a name in settings.DATABASES
else:
dbName = None
return dbName

def db_for_write(self, model, **hints):
label = model._meta.app_label
if label == 'books':
dbName = 'test'
else:
dbName = None
return dbName

def allow_relation(self, obj1, obj2, **hints):
label1 = obj1._meta.app_label
label2 = obj2._meta.app_label
if label1 == label2:
return True
return None

def allow_syncdb(self, db, model):
# db is a string of database name.
label = model._meta.app_label
if label == 'books':
dbName = 'test'
else:
dbName = None
if dbName == db:
return True
else:
return False


Now, here is the important stuff. If you don't have the database file 
test.sqlite yet, you must create it first before you enable the database 
routing. Use the following command to do this:

./manage.py syncdb --database=test

With this step, Django will initialize the database, including creating some 
required tables (such as django_content_type). In the routing scheme, only 
models from the app books can access the database 'test'. That means that 
even Django cannot get in the database and make the necessary setups 
including creating some necessary tables. Once you have initialized the 
database, you can enable the routing scheme.

To sum up, here are the steps I recommend if you want to create a database 
to store data from certain models.

   1. Add that new database to settings.py.
   2. Make sure that the database routing is disabled. (To disable the 
   database routing, just comment out the DATABASE_ROUTERS setting in the 
   settings.py file.)
   3. Initialize your new database as shown above.
   4. Enable database routing (by enabling the DATABASE_ROUTERS setting in 
   the settings.py file).
   5. Run ./manage.py syncdb --database= to create 
   tables for your models.
   
In the above steps, I assume you have created your models and database 
routers properly.

That's it.

BTW, I am new to Django. So, if I am missing anything above or having 
anything misleading, please do correct me. Thank you very much.
 



-- 
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/-/3CnRHQefMHAJ.
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 make an app independent on a specific site?

2011-08-23 Thread Jim
BTW, the way I posted above isn't so elegant. Is there a better way to do 
this? Any thoughts?

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



How to make an app independent on a specific site?

2011-08-23 Thread Jim
Greetings, everyone.

I am new to Django, and much of my knowledge comes from the Django book 
version 2 . In the book, a site, mysite, 
is created for demo purposes. And an app, books, is also created for demo 
purposes. In the file, mysite/books/admin.py, there is a line like this:

from mysite.books.models import Publisher, Author, Book

It seems to me that this line makes the app dependent on the name of the 
site, which is mysite. There is a possibility that an app you have developed 
for a site might turn out to have generic use. So, I think it is a good idea 
to always keep an app independent on the site as much as possible. 

Here is the question. Is it possible that to store the site name into a 
variable, such as site_name, then construct a statement like the following?

statement = 'from ' + site_name + '.books.models import Publisher' 
exec(statement) 
# I am not sure if exec is a legitimate function. Here is just an example








-- 
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/-/Jn_07ca2t6MJ.
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: Problems on using multiple databases

2011-08-23 Thread Jim
Still stuck on this problem. Can anybody help me out, please? It would be 
much appreciated.

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



Problems on using multiple databases

2011-08-22 Thread Jim
ngo/db/models/query.py",
 
line 273, in iterator
for row in compiler.results_iter():
  File 
"/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/django/db/models/sql/compiler.py",
 
line 680, in results_iter
for rows in self.execute_sql(MULTI):
  File 
"/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/django/db/models/sql/compiler.py",
 
line 735, in execute_sql
cursor.execute(sql, params)
  File 
"/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/django/db/backends/util.py",
 
line 34, in execute
return self.cursor.execute(sql, params)
  File 
"/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py",
 
line 234, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.DatabaseError: no such table: django_content_type

Any help would be appreciated. Thank you very much.

Jim

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



mod_wsgi cannot load MySQLdb

2011-08-22 Thread Jim
Hello folks,

This probably has been discussed many times, but I still can't find any 
solution yet. Basically, it turns out that python can load MySQLdb just 
fine, but Apache can't load MySQLdb from the wsgi script.

I am using python2.7 in a virtual environment created by virtualenv. Here is 
the error info extracted from the Apache error log. To make the lines 
shorter, I deleted all the time tags in the brackets.

Any ideas how to fix it?

[] mod_wsgi (pid=3136): Target WSGI script 
'/Users/jianbao/projects/tao.com/mysite/apache/django.wsgi' cannot be loaded 
as Python module.
[] mod_wsgi (pid=3136): Exception occurred processing WSGI script 
'/Users/jianbao/projects/tao.com/mysite/apache/django.wsgi'.
[] Traceback (most recent call last):
[]   File "/Users/jianbao/projects/tao.com/mysite/apache/django.wsgi", line 
56, in 
[] import MySQLdb
[]   File 
"/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/MySQLdb/__init__.py",
 
line 19, in 
[] import _mysql
[] ImportError: 
dlopen(/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/_mysql.so,
 
2): Library not loaded: libmysqlclient.18.dylib
[]   Referenced from: 
/Users/jianbao/projects/tao.com/mysite/lib/python2.7/site-packages/_mysql.so
[]   Reason: image not found

-- 
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/-/eXS-nCx7Ut4J.
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: Import problem

2011-08-21 Thread Jim
You are right, SleepyCal. I changed global to something else, and the import 
issue was solved.

-- 
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/-/ElDTlCgIITMJ.
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 create a sub-app directly

2011-08-21 Thread Jim
Thank you, folks. I am new to django. I read  a blog the other day that 
suggests put all applications under a common directory, such as apps, to 
make the site directory neat, and I think that seems a good idea. That's why 
I thought it would be wonderful if manage.py could make an app under a given 
directory, which is apps/ in my case. 

Anyway, it is always nice to hear other people's ideas. Again, thank you 
very much.

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



How to create a sub-app directly

2011-08-21 Thread Jim
Hello folks,

Here is the story. I created a site, mysite, with this command django-admin 
startproject mysite. Then, under the directory mysite/, I created an app 
named apps with this command ./manage.py startapp apps. apps is meant to 
hold all applications for mysite. Now, here comes the question: 
*How do I create a sub-app under apps with manage.py directly?*

I tried 
../manage.py startapp someapp 
under apps/, but that created the someapp under mysite/ rather than under 
apps/. 

I also tried 
./manage.py startapp apps/someapp 
and 
./manage.py startapp apps.someapp
under mysite/, but neither worked.

So, my current work-around is to create a sub-app under mysite/ first, then 
move it into apps/ manually. But that seems dumb, and I suspect there is a 
simpler way to do this. 

Thanks for reading this. Any help is certainly appreciated.

Jim

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



Import problem

2011-08-21 Thread Jim
Hello folks,

I am new to both Python and Django. And the story is a little long. So, 
please bear with me. 

Recently I created a site named djangoSite to practice the Django framework. 
The first thing I want to do is to create a SQLite database to hold global 
data of the site. As simple as it sounds, the actual process I went through 
wasn't so simple. 

First, I created an apps/ subdirectory under djangoSite/ to hold all 
potential applications I may have. Then, I created an empty file __init__.pyto 
makeapps/a package.Then, I wanted to create an app 
global to make models for holding global data. I tried the following to do 
this.
djangoSite/ >$ cd apps
apps/ >$ ../manage.py startapp global
It turns out the app global was created under djangoSite/ rather than under 
apps/. So, here is one question. *How do I create a sub-app under apps/ with 
manage.py?* Anyway, I didn't stop there. I moved the folder global/ into 
apps/. I assumed that this would make global a subapp of apps, so that 
something like this would work under manage.py shell: import apps.global. 
However, I didn't test it right after moving the folder global/, which I 
should have. Instead, I proceeded and created a model in 
apps/global/models.py named NavItem. Then, I added 'djangoSite.apps.global' 
to settings.INSTALLED_APPS.

Then, I added a SQLite3 database 'global' in settings.DATABASES, and created 
a Python file dbrouter.py under djangoSite/, in which I created a class 
DBRouter to route the databases. Accordingly, I added DATABASE_ROUTERS = 
['djangoSite.dbrouter.DBRouter'] to settings.py. Here is another question. 
When creating the class DBRouter, I basically copied the example (only the 
master class) in the Django documentation Multiple 
Databases<https://docs.djangoproject.com/en/dev/topics/db/multi-db/#topics-db-multi-db-routing>.
 
It seems to me the newly created routing class, which is DBRouter in my 
case, inherits a class named object, because of this statement: class 
DBRouter(object). However, the example in the document I mentioned earlier 
doesn't import anything at all, so the question is *where this class 
'object' come from*? 

Anyway, I kept moving. Under djangoSite/, I ran ./manage.py validate, which 
gave 0 error. Then, I ran ./manage.py syncdb. And I got a bunch of errors. I 
suspected that the database routing may not work. So, commented out the 
DATABASE_ROUTERS settings, and ran ./manage.py syncdb again. This time, it 
went through without errors. Now I am guessing that I need to import 
something to make DBRouter work. 

So I started tracking down the problem. I invoked manage.py shell, and 
wanted to create an instance of NavItem. I tried the following import 
statements, but none of these worked. All of the them get a syntax error. 
Here thery are.

>>> from apps.global.models import NavItem
  File "", line 1
from apps.global.models import NavItem
   ^
SyntaxError: invalid syntax
>>> from global.models import NavItem
  File "", line 1
from global.models import NavItem
  ^
SyntaxError: invalid syntax
>>> from djangoSite.apps.global.models import NavItem
  File "", line 1
from djangoSite.apps.global.models import NavItem
  ^
SyntaxError: invalid syntax
>>> from global.models import NavItem
  File "", line 1
from global.models import NavItem
  ^
SyntaxError: invalid syntax


Now I am running out of ideas about what went wrong. I know this is a bit 
long, so I really appreciate your help. Thank you very much.

Jim



, I also created and an subdirectory apps to hold all my django 
applications. I created an empty file __init__.py to make the folder apps a 
package. Then, I meant to create an app named global to hold global data of 
the site. 

-- 
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/-/3cTQeJLV05gJ.
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: Defining global names

2011-03-18 Thread Jim Thaxton
Can you set it in the settings.py file for your project? You can then import 
the Django settings in your views with:

from django.conf import settings

and call the variable with settings.my_var_name when needed.

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



Putting content_type on a different class for a generic relation?

2011-03-02 Thread Jim D
I've got two models. Here's what I'm trying to do:

class InterestSet(models.Model, MailChimpAPIMixin):
name = models.CharField(help_text="The interest grouping to add.
Grouping names must be unique.", max_length=128, unique=True)
content_type = models.ForeignKey(ContentType, blank=True,
null=True)

class InterestGroup(models.Model, MailChimpAPIMixin):
name = models.CharField(max_length=128, unique=True)
interest_grouping = models.ForeignKey(InterestGrouping)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object =
generic.GenericForeignKey('interest_set__content_type', 'object_id')


Basically, I want to define a content type for an Interest Set on the
"parent" model. Then, for each Interest Group, I want the object id to
always refer to the content type set on Interest Set. You can see by
the first argument to GenericForeignKey() how I wish it worked.

Alas it does not. Plan B is just to move the content_type field back
to Interest Grouping and deal (or possibly just custom code my
relationships without relying on GenericForeignKey). It's a shame
because it duplicates data unnecessarily and creates an opportunity
for a relationship to be created that violates a business rule for
this application (which is that all Interest Groups in an Interest Set
must be related to the same content type).

I'm just wondering if either a) I'm missing an obvious way to
accomplish this or b) this has come up before or been discussed
somewhere. I might explore the possibility of patching the source code
to enable this behavior of that sounds at all desirable.

Let me know your thoughts. 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: Does loaddata in fact save objects to DB with a raw save? Or is this a bug?

2011-01-14 Thread Jim D.
> loaddata saves object created via deserialization, which pass raw=True to
> the model's save_base, see:
>
> http://code.djangoproject.com/browser/django/trunk/django/core/serial...

Thanks Karen. That's exactly the answer I was looking for.

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



Does loaddata in fact save objects to DB with a raw save? Or is this a bug?

2011-01-13 Thread Jim D.
I was just now researching some options for how to manage the way
certain post_save/pre_save signals can interfere with fixture loading
during tests, when I happened upon this ticket:

http://code.djangoproject.com/ticket/12610

Which says:

"There is already a hook to check for this - data saved during a
fixture load is loaded 'raw', and the 'raw' argument is passed to the
pre/post save handlers. If you modify your pre/post save handlers to
do nothing in the case of a raw save, you should be able to load
fixtures without the problems you describe."

It made sense to me, but when I why tried to actually use it...I found
raw was not being passed at all to any of my handlers. Closer
examination of loaddata.py does not show it using save_base() or
passing raw anywhere.

So that leaves me confused. Am I overlooking something? Or is comment
by Russel in the ticket wrong?

I might do a bit more research. I imagine there must be a test or
other open ticket specifying the raw behavior, and if so that could be
broken, in which case I'll file a ticket. I figured I'd post here
first before raising the alarm.

-- 
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: BrightonPy event: The Why and How of Automated Testing with Python and Django

2010-11-04 Thread Jim Purbrick
The video and slides for this talk are now online here:
http://jimpurbrick.com/2010/11/04/why-and-how-automated-testing-python-and-django/

Cheers,

Jim

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



Strange Filter Behaviour With UUIDField

2010-10-21 Thread Jim Purbrick
I've just finished patching django.contrib.auth.User to use one of
reverie's UUIDFields (http://gist.github.com/374662) as it's primary
key.

It's mostly been pleasantly straightforward, but I was slightly
puzzled by the need for the patch below, which requires the filter to
explicitly address the id field when the primary key is a UUIDField
(but not when it's an AutoField) in order for the auth tests to pass.

Am I missing something here? Should the UUIDField or the User model be
doing something else in order for the "group__user=user_obj" filter to
work?

Cheers,

Jim

--- backends.py.old 2010-10-21 18:21:06.0 +0100
+++ backends.py 2010-10-21 17:05:19.0 +0100
@@ -25,7 +25,7 @@
 groups.
 """
 if not hasattr(user_obj, '_group_perm_cache'):
-perms = Permission.objects.filter(group__user=user_obj
+perms = Permission.objects.filter(group__user__id=user_obj.id
 ).values_list('content_type__app_label', 'codename'
 ).order_by()
 user_obj._group_perm_cache = set(["%s.%s" % (ct, name)
for ct, name in perms])

-- 
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: Preventing code from running during user tests

2010-09-16 Thread Jim D.
Thanks Russ, that's helpful.

I would think signals would ideally be a solution for this, no? E.g.,
a setup and teardown signal that fired in setup_test_environment() and
teardown_test_environment(), respectfully. I was actually hoping to
find this already implemented when I checked the documentation for
signals.

On Sep 16, 5:13 pm, Russell Keith-Magee <russ...@keith-magee.com>
wrote:
> On Fri, Sep 17, 2010 at 6:15 AM, Jim D. <jim.dal...@gmail.com> wrote:
> > I have some code that calls a third-party API in a Django application
> > I'm working on, which could be triggered at various points throughout
> > a project. I would like to ensure that the API itself doesn't actually
> > get called at all during test mode, much the same way that Django
> > itself swaps out the email backend during test mode to ensure emails
> > don't actually get sent during testing.
>
> > The key point here is I need to ensure the real library isn't being
> > called anywhere during the tests being run throughout the suite, not
> > just in the test code I'm writing specifically for the application
> > itself.
>
> > Is there a clean way to do this? I notice that Django disables the
> > email and a few other settings in the setup_test_environment()
> > function. I'd like to do something similar, but the only idea I've
> > come up with so far is to create a custom test runner that extends the
> > default setup_test_environment() method and adds a few items of my
> > own. While this would work, it would depend on the project using a
> > custom test runner.
>
> > Other ideas include a crazy hack like this guy has proposed:
> >http://www.thebitguru.com/blog/view/246-Using%20custom%20settings%20i...
>
> > Surely others of you have had to ensure a given library isn't called
> > during testing or development (e.g. if you were implementing a payment
> > processor API, you wouldn't want to actually call that library during
> > tests). Am I just missing a totally obvious way to accomplish this?
>
> A custom test runner would be the usual way to accomplish this, and as
> of Django 1.2, it's a lot easier to write one because the test runner
> is class based. On a smaller scale, you could also accomplish this
> using a setUp()/tearDown() pair in individual test cases.
>
> The "if TEST" approach advocated by 'thebitguru' will certainly work,
> but it's not a pattern that I'd like to see take hold in Django
> itself. This approach essentially introduces branches into your main
> codebase, so now you need to be testing whether or not your code is
> hitting the right branches -- in theory, it is possible that your
> production code could activate the "if TEST' branch, so you need to
> test that this won't happen.
>
> If you have a suggestion of a better way to provide setup/teardown
> hooks, I'd be happy to hear it.
>
> Yours,
> Russ Magee %-)

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



Preventing code from running during user tests

2010-09-16 Thread Jim D.
I have some code that calls a third-party API in a Django application
I'm working on, which could be triggered at various points throughout
a project. I would like to ensure that the API itself doesn't actually
get called at all during test mode, much the same way that Django
itself swaps out the email backend during test mode to ensure emails
don't actually get sent during testing.

The key point here is I need to ensure the real library isn't being
called anywhere during the tests being run throughout the suite, not
just in the test code I'm writing specifically for the application
itself.

Is there a clean way to do this? I notice that Django disables the
email and a few other settings in the setup_test_environment()
function. I'd like to do something similar, but the only idea I've
come up with so far is to create a custom test runner that extends the
default setup_test_environment() method and adds a few items of my
own. While this would work, it would depend on the project using a
custom test runner.

Other ideas include a crazy hack like this guy has proposed:
http://www.thebitguru.com/blog/view/246-Using%20custom%20settings%20in%20django%20tests

Surely others of you have had to ensure a given library isn't called
during testing or development (e.g. if you were implementing a payment
processor API, you wouldn't want to actually call that library during
tests). Am I just missing a totally obvious way to accomplish this?

-- 
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 do you avoid this race condition in Django?

2010-09-06 Thread Jim
Maybe I'm not understanding the question but I'd freeze the row in the
database, do the work, and then unfreeze the row.

Jim

-- 
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: Touch-ing django.wsgi doesn't reliably reload source code

2010-08-22 Thread Jim

> Graham

Thank you; that solved my problem.  That was a big help to me.  I
bought a couple of things from your wish list -- I hope that your
child enjoys them.

Jim

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



Touch-ing django.wsgi doesn't reliably reload source code

2010-08-21 Thread Jim
Hello,

I have Django running under apache2 (the worker version, I believe,
with MaxRequestsPerChild set to the default, which is 0).  I am using
mod_wsgi in daemon mode.  I have checked that it is daemon mode using
the method described on mod_wsgi's ReloadingSourceCode page.

I need to do a nightly refresh because I get data for the db from a
coworker somewhere else.  So I have a cron job that does as follows.

  (1) Sets a flag "SITE_UP=False" in the code base file "site_up.py"
that shows up in each RequestContext, causing each dynamic page to say
"site is not up" since base.html looks for that flag {{SITE_UP}}.
  (2) Touches django.wsgi so pages will tell visitors the site is not
up.
  (3) Updates the dB
  (4) Sets the flag from (1) back to its starting value
"SITE_UP=True".
  (5) Touches django.wsgi.

(Step (3) takes perhaps a half hour.  If there is a better way to do
what I am trying to do, I'd be very glad to hear it.)

The problem is: I come in the next morning and sometimes the pages
work, while sometimes they say "Site is no up".

If I keep refreshing a page in my browser then sometimes it works
correctly and gives me the new data, and sometimes it says "not up."

If I restart apache, the problem of showing "not up" disappears.

I had thought that Apache's children talk to the wsgi processes (I
have 4 of them), which mod_wsgi's ReloadingSourceCode page tells me
will be restarted.But obviously I'm not understanding something.

I wonder if anyone has a suggestion about how I am going wrong?  I was
hopeful of finding a way to accomplish this without having to restart
apache from a cron job.

Thank you,
Jim

-- 
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: passing a keyword argument from form to a field in that form

2010-08-03 Thread Jim
On Aug 3, 3:59 am, Daniel Roseman <dan...@roseman.org.uk> wrote:
> This code looks absolutely right.

Boy there's a phrase I don't hear often!

> What do you mean by 'setting
> self.fields didn't work'? How did it not work? What didn't happen that
> you expected to happen? Did you get errors?

If I put in a statement logging the value of self.show_all, it is
unaffected by whether I call KeywordsForm as
KeywordsForm(show_all=True) or KeywordsForm(show_all=False).

> That is the usual way of dynamically setting an attribute on a field,
> and I've used it many times with no problems.

Thank you, Daniel; it is helpful to know that I have the right
approach but must have a bug somewhere.  I'll have another whack at
it-- sometimes a nights sleep makes plain some imbecility on my
part.  :-)

Jim

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



passing a keyword argument from form to a field in that form

2010-08-02 Thread Jim
Hello,

I have a custom field whose behavior depends on a parameter show_all.
(It makes the field pull from the database for display only those
keywords where show=True.)

class KeywordsField(forms.ChoiceField):
def __init__(self, choices=(), required=True,
widget=widgets.KeywordsWidget, label=None, initial=None,
show_all=False, help_text=None):
self.show_all=show_all
super(KeywordsField, self).__init__(choices=self.choices,
required=required, widget=widget, label=label, initial=initial,
help_text=help_text)

(edited; I hope I didn't introduce any typos.)

I have a form that I'd like to call as
f0=KeywordsForm(show_all=True)
and pass show_all to the field.  Here is my try.

class KeywordsForm(forms.Form):
keywords=KeywordsField(required=False)

def __init__(self, show_all=False, *args, **kwargs):
self.show_all = show_all
super(KeywordsForm, self).__init__(*args, **kwargs)
self.fields['keywords'].show_all=show_all

Setting self.fields didn't work (or I wouldn't be writing).  Neither
did calling this.
keywords=KeywordsField(required=False,show_all=self.show_all)
Neither did a fair amount of looking at the documentation, the source,
and googling, although no doubt I didn't do it right.

Can someone give me a hint about how I should do it?  I'd be grateful.
Jim

-- 
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: check md5sum on an uploaded file

2010-07-15 Thread Jim
Could you clarify what you want to do beyond saving the file somewhere
and running  md5 on 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-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 set initial form field value in the view function?

2010-07-04 Thread Jim
> The initial keyword is great when defining a subclass of Form if you
> the initial values is ALWAYS the same.
>
> What if it varies?...I'm guessing I must set it in the view.

From:
  http://docs.djangoproject.com/en/1.2/ref/forms/api/#dynamic-initial-values
we have:
  Dynamic initial values¶
  Form.initial
  Use initial to declare the initial value of form fields at runtime.
For example, you might want to fill in a username field with the
username of the current session.

Possibly you could restate your requirement?  At least I'm not seeing
why
  fm(initial={'x':variable_name})
won't help you.

Or possibly you want to override the __init__ method of the form?

Jim

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



Unsubsubscribe

2010-06-06 Thread Jim Norman
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

How do I unsubscribe from this list?

Jim Norman
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkwMVVMACgkQ677kSNWvnhS3EQCeO2OguYmNhKiyywl2HqXnLslF
yUYAn2SxlG+C359KA0quWLNsq0VNn0QA
=DPg7
-END PGP SIGNATURE-

-- 
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: Performing an action on model.save() but not on update

2010-04-26 Thread Jim N
Nick,

Thanks very much.  That worked!  I can't work out why my code didn't
though (or rather, worked twice).

-Jim

On Apr 23, 6:37 pm, Nick Serra <nickse...@gmail.com> wrote:
> Try this out and see what happens:
>
> def _hook_post_save_answer(instance, created, sender, **kwargs):
>     if created:
>         if instance.user:
>             quser = instance.user.get_profile()
>             quser.increment_answers()
>         instance.question.increment_responses()
>
> post_save.connect(_hook_post_save_answer, sender=Answer)
>
> On Apr 23, 6:20 pm, Jim N <jim.nach...@gmail.com> wrote:
>
>
>
> > OK, that makes total sense.
>
> > I've implemented it like so:
>
> > def _hook_post_save_answer(instance, sender, **kwargs):
> >     if 'created' in kwargs and kwargs['created'] == True:
> >         if instance.user:
> >             quser = instance.user.get_profile()
> >             quser.increment_answers()
> >         instance.question.increment_responses()
>
> > post_save.connect(_hook_post_save_answer, sender=Answer)
>
> >http://dpaste.de/897o/
>
> > But now, it increments TWICE!
>
> > Is there some glaring error in my logic above?
>
> > On Apr 23, 4:50 pm, Nick Serra <nickse...@gmail.com> wrote:
>
> > > I didn't even think of that. It's not very common to be specifying
> > > pk's on create anyway, so yours would probably be fine. I just think
> > > signals are cleaner and use them when I can :)
>
> > > On Apr 23, 4:47 pm, Skylar Saveland <skylar.savel...@gmail.com> wrote:
>
> > > > Yeah, and I think my suggestion fails for a user-defined rather than
> > > > auto-incrementing pk.
>
> > > > On Apr 23, 4:21 pm, Nick Serra <nickse...@gmail.com> wrote:
>
> > > > > A post save signal seems better suited for this. The post save signal
> > > > > has an attribute 'created' that will be true or false depending on if
> > > > > the object is being created or updated. Check out the post_save
> > > > > documentation:http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.si...
>
> > > > > On Apr 23, 3:32 pm, Skylar Saveland <skylar.savel...@gmail.com> wrote:
>
> > > > > > On Apr 23, 3:27 pm, Jim N <jim.nach...@gmail.com> wrote:
>
> > > > > > > Hi,
>
> > > > > > > I have overridden the default save() on a model so that I can 
> > > > > > > update
> > > > > > > some counts every time a save occurs.  Unfortunately, I don't 
> > > > > > > want to
> > > > > > > perform these actions every time the model is updated, which 
> > > > > > > seems to
> > > > > > > happen.
>
> > > > > > > Is there another approach I can take that distinguishes between 
> > > > > > > save
> > > > > > > and update?
>
> > > > > > > class Answer(models.Model):
> > > > > > >     answer = models.TextField()
> > > > > > >     user = models.ForeignKey(User, null=True)
> > > > > > >     submit_date = models.DateTimeField('Date Submitted',
> > > > > > > default=datetime.datetime.now)
> > > > > > >     question = models.ForeignKey(Question)
> > > > > > >     permalink = models.CharField(max_length=300, blank=True)
>
> > > > > > >     def save(self, *args, **kwargs):
> > > > > > >         super(Answer, self).save(*args, **kwargs) # Call the 
> > > > > > > "real"
> > > > > > > save() method.
> > > > > > >         if(self.user):
> > > > > > >             quser = self.user.get_profile()
> > > > > > >             quser.increment_answers()   # <-- I don't want to do 
> > > > > > > this
> > > > > > > on an update.
> > > > > > >             self.question.increment_responses() # <-- I don't 
> > > > > > > want to
> > > > > > > do this either.
>
> > > > > > > Or in more readable form:http://dpaste.de/I2IR/
>
> > > > > > Before you call super you can see if bool(self.pk) is True or False.
> > > > > > It will be False before the first save.
>
> > > > > > --
> > > > > > You received this message because you are subscribed to the Google 
> >

Re: Performing an action on model.save() but not on update

2010-04-23 Thread Jim N
OK, that makes total sense.


I've implemented it like so:


def _hook_post_save_answer(instance, sender, **kwargs):
if 'created' in kwargs and kwargs['created'] == True:
if instance.user:
quser = instance.user.get_profile()
quser.increment_answers()
instance.question.increment_responses()

post_save.connect(_hook_post_save_answer, sender=Answer)

http://dpaste.de/897o/


But now, it increments TWICE!

Is there some glaring error in my logic above?



On Apr 23, 4:50 pm, Nick Serra <nickse...@gmail.com> wrote:
> I didn't even think of that. It's not very common to be specifying
> pk's on create anyway, so yours would probably be fine. I just think
> signals are cleaner and use them when I can :)
>
> On Apr 23, 4:47 pm, Skylar Saveland <skylar.savel...@gmail.com> wrote:
>
>
>
> > Yeah, and I think my suggestion fails for a user-defined rather than
> > auto-incrementing pk.
>
> > On Apr 23, 4:21 pm, Nick Serra <nickse...@gmail.com> wrote:
>
> > > A post save signal seems better suited for this. The post save signal
> > > has an attribute 'created' that will be true or false depending on if
> > > the object is being created or updated. Check out the post_save
> > > documentation:http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.si...
>
> > > On Apr 23, 3:32 pm, Skylar Saveland <skylar.savel...@gmail.com> wrote:
>
> > > > On Apr 23, 3:27 pm, Jim N <jim.nach...@gmail.com> wrote:
>
> > > > > Hi,
>
> > > > > I have overridden the default save() on a model so that I can update
> > > > > some counts every time a save occurs.  Unfortunately, I don't want to
> > > > > perform these actions every time the model is updated, which seems to
> > > > > happen.
>
> > > > > Is there another approach I can take that distinguishes between save
> > > > > and update?
>
> > > > > class Answer(models.Model):
> > > > >     answer = models.TextField()
> > > > >     user = models.ForeignKey(User, null=True)
> > > > >     submit_date = models.DateTimeField('Date Submitted',
> > > > > default=datetime.datetime.now)
> > > > >     question = models.ForeignKey(Question)
> > > > >     permalink = models.CharField(max_length=300, blank=True)
>
> > > > >     def save(self, *args, **kwargs):
> > > > >         super(Answer, self).save(*args, **kwargs) # Call the "real"
> > > > > save() method.
> > > > >         if(self.user):
> > > > >             quser = self.user.get_profile()
> > > > >             quser.increment_answers()   # <-- I don't want to do this
> > > > > on an update.
> > > > >             self.question.increment_responses() # <-- I don't want to
> > > > > do this either.
>
> > > > > Or in more readable form:http://dpaste.de/I2IR/
>
> > > > Before you call super you can see if bool(self.pk) is True or False.
> > > > It will be False before the first 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 
> > > 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 
> > 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 
> 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.



Performing an action on model.save() but not on update

2010-04-23 Thread Jim N
Hi,

I have overridden the default save() on a model so that I can update
some counts every time a save occurs.  Unfortunately, I don't want to
perform these actions every time the model is updated, which seems to
happen.

Is there another approach I can take that distinguishes between save
and update?

class Answer(models.Model):
answer = models.TextField()
user = models.ForeignKey(User, null=True)
submit_date = models.DateTimeField('Date Submitted',
default=datetime.datetime.now)
question = models.ForeignKey(Question)
permalink = models.CharField(max_length=300, blank=True)


def save(self, *args, **kwargs):
super(Answer, self).save(*args, **kwargs) # Call the "real"
save() method.
if(self.user):
quser = self.user.get_profile()
quser.increment_answers()   # <-- I don't want to do this
on an update.
self.question.increment_responses() # <-- I don't want to
do this either.


Or in more readable form: http://dpaste.de/I2IR/


TIA!

-Jim

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



  1   2   3   >