Re: ModelAdmin

2023-01-04 Thread Mike Dewhirst

Satyajit

I'm speaking for myself here.

I'm not comfortable with dilution of list content with what appears to 
be a competing Whatsapp group.


In particular, this thread is one to which I have contributed and if you 
kidnap the thread you cut me out of my conversation.


In general, if you take conversations away from the list you hide them 
from core Django devs who are then deprived of information coming from 
users. Django users are exactly equal to customers of an enterprise and 
if an enterprise doesn't hear customer feedback it risks becoming 
irrelevant and possibly going out of business.


I think Whatsapp, Slack etc are all very appropriate places for private 
conversations. Not so much for a user mutual-support mailing list like 
this one.


 Thanks for understanding

Cheers

Mike

On 5/01/2023 3:31 pm, Satyajit Barik wrote:
Yes. It does. ModelAdmin classes can define list filters that appear 
in the right sidebar of the change list page of the admin.
For more reference: 
https://docs.djangoproject.com/en/4.1/ref/contrib/admin/filters/


For this topic related join our WhatsApp group: https://bit.ly/3oJtfcf

Regards,
Satyajit

On Thu, Jan 5, 2023 at 9:09 AM Mike Dewhirst  
wrote:


On 5/01/2023 5:43 am, Mario St-Gelais wrote:

Hello group, first post here.
Quick question.  Can capabilities of ModelAdmin such as
list_filter or search_fields be used outside of the admin interface?


Have you looked at htmx?

https://www.simplecto.com/htmx-and-the-list_editable-in-django-admin/

htmx is very sweet. Essentially, you can replace a named  on an existing page by calling whatever view
you care to write. Your view might have to borrow from the Django
code if you really like what it does.

Digressing slightly, I discovered that you can make a link in html
using the  entity and just replace href="/search" with
hx_trigger="/hx_search", for example, so that the existing css
works and it looks like an ordinary link.

Cheers

mike



I want a view that would allow non logged users to search a site
through checkboxes and some search fields possibly and obviously,
the way this is implemented in the admin view is rather good.

Alternatively, what approach can be used in django?

Thanks
Mario
-- 
You received this message because you are subscribed to the

Google Groups "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/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.com

<https://groups.google.com/d/msgid/django-users/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.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/6b16042c-dd2b-9757-2edc-1bbae0e7d911%40dewhirst.com.au

<https://groups.google.com/d/msgid/django-users/6b16042c-dd2b-9757-2edc-1bbae0e7d911%40dewhirst.com.au?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/CANd-%2BoD5Nrj1OxsSHvy8nVru5u1Hw1yWzJ19k7tAoEZOoovQBg%40mail.gmail.com 
<https://groups.google.com/d/msgid/django-users/CANd-%2BoD5Nrj1OxsSHvy8nVru5u1Hw1yWzJ19k7tAoEZOoovQBg%40mail.gmail.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/83079885-1bb7-81a1-75d9-753d195af702%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


Re: ModelAdmin

2023-01-04 Thread Satyajit Barik
Yes. It does. ModelAdmin classes can define list filters that appear in the
right sidebar of the change list page of the admin.
For more reference:
https://docs.djangoproject.com/en/4.1/ref/contrib/admin/filters/

For this topic related join our WhatsApp group: https://bit.ly/3oJtfcf

Regards,
Satyajit

On Thu, Jan 5, 2023 at 9:09 AM Mike Dewhirst  wrote:

> On 5/01/2023 5:43 am, Mario St-Gelais wrote:
>
> Hello group, first post here.
> Quick question.  Can capabilities of ModelAdmin such as list_filter or
> search_fields be used outside of the admin interface?
>
>
> Have you looked at htmx?
>
> https://www.simplecto.com/htmx-and-the-list_editable-in-django-admin/
>
> htmx is very sweet. Essentially, you can replace a named  id="whatever"> on an existing page by calling whatever view you care
> to write. Your view might have to borrow from the Django code if you really
> like what it does.
>
> Digressing slightly, I discovered that you can make a link in html using
> the  entity and just replace href="/search" with
> hx_trigger="/hx_search", for example, so that the existing css works and it
> looks like an ordinary link.
>
> Cheers
>
> mike
>
>
> I want a view that would allow non logged users to search a site through
> checkboxes and some search fields possibly and obviously, the way this is
> implemented in the admin view is rather good.
>
> Alternatively, what approach can be used in django?
>
> Thanks
> Mario
> --
> You received this message because you are subscribed to the Google Groups
> "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/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.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/6b16042c-dd2b-9757-2edc-1bbae0e7d911%40dewhirst.com.au
> <https://groups.google.com/d/msgid/django-users/6b16042c-dd2b-9757-2edc-1bbae0e7d911%40dewhirst.com.au?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/CANd-%2BoD5Nrj1OxsSHvy8nVru5u1Hw1yWzJ19k7tAoEZOoovQBg%40mail.gmail.com.


Re: ModelAdmin

2023-01-04 Thread Mike Dewhirst

On 5/01/2023 5:43 am, Mario St-Gelais wrote:

Hello group, first post here.
Quick question.  Can capabilities of ModelAdmin such as list_filter or 
search_fields be used outside of the admin interface?


Have you looked at htmx?

https://www.simplecto.com/htmx-and-the-list_editable-in-django-admin/

htmx is very sweet. Essentially, you can replace a named id="whatever"> on an existing page by calling whatever view you 
care to write. Your view might have to borrow from the Django code if 
you really like what it does.


Digressing slightly, I discovered that you can make a link in html using 
the  entity and just replace href="/search" with 
hx_trigger="/hx_search", for example, so that the existing css works and 
it looks like an ordinary link.


Cheers

mike



I want a view that would allow non logged users to search a site 
through checkboxes and some search fields possibly and obviously, the 
way this is implemented in the admin view is rather good.


Alternatively, what approach can be used in django?

Thanks
Mario
--
You received this message because you are subscribed to the Google 
Groups "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/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.com 
<https://groups.google.com/d/msgid/django-users/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.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/6b16042c-dd2b-9757-2edc-1bbae0e7d911%40dewhirst.com.au.


OpenPGP_signature
Description: OpenPGP digital signature


ModelAdmin

2023-01-04 Thread Mario St-Gelais
Hello group, first post here.
Quick question.  Can capabilities of ModelAdmin such as list_filter or
search_fields be used outside of the admin interface?

I want a view that would allow non logged users to search a site through
checkboxes and some search fields possibly and obviously, the way this is
implemented in the admin view is rather good.

Alternatively, what approach can be used in django?

Thanks
Mario

-- 
You received this message because you are subscribed to the Google Groups 
"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/CAFmF6_vLzivA3Y-sskqmcZzsuLc27opP6xW3m3wvmV7nepu%3D-A%40mail.gmail.com.


Curious about ModelAdmin internals.. how the hell does it work

2021-09-01 Thread Michal Plsek
Hello, I would like to know about this (although I hacked around it, but I 
am still curious):

if I have model which contains ForeignKey attribute and I am using 
autocomplete_fields on it, where is the found FK of foreign object saved on 
ModelAdmin page?
Numerical ID of foreign object represented by usual SELECTBOX is marked 
using **. I understand reasons why this is not 
done with autocomplete_fields, but I would presume the found value of FK 
would be saved in some* * or something like that, 
which is obviously not.

So, using autocomplete_fields, how can I get the found FK value on page?

(q on SO: 
https://stackoverflow.com/questions/69016647/where-is-id-saved-in-django-modeladmin-autocomplete-fields
 
)

-- 
You received this message because you are subscribed to the Google Groups 
"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/b12187f2-af5c-4631-a20e-b7648c97e89bn%40googlegroups.com.


Re: How to hide/disable ModelAdmin

2021-03-05 Thread zvo...@seznam.cz
Seems I know the answer:

class HiddenAdmin(admin.ModelAdmin):
has_module_permission = lambda self, req: False

https://stackoverflow.com/questions/2431727/django-admin-hide-a-model
https://stackoverflow.com/questions/49293901/hide-model-from-main-admin-list-but-allow-creation-in-inline-editor
Dne čtvrtek 4. března 2021 v 21:22:41 UTC+1 uživatel zvo...@seznam.cz 
napsal:

> I want use Django 2+ autocomplete_fields.
> Adding them into (source) ModelAdmin will give lot of errors (see bellow).
> So I must add a (target) ModelAdmin with search_fields=...
>
> After that everything works.
> However I don't want to have such new ModelAdmin's visible/accessible.
> I have data of their models already much better accessible in Inlines.
>
> Is there a way how to give search_fields=.. and not show the new 
> ModelAdmin?
>
> Thank you.
>
> ```
> ERRORS: 
> : (admin.E039) An admin for model 
> "PartVariant" has to be registered to be referenced by 
> PartCodeInline.autocomplete_fields. 
> : (admin.E040) PartCodeTypeAdmin 
> must define "search_fields", because it's referenced by 
> PartCodeInline.autocomplete_fields. 
> : (admin.E039) An admin for model 
> "Size" has to be registered to be referenced by 
> PartSizeInline.autocomplete_fields. 
> : (admin.E039) An admin for 
> model "Size" has to be registered to be referenced by 
> PartSubGroupInline.autocomplete_fields.
> ```
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/98a443b2-15f7-4172-bd8e-1635dc98f30an%40googlegroups.com.


How to hide/disable ModelAdmin

2021-03-04 Thread zvo...@seznam.cz
I want use Django 2+ autocomplete_fields.
Adding them into (source) ModelAdmin will give lot of errors (see bellow).
So I must add a (target) ModelAdmin with search_fields=...

After that everything works.
However I don't want to have such new ModelAdmin's visible/accessible.
I have data of their models already much better accessible in Inlines.

Is there a way how to give search_fields=.. and not show the new ModelAdmin?

Thank you.

```
ERRORS: 
: (admin.E039) An admin for model 
"PartVariant" has to be registered to be referenced by 
PartCodeInline.autocomplete_fields. 
: (admin.E040) PartCodeTypeAdmin 
must define "search_fields", because it's referenced by 
PartCodeInline.autocomplete_fields. 
: (admin.E039) An admin for model 
"Size" has to be registered to be referenced by 
PartSizeInline.autocomplete_fields. 
: (admin.E039) An admin for 
model "Size" has to be registered to be referenced by 
PartSubGroupInline.autocomplete_fields.
```

-- 
You received this message because you are subscribed to the Google Groups 
"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/2d5c4536-9e1f-49f6-93a9-31802a80e12cn%40googlegroups.com.


Re: ModelAdmin Not work

2020-09-24 Thread John Rajesh
First correct email to email
On 24 Sep 2020 00:33, "coolguy"  wrote:

> either use admin.site.register
> OR
> *@*admin.register(User)
>
> On Wednesday, September 23, 2020 at 11:01:43 AM UTC-4 kkwaq...@gmail.com
> wrote:
>
>> *models.py*
>>
>> [image: 1.jpg]
>>
>> *admin.py*
>>
>> *[image: 2.jpg]*
>>
>> *errors*
>>
>>
>> *[image: 3.jpg]*
>>
>> *Object is not callable*
>>
>> *Please any body solutions *
>>
> --
> You received this message because you are subscribed to the Google Groups
> "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/00354cdd-5478-4ee5-9e44-95098e393c83n%
> 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/CA%2BbM%2BwDz86eHRda1fXb4DHRjipVu7xJsqmWHKEaThpRsdMP5VA%40mail.gmail.com.


Re: ModelAdmin Not work

2020-09-23 Thread coolguy
either use admin.site.register
OR
*@*admin.register(User)

On Wednesday, September 23, 2020 at 11:01:43 AM UTC-4 kkwaq...@gmail.com 
wrote:

> *models.py*
>
> [image: 1.jpg]
>
> *admin.py*
>
> *[image: 2.jpg]*
>
> *errors*
>
>
> *[image: 3.jpg]*
>
> *Object is not callable*
>
> *Please any body solutions *
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/00354cdd-5478-4ee5-9e44-95098e393c83n%40googlegroups.com.


ModelAdmin Not work

2020-09-23 Thread kkwaq...@gmail.com
*models.py*

[image: 1.jpg]

*admin.py*

*[image: 2.jpg]*

*errors*


*[image: 3.jpg]*

*Object is not callable*

*Please any body solutions *

-- 
You received this message because you are subscribed to the Google Groups 
"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/4e4ddd71-1b26-4976-a2a3-a19cf04f568an%40googlegroups.com.


ModelAdmin Media assets with django 1.8

2020-06-11 Thread Amirouche Boubekki
Using Django 1.8, I do not understand what is the behavior of `Media` [0] 
inside a `ModelAdmin` subclass.

In particular, whether the default behavior of form's media is applied in 
`ModelAdmin` that is: `extend=True` [1]

I am under the impression that the behavior is implemented in 
`options.ModelAdmin.media` property [2], maybe there is more to it than 
that since it has a custom metaclass.


Thanks in advance !

[0] 
https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#modeladmin-asset-definitions
[1] https://docs.djangoproject.com/en/1.8/topics/forms/media/#extend
[2] 
https://github.com/django/django/blob/6a0dc2176f4ebf907e124d433411e52bba39a28e/django/contrib/admin/options.py#L636-L649

-- 
You received this message because you are subscribed to the Google Groups 
"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/1235108b-e561-4866-970e-f899c3c3acf3o%40googlegroups.com.


Overriding change_list_results template per ModelAdmin

2019-10-17 Thread Luka Jančin
I have a model which is registered to two different admin sites with two 
ModelAdmins. 
I would like to override the template for change_list_results for each 
ModelAdmin independently. Currently it's not possible the same way you can 
do it for add_form_template, change_form_template etc. by overriding the 
appropriate member.
Is it possible to achieve this some other way?

-- 
You received this message because you are subscribed to the Google Groups 
"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/d2dcfd18-9fc2-4789-9ab3-28754fc144dd%40googlegroups.com.


Re: How to override the ModelAdmin "change" form ?

2019-03-01 Thread Mike Dewhirst

On 2/03/2019 2:08 am, karim.at...@gmail.com wrote:

Hi Mike,

I tried what you wrote by overriding the *self.change_form_template* 
but the form does not appear.
Would you please provide me the content of your model admin 
*billing_payment_view ?*


Sure. I recently asked for assistance here and posted most of the code ...

https://groups.google.com/forum/#!topic/django-users/809HBmPa9vk

You are right, my application is different. My template contains a 
script provided by Stripe which calls their API to collect a credit card 
payment. But overall it isn't much different than any other template 
called by any other view. The view just takes a different path depending 
on whether it is a POST or a GET request. My view looks complex because 
when the user clicks [Pay now] it happens in the Stripe js embedded in 
the template and the Stripe API - in turn - hits my view with the actual 
POST containing the result of the credit card transaction. I had to seed 
the form/template with hidden data so it travelled across the Stripe 
boundary and back to me so I could complete the processing. If you can 
see past that complication it should be clear that I'm using the form to 
clean the data and the view to interface with the ORM/database.


It is working well for me now and I'm in the middle of writing unit tests.

Good luck



Thanks.

Karim

Le vendredi 1 mars 2019 00:06:40 UTC+1, Mike Dewhirst a écrit :

On 28/02/2019 9:46 pm, karim...@gmail.com  wrote:

Hi,

I'm currently struggling with a custom ModelAdmin.


Karim

I haven't tried to fully understand your use case. However, this
is what I think your process could be if you do not wish to ajax
it ...

1. Override the model save() method to call a model method which
detects your trigger scenario and calls the code you wish to
execute to collect all the data you wish to display. This might be
in the parent model or the m2m 'through' model. Unlikely to be in
the child model.

2. Write a Form to reveal the data you wish to display. It
probably needs to be a ModelForm

3. Write a template for the data including any hidden fields for
object pks and additionally consider calling {{ block.super }} to
display inherited stuff if you are extending another template and
using the same block. When I first started to work all this out I
was able to get my form to appear at the top of the ModelAdmin
form using block.super and spent a bit of time hiding the big red
[Delete] button because it was too close to my big blue [Pay now]
button. However, as I got deeper into it I somehow lost that and
never got it back. I was so pleased with getting it working
eventually that I persuaded myself I didn't really want it on the
same page anyway. Your mileage may vary :) I think you need to
hard-code the form in the ModelAdmin to get it appearing above
everything else.

4. Write any necessary urls

5. Write a view to manipulate your data, based on the request and
your form

6. Get the Admin to display it on demand. The first line of the
change_view() method below initialises the ModelAdmin to do
absolutely nothing different than usual. Nothing will happen
unless the trigger is detected. Then finally call to super to
resume the normal course of events when your code is complete.
What follows is my own recent experience. The comments should tell
you more than the code

def change_view(self, request, object_id, form_url='', extra_context=None):

     """ self = SubstanceAdmin
 request = wsgi request object
 object_id = substance
 form_url = no idea!
 extra_context = dict of apps, models, admin_urls and permissions

 https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django  
<https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django>.
 contrib.admin.ModelAdmin.change_view

     """
 # Let the ModelAdmin resume normal operations with its own template
 self.change_form_template = None
 # queryset of m2m records from the 'through' table
 ingredients = 
Substance_Ingredients.objects.filter(substance_id=object_id)
 subscription = None
 for sm2mi in ingredients:
 # sm2mi.fee_payable() is the detector which triggers the process
 payable, fee_type = sm2mi.fee_payable()  # eg., True, PAID_DATA
 if payable:
 # generate a subscription record with blank token field or
 # if one exists with a non-blank token, return None
 subscription = billing_subscribe(sm2mi, fee_type)
 if subscription:# collect money for the owner
 # switch the ModelAdmin to the new template
 self.change_form_template = 'payment.html'
 # assemble

Re: How to override the ModelAdmin "change" form ?

2019-03-01 Thread karim . atiki
Hi Mike,

I tried what you wrote by overriding the *self.change_form_template* but 
the form does not appear.
Would you please provide me the content of your model admin  
*billing_payment_view 
?*

Thanks.

Karim

Le vendredi 1 mars 2019 00:06:40 UTC+1, Mike Dewhirst a écrit :
>
> On 28/02/2019 9:46 pm, karim...@gmail.com  wrote:
>
> Hi, 
>
> I'm currently struggling with a custom ModelAdmin.
>
>
> Karim
>
> I haven't tried to fully understand your use case. However, this is what I 
> think your process could be if you do not wish to ajax it ...
>
> 1. Override the model save() method to call a model method which detects 
> your trigger scenario and calls the code you wish to execute to collect all 
> the data you wish to display. This might be in the parent model or the m2m 
> 'through' model. Unlikely to be in the child model.
>
> 2. Write a Form to reveal the data you wish to display. It probably needs 
> to be a ModelForm
>
> 3. Write a template for the data including any hidden fields for object 
> pks and additionally consider calling {{ block.super }} to display 
> inherited stuff if you are extending another template and using the same 
> block. When I first started to work all this out I was able to get my form 
> to appear at the top of the ModelAdmin form using block.super and spent a 
> bit of time hiding the big red [Delete] button because it was too close to 
> my big blue [Pay now] button. However, as I got deeper into it I somehow 
> lost that and never got it back. I was so pleased with getting it working 
> eventually that I persuaded myself I didn't really want it on the same page 
> anyway. Your mileage may vary :) I think you need to hard-code the form in 
> the ModelAdmin to get it appearing above everything else.
>
> 4. Write any necessary urls
>
> 5. Write a view to manipulate your data, based on the request and your form
>
> 6. Get the Admin to display it on demand. The first line of the 
> change_view() method below initialises the ModelAdmin to do absolutely 
> nothing different than usual. Nothing will happen unless the trigger is 
> detected. Then finally call to super to resume the normal course of events 
> when your code is complete. What follows is my own recent experience. The 
> comments should tell you more than the code
>
> def change_view(self, request, object_id, form_url='', extra_context=None):
>
> """ self = SubstanceAdmin
> request = wsgi request object
> object_id = substance
> form_url = no idea!
> extra_context = dict of apps, models, admin_urls and permissions
>
> https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.
> contrib.admin.ModelAdmin.change_view 
>
> """
> # Let the ModelAdmin resume normal operations with its own template
> self.change_form_template = None
> # queryset of m2m records from the 'through' table
> ingredients = Substance_Ingredients.objects.filter(substance_id=object_id)
> subscription = None
> for sm2mi in ingredients:
> # sm2mi.fee_payable() is the detector which triggers the process
> payable, fee_type = sm2mi.fee_payable()  # eg., True, PAID_DATA
> if payable:
> # generate a subscription record with blank token field or
>     # if one exists with a non-blank token, return None
> subscription = billing_subscribe(sm2mi, fee_type)
> if subscription:# collect money for the owner
> # switch the ModelAdmin to the new template
> self.change_form_template = 'payment.html'
> # assemble all the necessary data for the view
> context = billing_collect_context(
> sm2mi,
> subscription,
> )
> # get everything into the payment_view context
> if not extra_context:
> extra_context = dict()
> extra_context.update(self.admin_site.each_context(request))
> extra_context.update(context)
> # wrap the view to protect it with Admin permissions
> self.admin_site.admin_view(
> # call the view with request and context
> billing_payment_view(
> request,
> sm2mi,
> subscription,
> context=extra_context,
> )
> )
> # only one sm2mi at a time
> break
> return super(SubstanceAdmin, self).change_view(
> request, object_id, form_url, extra_context
> )

Re: How to override the ModelAdmin "change" form ?

2019-03-01 Thread karim . atiki
Hi Mike,

Thanks a lot for your feedback.
Your situation is quiet different from mine, BUT the way you override 
change_view and the related template will certainly help me to achieve what 
I need.
...and getting rid of dirty and unnecessary ajax calls.

I keep you posted.

Thx.

Karim

Le vendredi 1 mars 2019 00:06:40 UTC+1, Mike Dewhirst a écrit :
>
> On 28/02/2019 9:46 pm, karim...@gmail.com  wrote:
>
> Hi, 
>
> I'm currently struggling with a custom ModelAdmin.
>
>
> Karim
>
> I haven't tried to fully understand your use case. However, this is what I 
> think your process could be if you do not wish to ajax it ...
>
> 1. Override the model save() method to call a model method which detects 
> your trigger scenario and calls the code you wish to execute to collect all 
> the data you wish to display. This might be in the parent model or the m2m 
> 'through' model. Unlikely to be in the child model.
>
> 2. Write a Form to reveal the data you wish to display. It probably needs 
> to be a ModelForm
>
> 3. Write a template for the data including any hidden fields for object 
> pks and additionally consider calling {{ block.super }} to display 
> inherited stuff if you are extending another template and using the same 
> block. When I first started to work all this out I was able to get my form 
> to appear at the top of the ModelAdmin form using block.super and spent a 
> bit of time hiding the big red [Delete] button because it was too close to 
> my big blue [Pay now] button. However, as I got deeper into it I somehow 
> lost that and never got it back. I was so pleased with getting it working 
> eventually that I persuaded myself I didn't really want it on the same page 
> anyway. Your mileage may vary :) I think you need to hard-code the form in 
> the ModelAdmin to get it appearing above everything else.
>
> 4. Write any necessary urls
>
> 5. Write a view to manipulate your data, based on the request and your form
>
> 6. Get the Admin to display it on demand. The first line of the 
> change_view() method below initialises the ModelAdmin to do absolutely 
> nothing different than usual. Nothing will happen unless the trigger is 
> detected. Then finally call to super to resume the normal course of events 
> when your code is complete. What follows is my own recent experience. The 
> comments should tell you more than the code
>
> def change_view(self, request, object_id, form_url='', extra_context=None):
>
> """ self = SubstanceAdmin
> request = wsgi request object
> object_id = substance
> form_url = no idea!
> extra_context = dict of apps, models, admin_urls and permissions
>
> https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.
> contrib.admin.ModelAdmin.change_view 
>
> """
> # Let the ModelAdmin resume normal operations with its own template
> self.change_form_template = None
> # queryset of m2m records from the 'through' table
> ingredients = Substance_Ingredients.objects.filter(substance_id=object_id)
> subscription = None
> for sm2mi in ingredients:
> # sm2mi.fee_payable() is the detector which triggers the process
> payable, fee_type = sm2mi.fee_payable()  # eg., True, PAID_DATA
> if payable:
> # generate a subscription record with blank token field or
>     # if one exists with a non-blank token, return None
> subscription = billing_subscribe(sm2mi, fee_type)
> if subscription:# collect money for the owner
> # switch the ModelAdmin to the new template
> self.change_form_template = 'payment.html'
> # assemble all the necessary data for the view
> context = billing_collect_context(
> sm2mi,
> subscription,
> )
> # get everything into the payment_view context
> if not extra_context:
> extra_context = dict()
> extra_context.update(self.admin_site.each_context(request))
> extra_context.update(context)
> # wrap the view to protect it with Admin permissions
> self.admin_site.admin_view(
> # call the view with request and context
> billing_payment_view(
> request,
> sm2mi,
> subscription,
> context=extra_context,
> )
> )
> # only one sm2mi at a time
> break
> return super(SubstanceAdmin, self).change_vi

Re: How to override the ModelAdmin "change" form ?

2019-02-28 Thread Mike Dewhirst

  
  
On 28/02/2019 9:46 pm,
  karim.at...@gmail.com wrote:


  
  Hi,


I'm currently struggling with a custom ModelAdmin.
  


Karim

I haven't tried to fully understand your use case. However, this is
what I think your process could be if you do not wish to ajax it ...

1. Override the model save() method to call a model method which
detects your trigger scenario and calls the code you wish to execute
to collect all the data you wish to display. This might be in the
parent model or the m2m 'through' model. Unlikely to be in the child
model.

2. Write a Form to reveal the data you wish to display. It probably
needs to be a ModelForm

3. Write a template for the data including any hidden fields for
object pks and additionally consider calling {{ block.super }} to
display inherited stuff if you are extending another template and
using the same block. When I first started to work all this out I
was able to get my form to appear at the top of the ModelAdmin form
using block.super and spent a bit of time hiding the big red
[Delete] button because it was too close to my big blue [Pay now]
button. However, as I got deeper into it I somehow lost that and
never got it back. I was so pleased with getting it working
eventually that I persuaded myself I didn't really want it on the
same page anyway. Your mileage may vary :) I think you need to
hard-code the form in the ModelAdmin to get it appearing above
everything else.

4. Write any necessary urls

5. Write a view to manipulate your data, based on the request and
your form

6. Get the Admin to display it on demand. The first line of the
change_view() method below initialises the ModelAdmin to do
absolutely nothing different than usual. Nothing will happen unless
the trigger is detected. Then finally call to super to resume the
normal course of events when your code is complete. What follows is
my own recent experience. The comments should tell you more than the
code

def change_view(self, request, object_id, form_url='', extra_context=None):
    """ self = SubstanceAdmin
request = wsgi request object
object_id = substance
form_url = no idea!
extra_context = dict of apps, models, admin_urls and permissions

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.
contrib.admin.ModelAdmin.change_view 

    """
# Let the ModelAdmin resume normal operations with its own template
    self.change_form_template = None
# queryset of m2m records from the 'through' table
ingredients = Substance_Ingredients.objects.filter(substance_id=object_id)
subscription = None
for sm2mi in ingredients:
# sm2mi.fee_payable() is the detector which triggers the process
payable, fee_type = sm2mi.fee_payable()  # eg., True, PAID_DATA
if payable:
# generate a subscription record with blank token field or
# if one exists with a non-blank token, return None
subscription = billing_subscribe(sm2mi, fee_type)
if subscription:# collect money for the owner
    # switch the ModelAdmin to the new template
self.change_form_template = 'payment.html'
# assemble all the necessary data for the view
context = billing_collect_context(
sm2mi,
subscription,
)
# get everything into the payment_view context
if not extra_context:
extra_context = dict()
extra_context.update(self.admin_site.each_context(request))
extra_context.update(context)
# wrap the view to protect it with Admin permissions
self.admin_site.admin_view(
# call the view with request and context
billing_payment_view(
request,
sm2mi,
subscription,
context=extra_context,
)
)
# only one sm2mi at a time
break
return super(SubstanceAdmin, self).change_view(
request, object_id, form_url, extra_context
)



 
7. Call super in the model save() method *or* raise an exception to
prevent saving. I'm actually not sure about this bit. It may go
against the Django flow. However, I do use a BusinessRuleViolation
exception which inherits from ValidationError and therefore lets me
include a human readable message which appears in the Admin and
*seems* to prevent saving. You would need to test this especially
with m2m side-effects and atomicity consequences.

I 

Re: How to override the ModelAdmin "change" form ?

2019-02-28 Thread Nelson Varela
You maybe want a model admin view where you can send the user to and 
collect the data you want to comare and show warnings

-- 
You received this message because you are subscribed to the Google Groups 
"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/2b4e6166-2f8a-40f0-9f0d-a5c7c8df494e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to override the ModelAdmin "change" form ?

2019-02-28 Thread karim . atiki
Hi,

I'm currently struggling with a custom ModelAdmin.

Considering the following model:


# Bloc fonctionnel
class Assembly(Item):

product = models.ForeignKey(to='ProductFamily', on_delete=models.CASCADE
, null=True, verbose_name=_('Famille Produit'))
functions = models.ManyToManyField(Function, verbose_name=_('Fonctions'
))
*performances* = models.ManyToManyField(Performance, verbose_name=_(
'Performances'), related_name='performances')

def _get_type(self):
return ItemType.ASSEMBLY

class Meta:
verbose_name = _('Bloc Fonctionnel')
verbose_name_plural = _('Blocs Fonctionnels')



I have a custom AssemblyAdmin related to it and also a custom AssemblyForm 
for customizing some fieds.

The *performances* m2m field is critical.  
The performances are captured in the form with a dynamic_raw_id field, 
which works fine.

But when this field is modified, some updates/deletions might be applied in 
other tables of the database.
For this purpose, I need to collect the "performance" pk captured in the 
html form and compare them with those currently in the database.

Basically, when the user clicks on the regular "Save" or "Save and 
continue" button, I would need to display an alert form (like when you 
click on the delete button) to explain what would happen.

I struggled with some ajax routines but it does not work as expected. 

I don't know if it's really doable and how to achieve it.

Any suggestion is welcome.

Cheers.

Z.







-- 
You received this message because you are subscribed to the Google Groups 
"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/88135218-a965-46c8-a454-c0376a5682f1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django ModelAdmin ignores has_delete_permission

2018-05-19 Thread Daniel Germano Travieso
Hello!

Ordinary staff users on the main django admin module are just standard 
django users that can access the admin site.

Setting the has_add_permission, has_change_permission and 
has_delete_permission via the ModelAdmin should be done to customize the 
permissions for specific object instances (as stated on the documentation 
https://docs.djangoproject.com/en/1.11/topics/auth/default/#topic-authorization 
)

The propper way to set the default permissions for a ordinary staff user 
should be either by assigning user/group permissions via 
- the superuser user on the admin site 
- via command line using the myuser.user_permissions.set([permission_list]) 
or myuser.user_permissions.add() or .remove() or using 
myuser.groups.set([group_list]) and myuser.groups.add(group1, group2) / 
.remove(group1, group2).
- programatically on specific staff user creation, using the same methods 
as the above

Either option should give the staff user the propper permissions to a 
specific model. The default permissions for a specific model always are 
named, for a app with app_label foo, as follows: foo.add_bar, 
foo.change_bar and foo.delete_bar where bar is the lowercase name for the 
specific model.

I encourage you to read on the Official Django Documentation for the topic 
of authorization as it provides these and other insights.

Hope it helps!

On Friday, May 18, 2018 at 4:36:07 AM UTC-3, Vitaly Trifanov wrote:
>
> I have simple project on Django 1.11.13, that uses ordinary Django's admin 
> module. Staff user can not delete object while is permitted 
> (has_delete_permission returns always true).
>
> models.py:
>
>
> class MyModel(models.Model):
> name = models.IntegerField("Value", blank=True, null=True)
>
> admin.py:
>
>
> @admin.register(MyModel)class MyModelAdmin(admin.ModelAdmin):
> def has_add_permission(self, request):
> return True
>
> def has_change_permission(self, request, obj=None):
> return True
>
> def has_delete_permission(self, request, obj=None):
> return True
>
>
> I created user and logged in. He can create MyModel object (as expected), 
> can edit (as expected), but can not delete!!
>
> That's what I see if I try to delete it:
>
> Deleting the selected my model would result in deleting related objects, 
> but your account doesn't have permission to delete the following types of 
> objects:
>
> my model
>
> What am I doing wrong? How should I give permissions to delete MyModels to 
> ordinary staff user?
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/35bafb48-34c8-418a-9f70-10dbb6f54868%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django ModelAdmin ignores has_delete_permission

2018-05-18 Thread Vitaly Trifanov


I have simple project on Django 1.11.13, that uses ordinary Django's admin 
module. Staff user can not delete object while is permitted 
(has_delete_permission returns always true).

models.py:


class MyModel(models.Model):
name = models.IntegerField("Value", blank=True, null=True)

admin.py:


@admin.register(MyModel)class MyModelAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return True

def has_change_permission(self, request, obj=None):
return True

def has_delete_permission(self, request, obj=None):
return True


I created user and logged in. He can create MyModel object (as expected), 
can edit (as expected), but can not delete!!

That's what I see if I try to delete it:

Deleting the selected my model would result in deleting related objects, 
but your account doesn't have permission to delete the following types of 
objects:

my model

What am I doing wrong? How should I give permissions to delete MyModels to 
ordinary staff user?

-- 
You received this message because you are subscribed to the Google Groups 
"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/f2a89d70-b488-4584-8fad-0d5b7a5d20e5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Add extra fields to a ModelAdmin form

2018-05-05 Thread Mark Phillips
James,

I was finally able to add extra fields to a ModelForm dynamically! Check
out the answer to this post -
https://stackoverflow.com/questions/32335349/how-do-i-create-and-save-dynamic-fields-in-django-modeladmin

It worked for me in django 2. I have not tried it in django 1.11.

I hope this help!

Mark

On Wed, May 2, 2018 at 9:12 AM, 'James Foley' via Django users <
django-users@googlegroups.com> wrote:

> Hey Mark,
>
> I've not actually found a solution yet, I've just sort of put it at the
> bottom of my pile of problems...
>
> Here is the post that I used to get where I am https://stackoverflow.com/
> a/35797311/3173119
>
> It just doesn't feel very Django like, and I feel that there must be an
> easier way to simply add a non-model field to a model admin form. My fields
> are also added at run time which is whats causing me issues.
>
> My actual goal is to convert a flat JSON string stored in a JSON field,
> into fields for each key. Then once saved it coverts them all back into a
> JSON string and stored them back on the one JSON field.
>
> James.
>
> On Wednesday, 2 May 2018 16:02:51 UTC+1, mark wrote:
>>
>> James,
>>
>> Did you ever get a response to this issue? I am having a devil of a time
>> adding some extra non-model fields to an admin inline form. My added
>> complication is that the fields are only defined at run time, so I have to
>> have a loop that creates them based on a different model in my app.
>>
>> Would you be willing to share your code with me? In particular, I am not
>> sure where and how you are using self.form.declared_fields.
>>
>> I am running django 1.11.
>>
>> Thanks!
>>
>> Mark
>>
>> On Mon, Apr 30, 2018 at 1:41 AM, 'James Foley' via Django users <
>> django...@googlegroups.com> wrote:
>>
>>> So, I have a ModelAdmin that I need to add extra fields to. These fields
>>> do not exist on the model, but will be dynamically added to a custom
>>> ModelForm through the __init__ method, and logic inside clean will handle
>>> the returned data on save.
>>>
>>> I can't seem to find any solid information related to adding custom
>>> non-model fields to a ModelAdmin form. The closest I have come is by
>>> overriding get_fields on the ModelAdmin class and updating
>>> self.form.declared_fields with the new fields I'd like to add.
>>>
>>> This just doesn't feel very clean to me and I was curious if there was a
>>> better way to add new fields to a ModelAdmin dynamically?
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>> To post to this group, send email to django...@googlegroups.com.
>>> Visit this group at https://groups.google.com/group/django-users.
>>> To view this discussion on the web visit https://groups.google.com/d/ms
>>> gid/django-users/a590e54f-1f36-497b-b508-cba339c5f2fc%40googlegroups.com
>>> <https://groups.google.com/d/msgid/django-users/a590e54f-1f36-497b-b508-cba339c5f2fc%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/9889680c-d447-4217-bc37-fc394772b512%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/9889680c-d447-4217-bc37-fc394772b512%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/CAEqej2Oac8tc2Nv7ozE4eV6p%3DF5%3DagPhSaExxtGqQXwoEXZeDw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Admin site and ModelAdmin

2018-05-04 Thread Mike Dewhirst

On 4/05/2018 7:02 AM, jt.oldn...@gmail.com wrote:

Thanks for the response Mike.

I generally don't like it when a design has to change to fit a framework,


I agree. My design is almost entirely in the models. I want an API to be 
able to work without Django forms.


however, in this case I decided to try your solution. I ran into a 
couple of problems though :-(
 1) The fields that I'm looking up were required fields. Validation 
failed and error messages were displayed until I changed my model to 
not require those fields (which creates other problems I'd need to 
fix). Is there a way to hook in before validation?


Maybe but not in the model. I think you should be able to intercept form 
validation. But see below.


I over-road the model save function. Would the pre-save signal method 
fix this problem?

No

Or maybe ModelAdmin.save_model?

Don't know. Possibly.

Django forms automatically do all the python-wise cleaning of data prior 
to the model's save() being called by the form If you are putting data 
independently from the form into fields inside the save() method (or via 
a pre_save hook) you have to be certain it is valid data.


I might be wrong but I don't think there is any effective difference 
between pre and post save signals and my approach. Maybe transaction 
management. Maybe not. This is my exact substance.save() method ...


    def save(self, *args, **kwargs):
    links = self._pre_save()
    super(Substance, self).save(*args, **kwargs)
    self._post_save(links)
    self._post_post_save()

Stuff which occurs in _pre_save() happens before the record is saved to 
the database. For example, the record may not yet have a primary key 
because it is new and hasn't ever been saved to the database. Stuff in 
_post_save() and _post_post_save() happens afterwards. I use those to 
create related records if required because by then (under normal circs) 
I can guarantee self.id is no longer null.


The last thing which happens prior to save() is the model's clean() 
method (if it exists) is called by the form. I put checks in there to be 
certain data in whatever fields I care deeply about is valid and raise a 
ValidationError if not. If that happens, the save() is aborted and the 
user has to fix the problem before trying again. Here is an example ...


    def clean(self):
    if self.physical_state is None:
    raise ValidationError('Physical form is required')

If you are getting external data you have no choice but to be certain it 
is good data. You need to validate it Python-wise en route to the 
destination model fields, perhaps in _pre_save() and business-rule-wise 
in Employee.clean()


The actual validation checks can be factored out and called from clean() 
or anywhere else such as save().


The actual sequence of events (form calls model.clean() before 
model.save()) indicates to me that Employee.clean() ought to be able to 
insert (clean) data into Employee fields before running its own business 
rule validation. However, whenever I have tried this I haven't been 
successful. Therefore I'm missing something. Maybe transaction 
management. Maybe someone can enlighten me?


A side note is that if you are not using a form, clean() does not get 
called. This matters for unit testing where there is no form. You have 
to deliberately call clean() to get the benefit of any checks.


 2) The desired result of the lookup would be to display the change 
form so that the information could be verified.


Sorry but that implies javascript and an API to fetch the data for 
verification if you want to do it all at once.


OTOH maybe you could save the Employee model without the external data 
and use a separate 1:1 model to carry it. That could be fetched 
separately after the Emplyee.save() has run. In my scenario it would be 
fetched in the _post_save() method and verified python-wise in there 
before adding the 1:1 model if it didn't already exist. The Employee 
would need to be saved again so the 1:1 model gets saved. The 1:1 model 
could check the business rule logic in its clean() method. Maybe the 
advantage here would be splitting the activity into separate atomic 
transactions and a 1:1 model validation error wouldn't interrupt the 
preceding Employee.save()


In other words, if doing the lookup, 'SAVE' (and 'Save and add 
another') should behave as if 'Save and continue editing' had been 
selected.


There is no save/clean difference between any of those. Just what 
happens next in the Admin.





--
You received this message because you are subscribed to the Google 
Groups "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 

Re: Admin site and ModelAdmin

2018-05-03 Thread jt . oldnews
Thanks for the response Mike.

I generally don't like it when a design has to change to fit a framework, 
however, in this case I decided to try your solution. I ran into a couple 
of problems though :-(
 1) The fields that I'm looking up were required fields. Validation failed 
and error messages were displayed until I changed my model to not require 
those fields (which creates other problems I'd need to fix). Is there a way 
to hook in before validation? I over-road the model save function. Would 
the pre-save signal method fix this problem? Or maybe ModelAdmin.save_model?
 2) The desired result of the lookup would be to display the change form so 
that the information could be verified. In other words, if doing the 
lookup, 'SAVE' (and 'Save and add another') should behave as if 'Save and 
continue editing' had been selected.


-- 
You received this message because you are subscribed to the Google Groups 
"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/26f88b4c-b2dd-4bce-aea7-d885295aa609%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Admin site and ModelAdmin

2018-05-02 Thread Mike Dewhirst

On 3/05/2018 10:33 AM, Mike Dewhirst wrote:

On 3/05/2018 7:00 AM, jt.oldn...@gmail.com wrote:
I'm new to Django and web development in general (C++ background) and 
I've got amazingly far very quickly, but there's one thing I've been 
struggling with for a couple days now :-(. Forgive me if I screw up 
the lingo.


I've got a ModelAdmin page for registrants of a conference which has 
fields for Employee ID, Name, email etc. The registrant does not have 
to be an employee, but if they are I could lookup their name, email 
etc. from an external source (already have the Python code for this). 
I'd like to have a button next to the employee id field which would 
lookup the employee's details and fill in the appropriate fields. 
This seems to me that it shouldn't be too hard but I am spinning my 
wheels here.  Do I need to ditch ModelAdmin?  Can someone please 
point me in the right direction.


You may not need a button which, in the Admin, implies javascript and 
an API. In your model you can intercept the save() method to visit 
another database/system to fetch the detail before the record is 
saved. There are probably many ways to do this. One uses a pre-save 
signal [1] but I prefer to override save() [2].


class Employee(models.Model):

    ... all the fields etc

    fetchdata = models.BooleanField(default=False, blank=True)

    def save(self, *args, **kwargs):
    if self.fetchdata:
    self.fetchdata = False
            try:
        self.this, self.that = self.fetch_data()
    except Exception:
    # avoid losing other changes
    pass

 super(Employee, self).save(*args, **kwargs)

Sorry - should have read what I pasted in


super(Substance, self).save(*args, **kwargs)

    def fetch_data(self):
        #call external database with employee ID and return necessary 
detail

    return this, that

[1] https://docs.djangoproject.com/en/1.11/ref/signals/#pre-save
[2] 
https://docs.djangoproject.com/en/2.0/ref/models/instances/#saving-objects


hth



Thanks,
JT
--
You received this message because you are subscribed to the Google 
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/1324e38c-ed15-4f3c-8e1e-cd7df220b96e%40googlegroups.com 
<https://groups.google.com/d/msgid/django-users/1324e38c-ed15-4f3c-8e1e-cd7df220b96e%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/88249111-78d2-5076-0ea9-b0cb5d5d5ae6%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Re: Admin site and ModelAdmin

2018-05-02 Thread Mike Dewhirst

On 3/05/2018 7:00 AM, jt.oldn...@gmail.com wrote:
I'm new to Django and web development in general (C++ background) and 
I've got amazingly far very quickly, but there's one thing I've been 
struggling with for a couple days now :-(. Forgive me if I screw up 
the lingo.


I've got a ModelAdmin page for registrants of a conference which has 
fields for Employee ID, Name, email etc. The registrant does not have 
to be an employee, but if they are I could lookup their name, email 
etc. from an external source (already have the Python code for this). 
I'd like to have a button next to the employee id field which would 
lookup the employee's details and fill in the appropriate fields. This 
seems to me that it shouldn't be too hard but I am spinning my wheels 
here.  Do I need to ditch ModelAdmin?  Can someone please point me in 
the right direction.


You may not need a button which, in the Admin, implies javascript and an 
API. In your model you can intercept the save() method to visit another 
database/system to fetch the detail before the record is saved. There 
are probably many ways to do this. One uses a pre-save signal [1] but I 
prefer to override save() [2].


class Employee(models.Model):

    ... all the fields etc

    fetchdata = models.BooleanField(default=False, blank=True)

    def save(self, *args, **kwargs):
    if self.fetchdata:
    self.fetchdata = False
            try:
        self.this, self.that = self.fetch_data()
    except Exception:
    # avoid losing other changes
    pass
    super(Substance, self).save(*args, **kwargs)

    def fetch_data(self):
        #call external database with employee ID and return necessary 
detail

    return this, that

[1] https://docs.djangoproject.com/en/1.11/ref/signals/#pre-save
[2] 
https://docs.djangoproject.com/en/2.0/ref/models/instances/#saving-objects


hth



Thanks,
JT
--
You received this message because you are subscribed to the Google 
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/1324e38c-ed15-4f3c-8e1e-cd7df220b96e%40googlegroups.com 
<https://groups.google.com/d/msgid/django-users/1324e38c-ed15-4f3c-8e1e-cd7df220b96e%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/add76f8e-b999-e9df-be5f-01bd2de26c3f%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Admin site and ModelAdmin

2018-05-02 Thread jt . oldnews
I'm new to Django and web development in general (C++ background) and I've 
got amazingly far very quickly, but there's one thing I've been struggling 
with for a couple days now :-(. Forgive me if I screw up the lingo.

I've got a ModelAdmin page for registrants of a conference which has fields 
for Employee ID, Name, email etc. The registrant does not have to be an 
employee, but if they are I could lookup their name, email etc. from an 
external source (already have the Python code for this). I'd like to have a 
button next to the employee id field which would lookup the employee's 
details and fill in the appropriate fields. This seems to me that it 
shouldn't be too hard but I am spinning my wheels here.  Do I need to ditch 
ModelAdmin?  Can someone please point me in the right direction.

Thanks,
JT

-- 
You received this message because you are subscribed to the Google Groups 
"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/1324e38c-ed15-4f3c-8e1e-cd7df220b96e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Add extra fields to a ModelAdmin form

2018-05-02 Thread 'James Foley' via Django users
Hey Mark,

I've not actually found a solution yet, I've just sort of put it at the 
bottom of my pile of problems...

Here is the post that I used to get where I 
am https://stackoverflow.com/a/35797311/3173119

It just doesn't feel very Django like, and I feel that there must be an 
easier way to simply add a non-model field to a model admin form. My fields 
are also added at run time which is whats causing me issues.

My actual goal is to convert a flat JSON string stored in a JSON field, 
into fields for each key. Then once saved it coverts them all back into a 
JSON string and stored them back on the one JSON field.

James.

On Wednesday, 2 May 2018 16:02:51 UTC+1, mark wrote:
>
> James,
>
> Did you ever get a response to this issue? I am having a devil of a time 
> adding some extra non-model fields to an admin inline form. My added 
> complication is that the fields are only defined at run time, so I have to 
> have a loop that creates them based on a different model in my app. 
>
> Would you be willing to share your code with me? In particular, I am not 
> sure where and how you are using self.form.declared_fields. 
>
> I am running django 1.11.
>
> Thanks!
>
> Mark
>
> On Mon, Apr 30, 2018 at 1:41 AM, 'James Foley' via Django users <
> django...@googlegroups.com > wrote:
>
>> So, I have a ModelAdmin that I need to add extra fields to. These fields 
>> do not exist on the model, but will be dynamically added to a custom 
>> ModelForm through the __init__ method, and logic inside clean will handle 
>> the returned data on save.
>>
>> I can't seem to find any solid information related to adding custom 
>> non-model fields to a ModelAdmin form. The closest I have come is by 
>> overriding get_fields on the ModelAdmin class and updating 
>> self.form.declared_fields with the new fields I'd like to add. 
>>
>> This just doesn't feel very clean to me and I was curious if there was a 
>> better way to add new fields to a ModelAdmin dynamically?
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/a590e54f-1f36-497b-b508-cba339c5f2fc%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/a590e54f-1f36-497b-b508-cba339c5f2fc%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/9889680c-d447-4217-bc37-fc394772b512%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Add extra fields to a ModelAdmin form

2018-05-02 Thread Mark Phillips
James,

Did you ever get a response to this issue? I am having a devil of a time
adding some extra non-model fields to an admin inline form. My added
complication is that the fields are only defined at run time, so I have to
have a loop that creates them based on a different model in my app.

Would you be willing to share your code with me? In particular, I am not
sure where and how you are using self.form.declared_fields.

I am running django 1.11.

Thanks!

Mark

On Mon, Apr 30, 2018 at 1:41 AM, 'James Foley' via Django users <
django-users@googlegroups.com> wrote:

> So, I have a ModelAdmin that I need to add extra fields to. These fields
> do not exist on the model, but will be dynamically added to a custom
> ModelForm through the __init__ method, and logic inside clean will handle
> the returned data on save.
>
> I can't seem to find any solid information related to adding custom
> non-model fields to a ModelAdmin form. The closest I have come is by
> overriding get_fields on the ModelAdmin class and updating
> self.form.declared_fields with the new fields I'd like to add.
>
> This just doesn't feel very clean to me and I was curious if there was a
> better way to add new fields to a ModelAdmin dynamically?
>
> --
> You received this message because you are subscribed to the Google Groups
> "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/a590e54f-1f36-497b-b508-cba339c5f2fc%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/a590e54f-1f36-497b-b508-cba339c5f2fc%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/CAEqej2NFGCaTbL2%3Dp8mBGbQfYGqjM4RbRYE5WOxK90zZL-ArsA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Add extra fields to a ModelAdmin form

2018-04-30 Thread 'James Foley' via Django users
So, I have a ModelAdmin that I need to add extra fields to. These fields do 
not exist on the model, but will be dynamically added to a custom ModelForm 
through the __init__ method, and logic inside clean will handle the 
returned data on save.

I can't seem to find any solid information related to adding custom 
non-model fields to a ModelAdmin form. The closest I have come is by 
overriding get_fields on the ModelAdmin class and updating 
self.form.declared_fields with the new fields I'd like to add. 

This just doesn't feel very clean to me and I was curious if there was a 
better way to add new fields to a ModelAdmin dynamically?

-- 
You received this message because you are subscribed to the Google Groups 
"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/a590e54f-1f36-497b-b508-cba339c5f2fc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to get ModelAdmin given a Model

2018-01-04 Thread Edouard C.

'type(v)' is model..instead of 'v is model' works,
in case not too late for someone else...
thanks Matt..

def get_admin(model):
for k,v in admin.site._registry.iteritems():

if type(v) is model:
return v


On Monday, January 11, 2010 at 9:37:47 PM UTC, Matt Schinckel wrote:
>
> On Jan 12, 4:11 am, Tomasz Zieliński
> <tomasz.zielin...@pyconsultant.eu> wrote:
> > On 11 Sty, 16:23, Marco Rogers <marco.rog...@gmail.com> wrote:
> >
> > > I'm reposting this from earlier to see if I have better luck. I need
> > > to be able to get the ModelAdmin associated with a model at runtime.
> > > Similar to how django.db.models.get_model allows you to retrieve a
> > > model.
> >
> > > admin_class = get_admin(Model)
> >
> > > Is this possible?
> >
> > > The original post has more info.
> >
> > >http://groups.google.com/group/django-users/browse_thread/thread/0cd0.
> ..
> >
> > Maybe something like this:
> >
> > 1. Write something like django.contrib.admin.autodiscover, to get all
> > ModelAdmins
> > 2. Iterate those ModelAdmins, retrieve models they are attached to and
> > store this mapping in a dict.
> > 3. def get_admin(model):
> > return admin_to_model[model]
>
> You should be able to iterate through admin.site._registry, and pull
> out the one you need.
>
> from django.contrib import admin
> def get_admin(model):
> for k,v in admin.site._registry.iteritems():
> if v is model:
> return v
>
> Written in a browser.
>
> Matt.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/8f5d1af4-3792-44f6-b8a4-f0fc1dbf8b6d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin Media JS file order issue in Django 2.0

2017-12-10 Thread Andréas Kühne
Checking through the documents I found the following reference:

https://docs.djangoproject.com/en/2.0/topics/forms/media/#order-of-assets

Changed in Django 2.0:

In older versions, the assets of Media objects are concatenated rather than
merged in a way that tries to preserve the relative ordering of the
elements in each list.


I'm guessing that this is your problem.

>From what I understand in this context, the:

**
import seems to be added in a previous dependent form and therefore is not
added again - you should probably check if the file is added somewhere else?

Best regards,

Andréas

2017-12-10 15:47 GMT+01:00 Marc R :

> because they are specific to only a few models, particularly the loading
> scripts, and options, etc.  this worked great in Django 1.11
>
>
> On Sunday, 10 December 2017 09:36:56 UTC-5, Etienne Robillard wrote:
>
>> Why don't you simply put the javascripts into your base template without
>> using Python ?
>>
>> Etienne
>>
>> Le 2017-12-10 à 09:30, Marc R a écrit :
>>
>> I have this in my model:
>>
>> class Media:
>> js = (
>>* '/static/plugins/codemirror/lib/codemirror.js',*
>> '/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
>> '/static/plugins/codemirror/addon/fold/foldcode.js',
>> '/static/plugins/codemirror/addon/fold/foldgutter.js',
>> '/static/plugins/codemirror/addon/fold/brace-fold.js',
>> '/static/plugins/codemirror/addon/fold/indent-fold.js',
>> '/static/plugins/codemirror/addon/fold/comment-fold.js',
>> '/static/plugins/codemirror/addon/fold/xml-fold.js',
>> '/static/plugins/codemirror/addon/comment/comment.js',
>> '/static/plugins/codemirror/addon/edit/matchbrackets.js',
>> '/static/plugins/codemirror/addon/edit/matchtags.js',
>> '/static/plugins/codemirror/mode/javascript/javascript.js',
>> '/static/plugins/codemirror/mode/xml/xml.js',
>> '/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
>> '/static/plugins/codemirror/addon/display/fullscreen.js',
>> '/static/js/admin/syslog/syslog_change_form.min.js'
>> )
>>
>> which used to work as it was included in the model admin page in the
>> order it appears. However, now in Django 2.0, it appears in this order:
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> 
>> *> src="/static/plugins/codemirror/lib/codemirror.js">*
>> 
>> 
>> 
>>
>> The issue is that the First file MUST be first as the remainder rely upon
>> it!  I'd rather not override a template file as if i change the admin
>> backend with a package i'd like this to "just work" as it did in Django 1.11
>> Is this a bug in the new way that Django includes these files (docs say
>> they made a change in how this is done, clearly it broke something that
>> worked!).
>>
>> Thanks
>>
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users...@googlegroups.com.
>> To post to this group, send email to django...@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit https://groups.google.com/d/ms
>> gid/django-users/5ad93160-05c2-4251-84ad-6f8a1574b675%40googlegroups.com
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>>
>> --
>> Etienne Robillardtka...@yandex.comhttps://www.isotopesoftware.ca/
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "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/8493b435-1574-4187-88f6-7f45f5dbaba6%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/CAK4qSCfTd0BBjYQsovHPx%2BS40U_dA1RA%3DYDNtBdYS3GJJFbKpA%40mail.gmail.com.
For more options, visit 

Re: ModelAdmin Media JS file order issue in Django 2.0

2017-12-10 Thread Marc R
because they are specific to only a few models, particularly the loading 
scripts, and options, etc.  this worked great in Django 1.11

On Sunday, 10 December 2017 09:36:56 UTC-5, Etienne Robillard wrote:
>
> Why don't you simply put the javascripts into your base template without 
> using Python ? 
>
> Etienne
>
> Le 2017-12-10 à 09:30, Marc R a écrit :
>
> I have this in my model: 
>
> class Media:
> js = (
>* '/static/plugins/codemirror/lib/codemirror.js',*
> '/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
> '/static/plugins/codemirror/addon/fold/foldcode.js',
> '/static/plugins/codemirror/addon/fold/foldgutter.js',
> '/static/plugins/codemirror/addon/fold/brace-fold.js',
> '/static/plugins/codemirror/addon/fold/indent-fold.js',
> '/static/plugins/codemirror/addon/fold/comment-fold.js',
> '/static/plugins/codemirror/addon/fold/xml-fold.js',
> '/static/plugins/codemirror/addon/comment/comment.js',
> '/static/plugins/codemirror/addon/edit/matchbrackets.js',
> '/static/plugins/codemirror/addon/edit/matchtags.js',
> '/static/plugins/codemirror/mode/javascript/javascript.js',
> '/static/plugins/codemirror/mode/xml/xml.js',
> '/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
> '/static/plugins/codemirror/addon/display/fullscreen.js',
> '/static/js/admin/syslog/syslog_change_form.min.js'
> )
>
> which used to work as it was included in the model admin page in the order 
> it appears. However, now in Django 2.0, it appears in this order:
>  src="/static/plugins/codemirror/addon/fold/foldcode.js">
>  src="/static/plugins/codemirror/addon/fold/foldgutter.js">
>  src="/static/plugins/codemirror/addon/fold/brace-fold.js">
>  src="/static/plugins/codemirror/addon/fold/indent-fold.js">
>  src="/static/plugins/codemirror/addon/fold/comment-fold.js">
>  src="/static/plugins/codemirror/addon/fold/xml-fold.js">
>  src="/static/plugins/codemirror/addon/comment/comment.js">
>  src="/static/plugins/codemirror/addon/edit/matchbrackets.js">
>  src="/static/plugins/codemirror/addon/edit/matchtags.js">
>  src="/static/plugins/codemirror/mode/javascript/javascript.js">
>  src="/static/plugins/codemirror/mode/xml/xml.js">
> * src="/static/plugins/codemirror/lib/codemirror.js">*
>  src="/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js">
>  src="/static/plugins/codemirror/addon/display/fullscreen.js">
>  src="/static/js/admin/syslog/syslog_change_form.min.js">
>
> The issue is that the First file MUST be first as the remainder rely upon 
> it!  I'd rather not override a template file as if i change the admin 
> backend with a package i'd like this to "just work" as it did in Django 1.11
> Is this a bug in the new way that Django includes these files (docs say 
> they made a change in how this is done, clearly it broke something that 
> worked!).
>
> Thanks
>
>
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users...@googlegroups.com .
> To post to this group, send email to django...@googlegroups.com 
> .
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/5ad93160-05c2-4251-84ad-6f8a1574b675%40googlegroups.com
>  
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>
>
> -- 
> Etienne robillardtka...@yandex.com 
> https://www.isotopesoftware.ca/
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/8493b435-1574-4187-88f6-7f45f5dbaba6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin Media JS file order issue in Django 2.0

2017-12-10 Thread Etienne Robillard
Why don't you simply put the javascripts into your base template without 
using Python ?


Etienne


Le 2017-12-10 à 09:30, Marc R a écrit :

I have this in my model:

class Media:
        js = (
*'/static/plugins/codemirror/lib/codemirror.js',*
'/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
'/static/plugins/codemirror/addon/fold/foldcode.js',
'/static/plugins/codemirror/addon/fold/foldgutter.js',
'/static/plugins/codemirror/addon/fold/brace-fold.js',
'/static/plugins/codemirror/addon/fold/indent-fold.js',
'/static/plugins/codemirror/addon/fold/comment-fold.js',
'/static/plugins/codemirror/addon/fold/xml-fold.js',
'/static/plugins/codemirror/addon/comment/comment.js',
'/static/plugins/codemirror/addon/edit/matchbrackets.js',
'/static/plugins/codemirror/addon/edit/matchtags.js',
'/static/plugins/codemirror/mode/javascript/javascript.js',
            '/static/plugins/codemirror/mode/xml/xml.js',
'/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
'/static/plugins/codemirror/addon/display/fullscreen.js',
'/static/js/admin/syslog/syslog_change_form.min.js'
        )

which used to work as it was included in the model admin page in the 
order it appears. However, now in Django 2.0, it appears in this order:
src="/static/plugins/codemirror/addon/fold/foldcode.js">
src="/static/plugins/codemirror/addon/fold/foldgutter.js">
src="/static/plugins/codemirror/addon/fold/brace-fold.js">
src="/static/plugins/codemirror/addon/fold/indent-fold.js">
src="/static/plugins/codemirror/addon/fold/comment-fold.js">
src="/static/plugins/codemirror/addon/fold/xml-fold.js">
src="/static/plugins/codemirror/addon/comment/comment.js">
src="/static/plugins/codemirror/addon/edit/matchbrackets.js">
src="/static/plugins/codemirror/addon/edit/matchtags.js">
src="/static/plugins/codemirror/mode/javascript/javascript.js">
src="/static/plugins/codemirror/mode/xml/xml.js">
*src="/static/plugins/codemirror/lib/codemirror.js">*
src="/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js">
src="/static/plugins/codemirror/addon/display/fullscreen.js">
src="/static/js/admin/syslog/syslog_change_form.min.js">


The issue is that the First file MUST be first as the remainder rely 
upon it!  I'd rather not override a template file as if i change the 
admin backend with a package i'd like this to "just work" as it did in 
Django 1.11
Is this a bug in the new way that Django includes these files (docs 
say they made a change in how this is done, clearly it broke something 
that worked!).


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/5ad93160-05c2-4251-84ad-6f8a1574b675%40googlegroups.com 
.

For more options, visit https://groups.google.com/d/optout.


--
Etienne Robillard
tkad...@yandex.com
https://www.isotopesoftware.ca/

--
You received this message because you are subscribed to the Google Groups "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/36e6755b-ed27-9a77-9bdd-77a9bd4bf429%40yandex.com.
For more options, visit https://groups.google.com/d/optout.


ModelAdmin Media JS file order issue in Django 2.0

I have this in my model:

class Media:
js = (
   * '/static/plugins/codemirror/lib/codemirror.js',*
'/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
'/static/plugins/codemirror/addon/fold/foldcode.js',
'/static/plugins/codemirror/addon/fold/foldgutter.js',
'/static/plugins/codemirror/addon/fold/brace-fold.js',
'/static/plugins/codemirror/addon/fold/indent-fold.js',
'/static/plugins/codemirror/addon/fold/comment-fold.js',
'/static/plugins/codemirror/addon/fold/xml-fold.js',
'/static/plugins/codemirror/addon/comment/comment.js',
'/static/plugins/codemirror/addon/edit/matchbrackets.js',
'/static/plugins/codemirror/addon/edit/matchtags.js',
'/static/plugins/codemirror/mode/javascript/javascript.js',
'/static/plugins/codemirror/mode/xml/xml.js',
'/static/plugins/codemirror/mode/htmlmixed/htmlmixed.js',
'/static/plugins/codemirror/addon/display/fullscreen.js',
'/static/js/admin/syslog/syslog_change_form.min.js'
)

which used to work as it was included in the model admin page in the order 
it appears. However, now in Django 2.0, it appears in this order:











**




The issue is that the First file MUST be first as the remainder rely upon 
it!  I'd rather not override a template file as if i change the admin 
backend with a package i'd like this to "just work" as it did in Django 1.11
Is this a bug in the new way that Django includes these files (docs say 
they made a change in how this is done, clearly it broke something that 
worked!).

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/5ad93160-05c2-4251-84ad-6f8a1574b675%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to combine change_list_template in ModelAdmin mixin


I would like to create a mixin to extend the ModelAdmin class that adds a 
description text to the view, overriding the default change_list_template.

[admin_extra.py]
class DescriptionAdminMixin(object)
change_list_template = "description_change_list.html"
...

def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context.update({
'description': self.description,
})
return super(DescriptionAdminMixin, self).changelist_view(request, 
extra_context=extra_context)

[description_change_list.html]
{% extends "admin/change_list.html" %}
{% block object-tools %}
{% block description %}
{% if description %}{{ description }}{% endif %}
{% endblock description %}
{{ block.super }}
{% endblock %}


This works fine if used on a ModelAdmin, but it fails if used on an already 
subclassed ModelAdmin that also defines change_list_template, as it gets 
overwritten.


Ex. adding django-import-export mixin:

class MyModelAdmin(DescriptionAdminMixin, ExportMixin, ModelAdmin): 
...

where ExportMixin is defined as:

class ExportMixin(ImportExportMixinBase):
...
change_list_template = 'admin/import_export/change_list_export.html'
...

Is there a preferred way to combine both templates?


The solution I use for now is defining a parent_template in the context, 
and use that in the template to extend from it

[admin_extra.py]
class DescriptionAdminMixin(object)
change_list_template = "description_change_list.
...
def changelist_view(self, request, extra_context=None):
# Define parent object template, or use the default admin change 
list template
opts = self.model._meta
app_label = opts.app_label
parent_template_list = super(DescriptionAdminMixin, 
self).change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.model_name),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
]
parent_template = 
SimpleTemplateResponse(None).resolve_template(parent_template_list)

extra_context = extra_context or {}
extra_context.update({
'description': self.description,
'parent_template': parent_template,
})
return super(DescriptionAdminMixin, self).changelist_view(request, 
extra_context=extra_context)

[description_change_list.html]
{% extends parent_template %}
{% block object-tools %}
{% block description %}
{% if description %}{{ description }}{% endif %}
{% endblock description %}
{{ block.super }}
{% endblock %}

Is there any better solution? Is there a way for the AdminObject to provide 
the default template, something like get_change_list_template() to avoid 
doing the template resolution? Or even better some built-in way of getting 
the template of the parent class?



-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+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/62cb6134-cae1-48a0-8938-41604553d07f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

On Sep 16, 2016 1:46 AM, "Andrea D'Amore" <and.dam...@gmail.com> wrote:
>
> On 16 September 2016 at 00:53,  <th...@copperleaf.com> wrote:
> > I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>)
>
> Gives a 404:
>
> The requested URL /0LAt was not found on this server.
>
>
> I'm missing the rationale of using an external paste service while
> you're already using a text-based medium, the mailing list, that's
> able to accomodate what's (hopefully) a small code excerpt, in worst
> case scenario I think it'll accept an attachment as well.
>
> This also has the added bonus of getting archived and never result in
> broken links and missing content, like it's likely to happen at some
> point with external services.
>

(OT Disclaimer...not directed at this OP.)

I would [mostly] disagree.

Rationale: A majority of my responses (including this one) are written on
my phone while I'm bored and out and about, or at night during my pre-bed
email check. While the GMail app is great, I've never seen it employ any
sort of code highlighting or sane code wrapping or indentation, beyond
copying directly out of an SO post or other snippet service. Probably
because the GMail app is an email client, not an IDE. There is also no real
way to preview the effects of spacing and line wrapping on multiple
devices, screen sizes, HTML vs. plain text, Unicode handling, etc.
Basically, there's a bunch of ways a direct paste from an IDE can go
sideways in an email, with an increasing likelihood for large code chunks.
Difficult-to-read code directly in an email will deter responses. It does
for me, anyway.

For small code snippets, absolutely, paste them directly in and just make
sure your indentation is at least consistent. If you have more than a dozen
or so SLOC, though, try and reduce the provided code to the stuff that's
necessary (which will often force an OP to really evaluate what their code
is doing and aid in troubleshooting), or make use of an external service
such as dpaste.de.

Mobile devices cannot always open external files, especially those with
less common extensions such as .py. It also fills up your mailbox,
needlessly. I rarely, if ever, open the attachments sent out to this list.
Trying to keep track of the original question compared with the code in a
separate application screen on a mobile device is nearly impossible.

A majority of the code in this list doesn't need to live forever once the
OP has a proper answer. A response with a summation of the correct solution
is almost always the key piece needed when searching through the archives
or Googling, at least in my experience with this list and other forums.

With that being said, sometimes the OP may not know the exact pieces that
are needed for inspection, or there are multiple files involved, so an
attachment may be necessary. Code snippet services also lack in this area.

IMHO, you hijacked this thread to insert your preference for posts, without
offering a single bit of advice to the OP, which reflects poorly on you. I
would offer advice to the OP, but I have none because I have little
experience using the built-in admin.

I would recommend that you offer suggestions for posting guidelines to the
moderators of this list and/or the Django devs. Help move this community
forward rather than criticising those requesting assistance, especially on
a point of personal preference.

Just my personal opinion; if I'm out of line, someone please let me know.

-James

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


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

Apologies, I updated it.


class MyModelAdmin(ModelAdmin):
model = MyModel
form = MyForm
 
def get_form(self, request, obj=None, **kwargs):
form_class = super(MyModelAdmin, self).get_form(request, obj=obj, 
**kwargs)
 
some_parameter_for_one_thing = 
self.get_some_parameter_for_one_thing()
 
from django.forms.models import ModelFormMetaclass
class FormMetaclass(ModelFormMetaclass):
def __new__(mcs, name, bases, attrs):
attrs["some_parameter_for_one_thing"] = 
some_parameter_for_one_thing
return super(FormMetaclass, mcs).__new__(mcs, name, bases, 
attrs)
 
another_parameter_for_another_thing= 
obj.another_parameter_for_another_thing
 
import six
class FormWrapper(six.with_metaclass(FormMetaclass, form_class)):
def __init__(self, *args, **kwargs):
data = {"another_parameter_for_another_thing": 
six.text_type(another_parameter_for_another_thing)}
super(FormWrapper, self).__init__(data, *args, **kwargs)
 
return FormWrapper

On Friday, September 16, 2016 at 1:46:32 AM UTC-7, Andrea D'Amore wrote:
>
> On 16 September 2016 at 00:53,  <th...@copperleaf.com > 
> wrote: 
> > I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) 
>
> Gives a 404: 
>
> The requested URL /0LAt was not found on this server. 
>
>
> I'm missing the rationale of using an external paste service while 
> you're already using a text-based medium, the mailing list, that's 
> able to accomodate what's (hopefully) a small code excerpt, in worst 
> case scenario I think it'll accept an attachment as well. 
>
> This also has the added bonus of getting archived and never result in 
> broken links and missing content, like it's likely to happen at some 
> point with external services. 
>
>
> -- 
> Andrea 
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/9481df50-3280-4b9d-87c2-080e632a4cda%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

On 16 September 2016 at 00:53,  <th...@copperleaf.com> wrote:
> I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>)

Gives a 404:

The requested URL /0LAt was not found on this server.


I'm missing the rationale of using an external paste service while
you're already using a text-based medium, the mailing list, that's
able to accomodate what's (hopefully) a small code excerpt, in worst
case scenario I think it'll accept an attachment as well.

This also has the added bonus of getting archived and never result in
broken links and missing content, like it's likely to happen at some
point with external services.


-- 
Andrea

-- 
You received this message because you are subscribed to the Google Groups 
"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/CAMonFrQ%2B2JYMPEaOXw-FM2Oj--BxjNNrqsO6isEDgFGf%3DHnd0A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

I just realized that get_form is already passed the model instance as obj, 
so that fixes getting he model instance (for this method at least -- 
hopefully I don't need to override another method that doesn't get obj). 
Still need a better way to customize how a form instance is initialized, 
though...

On Thursday, September 15, 2016 at 6:00:02 PM UTC-7, th...@copperleaf.com 
wrote:
>
> Hi Tim, thanks for the reply :)
>
> It's not that I want to store the model instance on self.instance, it's 
> just the solution I was able to come up with, given the problem "I need to 
> get to the model instance for this HTTP request". If there's a better way 
> to do it, I'm all ears!
>
> T
>
> On Thursday, September 15, 2016 at 5:34:50 PM UTC-7, Tim Graham wrote:
>>
>> I think these ideas have been floated before. If you look through the 
>> Trac tickets you might find something related. However, your subclass where 
>> you store "self.instance" on ModelAdmin is a no no due to thread safety. 
>> See 
>> http://stackoverflow.com/questions/3388111/modeladmin-thread-safety-caching-issues
>>  
>> for an explanation.
>>
>> On Thursday, September 15, 2016 at 6:53:15 PM UTC-4, th...@copperleaf.com 
>> wrote:
>>>
>>> I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) and I 
>>> need to do a couple of things, but the functionality seems to be missing:
>>>
>>> 1. I need to access the model instance to perform some initialization, 
>>> but there's no instance member set. There are a few questions on Stack 
>>> Overflow on this topic, so I know I'm not alone.
>>>
>>> 2. I need to initialize my form with a parameter derived from the model 
>>> instance. If this were a View, I could just override get_form_kwargs and be 
>>> done with it, but ModelAdmin doesn't have it.
>>>
>>> Is there a reason why those two features are missing from ModelAdmin? 
>>> Maybe they could be added (and I could open a PR)? Or is there a better way 
>>> to do what I need to do?
>>>
>>>

-- 
You received this message because you are subscribed to the Google Groups 
"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/2a245d08-91b3-4a16-a3b2-4e172d2cbcb4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

I'm having trouble finding any related tickets other than this one, which 
is 8 years old:

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

On Thursday, September 15, 2016 at 5:34:50 PM UTC-7, Tim Graham wrote:
>
> I think these ideas have been floated before. If you look through the Trac 
> tickets you might find something related. However, your subclass where you 
> store "self.instance" on ModelAdmin is a no no due to thread safety. See 
> http://stackoverflow.com/questions/3388111/modeladmin-thread-safety-caching-issues
>  
> for an explanation.
>
> On Thursday, September 15, 2016 at 6:53:15 PM UTC-4, th...@copperleaf.com 
> wrote:
>>
>> I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) and I 
>> need to do a couple of things, but the functionality seems to be missing:
>>
>> 1. I need to access the model instance to perform some initialization, 
>> but there's no instance member set. There are a few questions on Stack 
>> Overflow on this topic, so I know I'm not alone.
>>
>> 2. I need to initialize my form with a parameter derived from the model 
>> instance. If this were a View, I could just override get_form_kwargs and be 
>> done with it, but ModelAdmin doesn't have it.
>>
>> Is there a reason why those two features are missing from ModelAdmin? 
>> Maybe they could be added (and I could open a PR)? Or is there a better way 
>> to do what I need to do?
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"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/43ace9be-231e-4ae9-bc04-b04b201c4962%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

Hi Tim, thanks for the reply :)

It's not that I want to store the model instance on self.instance, it's 
just the solution I was able to come up with, given the problem "I need to 
get to the model instance for this HTTP request". If there's a better way 
to do it, I'm all ears!

T

On Thursday, September 15, 2016 at 5:34:50 PM UTC-7, Tim Graham wrote:
>
> I think these ideas have been floated before. If you look through the Trac 
> tickets you might find something related. However, your subclass where you 
> store "self.instance" on ModelAdmin is a no no due to thread safety. See 
> http://stackoverflow.com/questions/3388111/modeladmin-thread-safety-caching-issues
>  
> for an explanation.
>
> On Thursday, September 15, 2016 at 6:53:15 PM UTC-4, th...@copperleaf.com 
> wrote:
>>
>> I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) and I 
>> need to do a couple of things, but the functionality seems to be missing:
>>
>> 1. I need to access the model instance to perform some initialization, 
>> but there's no instance member set. There are a few questions on Stack 
>> Overflow on this topic, so I know I'm not alone.
>>
>> 2. I need to initialize my form with a parameter derived from the model 
>> instance. If this were a View, I could just override get_form_kwargs and be 
>> done with it, but ModelAdmin doesn't have it.
>>
>> Is there a reason why those two features are missing from ModelAdmin? 
>> Maybe they could be added (and I could open a PR)? Or is there a better way 
>> to do what I need to do?
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"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/39bbf43e-3a6c-47a4-ab4d-46e5c49cf32b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin missing a couple of key features, or am I doing this wrong?

I think these ideas have been floated before. If you look through the Trac 
tickets you might find something related. However, your subclass where you 
store "self.instance" on ModelAdmin is a no no due to thread safety. See 
http://stackoverflow.com/questions/3388111/modeladmin-thread-safety-caching-issues
 
for an explanation.

On Thursday, September 15, 2016 at 6:53:15 PM UTC-4, th...@copperleaf.com 
wrote:
>
> I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) and I 
> need to do a couple of things, but the functionality seems to be missing:
>
> 1. I need to access the model instance to perform some initialization, but 
> there's no instance member set. There are a few questions on Stack Overflow 
> on this topic, so I know I'm not alone.
>
> 2. I need to initialize my form with a parameter derived from the model 
> instance. If this were a View, I could just override get_form_kwargs and be 
> done with it, but ModelAdmin doesn't have it.
>
> Is there a reason why those two features are missing from ModelAdmin? 
> Maybe they could be added (and I could open a PR)? Or is there a better way 
> to do what I need to do?
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/8555185b-0cec-4fc7-96e5-0cdb2ff7d8c5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


ModelAdmin missing a couple of key features, or am I doing this wrong?

I have a ModelAdmin subclass (code at: <https://dpaste.de/0LAt>) and I need 
to do a couple of things, but the functionality seems to be missing:

1. I need to access the model instance to perform some initialization, but 
there's no instance member set. There are a few questions on Stack Overflow 
on this topic, so I know I'm not alone.

2. I need to initialize my form with a parameter derived from the model 
instance. If this were a View, I could just override get_form_kwargs and be 
done with it, but ModelAdmin doesn't have it.

Is there a reason why those two features are missing from ModelAdmin? Maybe 
they could be added (and I could open a PR)? Or is there a better way to do 
what I need to do?

-- 
You received this message because you are subscribed to the Google Groups 
"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/26d907aa-6427-4cac-9653-0f656a90caf8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Dynamic ModelAdmin Field



El jueves, 14 de julio de 2016, 17:29:38 (UTC+2), Bernat Bonet escribió:
>
> I need to add dynamic fields to ModelAdmin that are not part of the Model.
>
> Models:
>
> product: cod, des
> product_categories: cat, val
>
> I want to add val1, val2 in ProductAdmin
>
> 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/3f832300-33aa-4b99-8e6c-8ff82550dd59%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Dynamic ModelAdmin Field

Why not use custom methods on your model?  These can effectively act as 
extra properties:



*https://docs.djangoproject.com/en/1.9/topics/db/models/#model-methods*(this 
is assuming you do not want to store any data of course... otherwise you 
will need to give a more concrete example of what you want to do)

On Thursday, 14 July 2016 17:29:38 UTC+2, Bernat Bonet wrote:
>
> I need to add dynamic fields to ModelAdmin that are not part of the Model.
>
> Models:
>
> product: cod, des
> product_categories: cat, val
>
> I want to add val1, val2 in ProductAdmin
>
> 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/ce318181-d3a5-45eb-96e5-70219a001810%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


ModelAdmin dynamic fields

I need to add dynamic fields to ModelAdmin fieldset that are not part of 
Model.

This field is to show or hide certain fields.

How can I do this?

Thanks

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


Dynamic ModelAdmin Field

I need to add dynamic fields to ModelAdmin that are not part of the Model.

Models:

product: cod, des
product_categories: cat, val

I want to add val1, val2 in ProductAdmin

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/47fa72e8-5954-4a20-989b-f8e99ad4a9b2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


please help me !django admin search bar add placeholder variable and how to call it in modelAdmin! HELP!

I want to add placeholder to search bar .First,I override the template 
change_list.html and find the search bar ,I know add attribute 
placeholder ,and I defined a variable placeholder={{'''search_tip'}}
to placeholder, as my app has three searchbar in different modelAdmin, I 
want to change the context of the placeholder by changing the variable..but 
I don't konw how to call the variable 'search_tip''  in the modelAdmin!

-- 
You received this message because you are subscribed to the Google Groups 
"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/90ee2d01-4482-4066-bedd-ff1bfce92e07%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


django admin search bar add placeholder variable and how to call it in modelAdmin

I want to add placeholder to search bar .First,I override the template 
change_list.html and find the search bar ,I know add attribute 
placeholder ,and I defined a variable placeholder={{'''search_tip'}}to 
placeholder, as my app has three searchbar in different modelAdmin, I want 
to change the context of the placeholder by changing the variable..but I 
don't konw how to call the variable 'search_tip''  in the modelAdmin!

-- 
You received this message because you are subscribed to the Google Groups 
"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/95fe6ba5-4c6b-458f-9cb4-15aa5258dea6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Malcolm,

> With the patch to check an instance rather than a class, perhaps I should 
extend the checks to check the result of get_readonly_fields() rather than 
just obj.readonly_fields. What do you think?

I think the checks should be run statically against ModelAdmin instances, 
that is only the properties of the instances should be checked and not the 
return value of methods that could depend on request properties such as the 
user.

Simon

Le jeudi 10 septembre 2015 13:32:32 UTC-4, Malcolm Box a écrit :
>
> Hi Simon,
>
> On Thursday, 10 September 2015 16:57:51 UTC+1, Simon Charette wrote:
>>
>> Hi Malcolm,
>>
>> > The system check checks that all the values returned from 
>> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
>> callable/fields on model, neither of which helps here). With them being 
>> created via __getattr__, they don't.
>>
>> There might be something else going on here but I highly doubt checks are 
>> ran against the get_readonly_fields() return value since it's a method 
>> bound to a ModelAdmin instance and requires a `request` argument to be 
>> called in the first place.
>>
>>
> My mistake, you're entirely correct. The SystemChecks check the 
> readonly_fields property, not the result of calling get_readonly_fields().
>
> With the patch to check an instance rather than a class, perhaps I should 
> extend the checks to check the result of get_readonly_fields() rather than 
> just obj.readonly_fields. What do you think?
>
> Malcolm
>
> Simon
>>
>> Le jeudi 10 septembre 2015 06:27:13 UTC-4, Malcolm Box a écrit :
>>>
>>> Hi Simon,
>>>
>>> I've tried that, and it still fails the same system check.
>>>
>>> The system check checks that all the values returned from 
>>> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
>>> callable/fields on model, neither of which helps here). With them being 
>>> created via __getattr__, they don't.
>>>
>>> I'm coming to the conclusion that the right behaviour is to run the 
>>> system check against an instance, not the class, since that's what the core 
>>> admin code uses.
>>>
>>> Thanks for the offer to review changes - I'll try to put a patch 
>>> together this week.
>>>
>>> Cheers,
>>>
>>> Malcolm
>>>
>>> On 9 September 2015 at 18:17, Simon Charette <chare...@gmail.com> wrote:
>>>
>>>> Hi Malcom,
>>>>
>>>> What I meant to suggest is to remove the fields from 
>>>> `fields`/`readonly_fields` and dynamically return them in the 
>>>> `get_(fields|readonly_fields)` fields method.
>>>>
>>>> e.g.
>>>>
>>>> class ThumbnailFieldsAdmin(models.ModelAdmin):
>>>> fields = []
>>>> readonly_fields = []
>>>> thumbnail_fields = []
>>>>
>>>> def __getattr__(self, name):
>>>> if name.endswith('_thumbnail'):
>>>> return thumbnail_function
>>>> raise AttributeError
>>>>
>>>> def get_fields(request, obj=None):
>>>> fields = super(ThumbnailFieldsAdmin, self).get_fields(request, 
>>>> obj=obj)
>>>>     return self.thumbnail_fields + fields
>>>>
>>>> def get_readonly_fields(request, obj=None):
>>>> readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
>>>> request, obj=obj)
>>>> return readonly_fields + thumbnail_fields
>>>>
>>>> But I'm afraid that you'll have to rely on metaclass programming if you 
>>>> want the order of fields to be maintained somehow.
>>>>
>>>> > I therefore suspect that the check is actually borked, and it should 
>>>> be checking hasattr(instance, field_name) rather than hasattr(cls, 
>>>> field_name)
>>>>
>>>> The thing is checks are run against ModelAdmin classes and not the 
>>>> instances bound to the site they were registered to 
>>>> <https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
>>>>  
>>>> You could submit a feature request to actually run the test against the 
>>>> instances but since this is really and edge case you'd have to provide a 
>>>> patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9 
>>>> which should enter feature freeze 

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Simon,

On Thursday, 10 September 2015 16:57:51 UTC+1, Simon Charette wrote:
>
> Hi Malcolm,
>
> > The system check checks that all the values returned from 
> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
> callable/fields on model, neither of which helps here). With them being 
> created via __getattr__, they don't.
>
> There might be something else going on here but I highly doubt checks are 
> ran against the get_readonly_fields() return value since it's a method 
> bound to a ModelAdmin instance and requires a `request` argument to be 
> called in the first place.
>
>
My mistake, you're entirely correct. The SystemChecks check the 
readonly_fields property, not the result of calling get_readonly_fields().

With the patch to check an instance rather than a class, perhaps I should 
extend the checks to check the result of get_readonly_fields() rather than 
just obj.readonly_fields. What do you think?

Malcolm

Simon
>
> Le jeudi 10 septembre 2015 06:27:13 UTC-4, Malcolm Box a écrit :
>>
>> Hi Simon,
>>
>> I've tried that, and it still fails the same system check.
>>
>> The system check checks that all the values returned from 
>> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
>> callable/fields on model, neither of which helps here). With them being 
>> created via __getattr__, they don't.
>>
>> I'm coming to the conclusion that the right behaviour is to run the 
>> system check against an instance, not the class, since that's what the core 
>> admin code uses.
>>
>> Thanks for the offer to review changes - I'll try to put a patch together 
>> this week.
>>
>> Cheers,
>>
>> Malcolm
>>
>> On 9 September 2015 at 18:17, Simon Charette <chare...@gmail.com> wrote:
>>
>>> Hi Malcom,
>>>
>>> What I meant to suggest is to remove the fields from 
>>> `fields`/`readonly_fields` and dynamically return them in the 
>>> `get_(fields|readonly_fields)` fields method.
>>>
>>> e.g.
>>>
>>> class ThumbnailFieldsAdmin(models.ModelAdmin):
>>> fields = []
>>> readonly_fields = []
>>> thumbnail_fields = []
>>>
>>> def __getattr__(self, name):
>>> if name.endswith('_thumbnail'):
>>> return thumbnail_function
>>> raise AttributeError
>>>
>>> def get_fields(request, obj=None):
>>> fields = super(ThumbnailFieldsAdmin, self).get_fields(request, 
>>> obj=obj)
>>> return self.thumbnail_fields + fields
>>>
>>> def get_readonly_fields(request, obj=None):
>>> readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
>>> request, obj=obj)
>>> return readonly_fields + thumbnail_fields
>>>
>>> But I'm afraid that you'll have to rely on metaclass programming if you 
>>> want the order of fields to be maintained somehow.
>>>
>>> > I therefore suspect that the check is actually borked, and it should 
>>> be checking hasattr(instance, field_name) rather than hasattr(cls, 
>>> field_name)
>>>
>>> The thing is checks are run against ModelAdmin classes and not the 
>>> instances bound to the site they were registered to 
>>> <https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
>>>  
>>> You could submit a feature request to actually run the test against the 
>>> instances but since this is really and edge case you'd have to provide a 
>>> patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9 
>>> which should enter feature freeze soon enough. I'd be glad to review your 
>>> proposed changes if you're interested.
>>>
>>> Simon
>>>
>>>
>>> Le mercredi 9 septembre 2015 10:31:12 UTC-4, Malcolm Box a écrit :
>>>
>>>> Hi Simon,
>>>>
>>>> Thanks for the pointer, but I don't think that helps.
>>>>
>>>> The fields are already declared using the existing fields / 
>>>> readonly_fields attributes on the ExampleAdmin class - and this is what 
>>>> get_fields / get_readonly_fields return. The system check fails because 
>>>> the 
>>>> fields declared don't exist on the ExampleAdmin class nor on the model. 
>>>> Here's the relevant lines from contrib/admin/checks.py:
>>>>
>>>> def _check_readonly_fields_item(self, 

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Malcolm,

> The system check checks that all the values returned from 
get_readonly_fields exist as class attributes on the ModelAdmin (or are 
callable/fields on model, neither of which helps here). With them being 
created via __getattr__, they don't.

There might be something else going on here but I highly doubt checks are 
ran against the get_readonly_fields() return value since it's a method 
bound to a ModelAdmin instance and requires a `request` argument to be 
called in the first place.

Simon

Le jeudi 10 septembre 2015 06:27:13 UTC-4, Malcolm Box a écrit :
>
> Hi Simon,
>
> I've tried that, and it still fails the same system check.
>
> The system check checks that all the values returned from 
> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
> callable/fields on model, neither of which helps here). With them being 
> created via __getattr__, they don't.
>
> I'm coming to the conclusion that the right behaviour is to run the system 
> check against an instance, not the class, since that's what the core admin 
> code uses.
>
> Thanks for the offer to review changes - I'll try to put a patch together 
> this week.
>
> Cheers,
>
> Malcolm
>
> On 9 September 2015 at 18:17, Simon Charette <chare...@gmail.com 
> > wrote:
>
>> Hi Malcom,
>>
>> What I meant to suggest is to remove the fields from 
>> `fields`/`readonly_fields` and dynamically return them in the 
>> `get_(fields|readonly_fields)` fields method.
>>
>> e.g.
>>
>> class ThumbnailFieldsAdmin(models.ModelAdmin):
>> fields = []
>> readonly_fields = []
>> thumbnail_fields = []
>>
>> def __getattr__(self, name):
>> if name.endswith('_thumbnail'):
>> return thumbnail_function
>> raise AttributeError
>>
>> def get_fields(request, obj=None):
>> fields = super(ThumbnailFieldsAdmin, self).get_fields(request, 
>> obj=obj)
>> return self.thumbnail_fields + fields
>>
>> def get_readonly_fields(request, obj=None):
>> readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
>> request, obj=obj)
>> return readonly_fields + thumbnail_fields
>>
>> But I'm afraid that you'll have to rely on metaclass programming if you 
>> want the order of fields to be maintained somehow.
>>
>> > I therefore suspect that the check is actually borked, and it should be 
>> checking hasattr(instance, field_name) rather than hasattr(cls, field_name)
>>
>> The thing is checks are run against ModelAdmin classes and not the 
>> instances bound to the site they were registered to 
>> <https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
>>  
>> You could submit a feature request to actually run the test against the 
>> instances but since this is really and edge case you'd have to provide a 
>> patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9 
>> which should enter feature freeze soon enough. I'd be glad to review your 
>> proposed changes if you're interested.
>>
>> Simon
>>
>>
>> Le mercredi 9 septembre 2015 10:31:12 UTC-4, Malcolm Box a écrit :
>>
>>> Hi Simon,
>>>
>>> Thanks for the pointer, but I don't think that helps.
>>>
>>> The fields are already declared using the existing fields / 
>>> readonly_fields attributes on the ExampleAdmin class - and this is what 
>>> get_fields / get_readonly_fields return. The system check fails because the 
>>> fields declared don't exist on the ExampleAdmin class nor on the model. 
>>> Here's the relevant lines from contrib/admin/checks.py:
>>>
>>> def _check_readonly_fields_item(self, cls, model, field_name, label):
>>> if callable(field_name):
>>> return []
>>> elif hasattr(cls, field_name):
>>> return []
>>> elif hasattr(model, field_name):
>>> return []
>>> else:
>>> try:
>>> model._meta.get_field(field_name)
>>> except FieldDoesNotExist:
>>> return [
>>> checks.Error(
>>> "The value of '%s' is not a callable, an 
>>> attribute of '%s', or an attribute of '%s.%s'." % (
>>> label, cls.__name__, model._meta.app_label, 
>>> model._meta.object_name
>>> ),
>>>

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Ticket filed: https://code.djangoproject.com/ticket/25374

On Thursday, 10 September 2015 11:27:13 UTC+1, Malcolm Box wrote:
>
> Hi Simon,
>
> I've tried that, and it still fails the same system check.
>
> The system check checks that all the values returned from 
> get_readonly_fields exist as class attributes on the ModelAdmin (or are 
> callable/fields on model, neither of which helps here). With them being 
> created via __getattr__, they don't.
>
> I'm coming to the conclusion that the right behaviour is to run the system 
> check against an instance, not the class, since that's what the core admin 
> code uses.
>
> Thanks for the offer to review changes - I'll try to put a patch together 
> this week.
>
> Cheers,
>
> Malcolm
>
> On 9 September 2015 at 18:17, Simon Charette <> wrote:
>
>> Hi Malcom,
>>
>> What I meant to suggest is to remove the fields from 
>> `fields`/`readonly_fields` and dynamically return them in the 
>> `get_(fields|readonly_fields)` fields method.
>>
>> e.g.
>>
>> class ThumbnailFieldsAdmin(models.ModelAdmin):
>> fields = []
>> readonly_fields = []
>> thumbnail_fields = []
>>
>> def __getattr__(self, name):
>> if name.endswith('_thumbnail'):
>> return thumbnail_function
>> raise AttributeError
>>
>> def get_fields(request, obj=None):
>> fields = super(ThumbnailFieldsAdmin, self).get_fields(request, 
>> obj=obj)
>> return self.thumbnail_fields + fields
>>
>> def get_readonly_fields(request, obj=None):
>> readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
>> request, obj=obj)
>> return readonly_fields + thumbnail_fields
>>
>> But I'm afraid that you'll have to rely on metaclass programming if you 
>> want the order of fields to be maintained somehow.
>>
>> > I therefore suspect that the check is actually borked, and it should be 
>> checking hasattr(instance, field_name) rather than hasattr(cls, field_name)
>>
>> The thing is checks are run against ModelAdmin classes and not the 
>> instances bound to the site they were registered to 
>> <https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
>>  
>> You could submit a feature request to actually run the test against the 
>> instances but since this is really and edge case you'd have to provide a 
>> patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9 
>> which should enter feature freeze soon enough. I'd be glad to review your 
>> proposed changes if you're interested.
>>
>> Simon
>>
>>
>> Le mercredi 9 septembre 2015 10:31:12 UTC-4, Malcolm Box a écrit :
>>
>>> Hi Simon,
>>>
>>> Thanks for the pointer, but I don't think that helps.
>>>
>>> The fields are already declared using the existing fields / 
>>> readonly_fields attributes on the ExampleAdmin class - and this is what 
>>> get_fields / get_readonly_fields return. The system check fails because the 
>>> fields declared don't exist on the ExampleAdmin class nor on the model. 
>>> Here's the relevant lines from contrib/admin/checks.py:
>>>
>>> def _check_readonly_fields_item(self, cls, model, field_name, label):
>>> if callable(field_name):
>>> return []
>>> elif hasattr(cls, field_name):
>>> return []
>>> elif hasattr(model, field_name):
>>> return []
>>> else:
>>> try:
>>> model._meta.get_field(field_name)
>>> except FieldDoesNotExist:
>>> return [
>>> checks.Error(
>>> "The value of '%s' is not a callable, an 
>>> attribute of '%s', or an attribute of '%s.%s'." % (
>>> label, cls.__name__, model._meta.app_label, 
>>> model._meta.object_name
>>>     ),
>>> hint=None,
>>> obj=cls,
>>> id='admin.E035',
>>> )
>>> ]
>>> else:
>>> return []
>>>
>>> If the thumbnail fields were defined as methods on the ExampleAdmin, all 
>>> would be fine e.g.:
>>>
>>> class ExampleAdmin(models.ModelAdmin):
>>&

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Simon,

I've tried that, and it still fails the same system check.

The system check checks that all the values returned from
get_readonly_fields exist as class attributes on the ModelAdmin (or are
callable/fields on model, neither of which helps here). With them being
created via __getattr__, they don't.

I'm coming to the conclusion that the right behaviour is to run the system
check against an instance, not the class, since that's what the core admin
code uses.

Thanks for the offer to review changes - I'll try to put a patch together
this week.

Cheers,

Malcolm

On 9 September 2015 at 18:17, Simon Charette <charett...@gmail.com> wrote:

> Hi Malcom,
>
> What I meant to suggest is to remove the fields from
> `fields`/`readonly_fields` and dynamically return them in the
> `get_(fields|readonly_fields)` fields method.
>
> e.g.
>
> class ThumbnailFieldsAdmin(models.ModelAdmin):
> fields = []
> readonly_fields = []
> thumbnail_fields = []
>
> def __getattr__(self, name):
> if name.endswith('_thumbnail'):
> return thumbnail_function
> raise AttributeError
>
> def get_fields(request, obj=None):
> fields = super(ThumbnailFieldsAdmin, self).get_fields(request, obj
> =obj)
> return self.thumbnail_fields + fields
>
> def get_readonly_fields(request, obj=None):
> readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
> request, obj=obj)
> return readonly_fields + thumbnail_fields
>
> But I'm afraid that you'll have to rely on metaclass programming if you
> want the order of fields to be maintained somehow.
>
> > I therefore suspect that the check is actually borked, and it should be
> checking hasattr(instance, field_name) rather than hasattr(cls, field_name)
>
> The thing is checks are run against ModelAdmin classes and not the
> instances bound to the site they were registered to
> <https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
> You could submit a feature request to actually run the test against the
> instances but since this is really and edge case you'd have to provide a
> patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9
> which should enter feature freeze soon enough. I'd be glad to review your
> proposed changes if you're interested.
>
> Simon
>
>
> Le mercredi 9 septembre 2015 10:31:12 UTC-4, Malcolm Box a écrit :
>
>> Hi Simon,
>>
>> Thanks for the pointer, but I don't think that helps.
>>
>> The fields are already declared using the existing fields /
>> readonly_fields attributes on the ExampleAdmin class - and this is what
>> get_fields / get_readonly_fields return. The system check fails because the
>> fields declared don't exist on the ExampleAdmin class nor on the model.
>> Here's the relevant lines from contrib/admin/checks.py:
>>
>> def _check_readonly_fields_item(self, cls, model, field_name, label):
>> if callable(field_name):
>> return []
>> elif hasattr(cls, field_name):
>> return []
>> elif hasattr(model, field_name):
>> return []
>> else:
>> try:
>> model._meta.get_field(field_name)
>> except FieldDoesNotExist:
>> return [
>> checks.Error(
>> "The value of '%s' is not a callable, an
>> attribute of '%s', or an attribute of '%s.%s'." % (
>> label, cls.__name__, model._meta.app_label,
>> model._meta.object_name
>> ),
>> hint=None,
>> obj=cls,
>> id='admin.E035',
>> )
>> ]
>> else:
>> return []
>>
>> If the thumbnail fields were defined as methods on the ExampleAdmin, all
>> would be fine e.g.:
>>
>> class ExampleAdmin(models.ModelAdmin):
>>fields = ['image', 'image_thumbnail']
>>
>>def image_thumbnail(self, obj):
>>return "" % obj.image.url
>>
>> That's fine, but if there's lots of image fields (with a variety of
>> names) spread over several ModelAdmin classes, then you end up with a lot
>> of duplicated code. The normal solution then is to refactor the code. And
>> that's where I get stuck - I can't see (short of metaclass programming!)
>> how to inject the methods into the class such that the system check
>> succeeds.
>>
>> I therefore 

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Malcom,

What I meant to suggest is to remove the fields from 
`fields`/`readonly_fields` and dynamically return them in the 
`get_(fields|readonly_fields)` fields method.

e.g.

class ThumbnailFieldsAdmin(models.ModelAdmin):
fields = []
readonly_fields = []
thumbnail_fields = []

def __getattr__(self, name):
if name.endswith('_thumbnail'):
return thumbnail_function
raise AttributeError

def get_fields(request, obj=None):
fields = super(ThumbnailFieldsAdmin, self).get_fields(request, obj=
obj)
return self.thumbnail_fields + fields

def get_readonly_fields(request, obj=None):
readonly_fields = super(ThumbnailFieldsAdmin, self).get_fields(
request, obj=obj)
return readonly_fields + thumbnail_fields

But I'm afraid that you'll have to rely on metaclass programming if you 
want the order of fields to be maintained somehow.

> I therefore suspect that the check is actually borked, and it should be 
checking hasattr(instance, field_name) rather than hasattr(cls, field_name)

The thing is checks are run against ModelAdmin classes and not the 
instances bound to the site they were registered to 
<https://github.com/django/django/blob/dae81c6ec62a76c1f28745ae3642c2d4a37ce259/django/contrib/admin/sites.py#L106-L110>.
 
You could submit a feature request to actually run the test against the 
instances but since this is really and edge case you'd have to provide a 
patch/PR if you don't want the ticket to rot in Trac make it to Django 1.9 
which should enter feature freeze soon enough. I'd be glad to review your 
proposed changes if you're interested.

Simon

Le mercredi 9 septembre 2015 10:31:12 UTC-4, Malcolm Box a écrit :
>
> Hi Simon,
>
> Thanks for the pointer, but I don't think that helps.
>
> The fields are already declared using the existing fields / 
> readonly_fields attributes on the ExampleAdmin class - and this is what 
> get_fields / get_readonly_fields return. The system check fails because the 
> fields declared don't exist on the ExampleAdmin class nor on the model. 
> Here's the relevant lines from contrib/admin/checks.py:
>
> def _check_readonly_fields_item(self, cls, model, field_name, label):
> if callable(field_name):
> return []
> elif hasattr(cls, field_name):
> return []
> elif hasattr(model, field_name):
> return []
> else:
> try:
> model._meta.get_field(field_name)
> except FieldDoesNotExist:
> return [
> checks.Error(
> "The value of '%s' is not a callable, an attribute 
> of '%s', or an attribute of '%s.%s'." % (
> label, cls.__name__, model._meta.app_label, 
> model._meta.object_name
> ),
> hint=None,
> obj=cls,
> id='admin.E035',
> )
> ]
> else:
> return []
>
> If the thumbnail fields were defined as methods on the ExampleAdmin, all 
> would be fine e.g.:
>
> class ExampleAdmin(models.ModelAdmin):
>fields = ['image', 'image_thumbnail']
>
>def image_thumbnail(self, obj):
>return "" % obj.image.url 
>
> That's fine, but if there's lots of image fields (with a variety of names) 
> spread over several ModelAdmin classes, then you end up with a lot of 
> duplicated code. The normal solution then is to refactor the code. And 
> that's where I get stuck - I can't see (short of metaclass programming!) 
> how to inject the methods into the class such that the system check 
> succeeds.
>
> I therefore suspect that the check is actually borked, and it should be 
> checking hasattr(instance, field_name) rather than hasattr(cls, 
> field_name)
>
> So I see three possibilities, in order of probability:
>
>1. I'm being dumb, and there's an easy way to dynamically create 
>attributes on a ModelAdmin that passes system checks
>2. The system check is incorrect, and should allow dynamically created 
>attributes on ModelAdmin when validating fields
>3. Metaclass programming is really the right way to do this
>
>
> Malcolm
>
> On 9 September 2015 at 02:23, Simon Charette <chare...@gmail.com 
> > wrote:
>
>> Hi Malcom!
>>
>> I would suggest you have a look at the ModelAdmin.get_fields() 
>> <https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields>
>>  
>> method to append your thumbnail read-only field names.
>>
>> As documented 
>> <https://docs.djangoproject.com/en/1.8/ref/contr

Re: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Simon,

Thanks for the pointer, but I don't think that helps.

The fields are already declared using the existing fields / readonly_fields
attributes on the ExampleAdmin class - and this is what get_fields /
get_readonly_fields return. The system check fails because the fields
declared don't exist on the ExampleAdmin class nor on the model. Here's the
relevant lines from contrib/admin/checks.py:

def _check_readonly_fields_item(self, cls, model, field_name, label):
if callable(field_name):
return []
elif hasattr(cls, field_name):
return []
elif hasattr(model, field_name):
return []
else:
try:
model._meta.get_field(field_name)
except FieldDoesNotExist:
return [
checks.Error(
"The value of '%s' is not a callable, an attribute
of '%s', or an attribute of '%s.%s'." % (
label, cls.__name__, model._meta.app_label,
model._meta.object_name
),
hint=None,
obj=cls,
id='admin.E035',
)
]
else:
return []

If the thumbnail fields were defined as methods on the ExampleAdmin, all
would be fine e.g.:

class ExampleAdmin(models.ModelAdmin):
   fields = ['image', 'image_thumbnail']

   def image_thumbnail(self, obj):
   return "" % obj.image.url

That's fine, but if there's lots of image fields (with a variety of names)
spread over several ModelAdmin classes, then you end up with a lot of
duplicated code. The normal solution then is to refactor the code. And
that's where I get stuck - I can't see (short of metaclass programming!)
how to inject the methods into the class such that the system check
succeeds.

I therefore suspect that the check is actually borked, and it should be
checking hasattr(instance, field_name) rather than hasattr(cls, field_name)

So I see three possibilities, in order of probability:

   1. I'm being dumb, and there's an easy way to dynamically create
   attributes on a ModelAdmin that passes system checks
   2. The system check is incorrect, and should allow dynamically created
   attributes on ModelAdmin when validating fields
   3. Metaclass programming is really the right way to do this


Malcolm

On 9 September 2015 at 02:23, Simon Charette <charett...@gmail.com> wrote:

> Hi Malcom!
>
> I would suggest you have a look at the ModelAdmin.get_fields()
> <https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields>
> method to append your thumbnail read-only field names.
>
> As documented
> <https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields>,
> just make sure you also override ModelAdmin.get_readonly_fields()
> <https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_readonly_fields>
> to return them as well.
>
> Cheers,
> Simon
>
> Le mardi 8 septembre 2015 13:31:47 UTC-4, Malcolm Box a écrit :
>>
>> Hi,
>>
>> I'm trying to add a dynamic method to a ModelAdmin so that I can have
>> automatically generated thumbnail fields for any image by simply adding
>> '_thumbnail' to the field definitions - which saves a lot of
>> code when there's a load of admin classes with image fields that need
>> thumbnails.
>>
>> e.g.
>>
>> class ThumbnailMixin(object):
>> def getattr(self, name):
>>  if name.endswith('_thumbnail'):
>>   # ... generate appropriate thumbnail method and return
>>   return thumbnail_function
>>  else:
>>  raise AttributeError
>>
>> class ExampleAdmin(models.ModelAdmin, ThumbnailMixin):
>>  fields = ['image_thumbnail', 'image', ...]
>>
>> This worked fine in Django 1.6/1.7, but it's now failing in 1.8 with a
>> SystemCheckError (admin.E035 / admin.E108). If I silence the error, the
>> admin actually works fine, but that feels icky.
>>
>> The check fails because it checks for the field being on the ExampleAdmin
>> class, not on an instance - whereas the admin always uses an instance, so
>> it works.
>>
>> What's the "right" way to do this in the 1.8 world - I've considered a
>> custom metaclass, but that feels like overkill for a simple task like this.
>> Should this even work, and if so is it a bug in the check framework?
>>
>> Cheers,
>>
>> Malcolm
>>
> --
> 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: Adding dynamic methods to ModelAdmin fails in 1.8

Hi Malcom!

I would suggest you have a look at the ModelAdmin.get_fields() 
<https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_fields>
 
method to append your thumbnail read-only field names.

As documented 
<https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields>,
 
just make sure you also override ModelAdmin.get_readonly_fields() 
<https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_readonly_fields>
 
to return them as well.

Cheers,
Simon

Le mardi 8 septembre 2015 13:31:47 UTC-4, Malcolm Box a écrit :
>
> Hi,
>
> I'm trying to add a dynamic method to a ModelAdmin so that I can have 
> automatically generated thumbnail fields for any image by simply adding 
> '_thumbnail' to the field definitions - which saves a lot of 
> code when there's a load of admin classes with image fields that need 
> thumbnails.
>
> e.g.
>
> class ThumbnailMixin(object):
> def getattr(self, name):
>  if name.endswith('_thumbnail'):
>   # ... generate appropriate thumbnail method and return
>   return thumbnail_function
>  else:
>  raise AttributeError
>
> class ExampleAdmin(models.ModelAdmin, ThumbnailMixin):
>  fields = ['image_thumbnail', 'image', ...]
>
> This worked fine in Django 1.6/1.7, but it's now failing in 1.8 with a 
> SystemCheckError (admin.E035 / admin.E108). If I silence the error, the 
> admin actually works fine, but that feels icky.
>
> The check fails because it checks for the field being on the ExampleAdmin 
> class, not on an instance - whereas the admin always uses an instance, so 
> it works.
>
> What's the "right" way to do this in the 1.8 world - I've considered a 
> custom metaclass, but that feels like overkill for a simple task like this. 
> Should this even work, and if so is it a bug in the check framework?
>
> Cheers,
>
> Malcolm
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/05249551-899b-4a64-b416-216c9f81d950%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Adding dynamic methods to ModelAdmin fails in 1.8

Hi,

I'm trying to add a dynamic method to a ModelAdmin so that I can have 
automatically generated thumbnail fields for any image by simply adding 
'_thumbnail' to the field definitions - which saves a lot of 
code when there's a load of admin classes with image fields that need 
thumbnails.

e.g.

class ThumbnailMixin(object):
def getattr(self, name):
 if name.endswith('_thumbnail'):
  # ... generate appropriate thumbnail method and return
  return thumbnail_function
 else:
 raise AttributeError

class ExampleAdmin(models.ModelAdmin, ThumbnailMixin):
 fields = ['image_thumbnail', 'image', ...]

This worked fine in Django 1.6/1.7, but it's now failing in 1.8 with a 
SystemCheckError (admin.E035 / admin.E108). If I silence the error, the 
admin actually works fine, but that feels icky.

The check fails because it checks for the field being on the ExampleAdmin 
class, not on an instance - whereas the admin always uses an instance, so 
it works.

What's the "right" way to do this in the 1.8 world - I've considered a 
custom metaclass, but that feels like overkill for a simple task like this. 
Should this even work, and if so is it a bug in the check framework?

Cheers,

Malcolm

-- 
You received this message because you are subscribed to the Google Groups 
"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/987461ae-f455-44f7-9c61-935a6d412c49%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django Admin - get formset class reference from modeladmin

Dear All,

 In a ModelAdmin object, how to reference the formset class of the 
inline?

-- 
You received this message because you are subscribed to the Google Groups 
"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/f0362459-df9e-45a0-83ce-862e1834c86c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


is it safe to use ModelAdmin variables like this

Is it safe to set a modeladmin variable and use it like this; it is set in 
the changelist_view based on the url search criteria and is used to limit 
the choices of a foreign key when adding new item

class MyModelAdmin(reversion.VersionAdmin):
...
selected_period = None

def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "period":
kwargs["queryset"] = Period.objects.filter(id=self.selected_period)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, 
request, **kwargs)

def changelist_view(self, request, extra_context=None):
   ..
if request.GET.has_key('period__id__exact'):
self.selected_period = request.GET['period__id__exact']
return super(MyModelAdmin, self).changelist_view(request, 
extra_context=extra_context)
admin.site.register(MyClassroomAbsenceLog, MyClassroomAbsenceLogAdmin)


-- 
You received this message because you are subscribed to the Google Groups 
"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/02120fbc-8f78-4d65-b0b8-d503434b8f6f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin with inlines: How to learn if/what has changed before the models are saved?


Hi Alex,

Am 20.12.2014 um 22:47 schrieb Alex Haylock:

Take a look at the Django signal dispatcher:
https://docs.djangoproject.com/en/dev/topics/signals/

Specifically, the 'update_fields' argument passed to the 'pre_save'
signal should provide what you need:

https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save


Many thanks for your reply!

While I seem to understand signals generally, I followed Collin's 
suggestion, because the ModelAdmin class already has so many readily 
available customization callbacks, so that this eventually looked a bit 
more straightforward to me.


Also, the big question that occurred to me when I (re-)read the signals 
documentation that you linked above was this description for the 
`update_fields` argument:
“The set of fields to update explicitly specified in the save() 
method. None if this argument was not used in the save() call.“


To be honest, I did not fully set it up to try it out, but in the 
ModelAdmin source I saw that the model's save() method is plainly 
called, without any explicit parameters. This would have rendered the 
`update_fields` useless, and left me with no way to figure out what has 
changed in the model when the pre_save signal is received, right?


Best regards,
Carsten

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


Re: ModelAdmin with inlines: How to learn if/what has changed before the models are saved?


Hi Collin,

Am 20.12.2014 um 00:18 schrieb Collin Anderson:

save_model() happens first, then save_related() which
calls save_formset() on each formset.

It might end up being easier to save the parent model _again_, instead
of doing something before it's saved.


Thank you very much for your reply, that helped a lot!


_has_changed() / has_changed() may come in handy in your case.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#has-changed


In Django 1.7, it seems that _has_changed() takes several parameters 
that I had not readily available, so I eventually looked this up in the 
Django 1.7 source code (django/forms/forms.py), and now instead of, for 
example (probably valid Django 1.8 code):


if form.fields['birthday'].has_changed():  ...

with Django 1.7 I use:

if "birthday" in form.changed_data:  ...

which works very well!

Thanks again for your help!

   :-)

Best regards,
Carsten

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


Re: ModelAdmin with inlines: How to learn if/what has changed before the models are saved?

On 18/12/14 17:19, Carsten Fuchs wrote:
> I would like to find out if anything has changed in the parent
> model or the related (inline) models, and depending on the result,
> update one of the parent model's fields before it is saved.
> 
> Can you please tell me how can this be achieved?


Take a look at the Django signal dispatcher:
https://docs.djangoproject.com/en/dev/topics/signals/

Specifically, the 'update_fields' argument passed to the 'pre_save'
signal should provide what you need:

https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save

Regards,

Alex.

-- 
You received this message because you are subscribed to the Google Groups 
"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/5495EE89.6040504%40mykolab.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelAdmin with inlines: How to learn if/what has changed before the models are saved?

Hi Carsten,

save_model() happens first, then save_related() which calls save_formset() 
on each formset.

It might end up being easier to save the parent model _again_, instead of 
doing something before it's saved.

_has_changed() / has_changed() may come in handy in your case.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#has-changed

Collin

On Thursday, December 18, 2014 12:20:34 PM UTC-5, Carsten Fuchs wrote:
>
> Hi fellow Django developers, 
>
> using a model with several related models, for the Django Admin I have a 
> ModelAdmin that uses several InlineModelAdmin objects, very much as in 
> the example at 
> <
> https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#inlinemodeladmin-objects>.
>  
>
>
> All works well, but when the user clicks the "Save" button in the change 
> view, I would like to find out if anything has changed in the parent 
> model or the related (inline) models, and depending on the result, 
> update one of the parent model's fields before it is saved. 
>
> Can you please tell me how can this be achieved? 
>
>
> In more detail, having read all of 
> https://docs.djangoproject.com/en/1.7/ref/contrib/admin/ and thinking 
> that I have understood most of it, the ModelAdmin methods 
>
>  save_model() 
>  save_formset() 
>  save_related() 
>
> seem to be the right approach to my problem, but are a complete mystery 
> to me: How are the related to each other, and what is their purpose? 
>
> The documentation of all three begins with "The save_* method is given 
> the HttpRequest, ...", but what follows it too sparse for my still 
> limited Django knowledge, and unfortunately I cannot see yet the bigger 
> picture about them, or how to proceed from there. 
>
> Could someone please explain how these methods work, when they are 
> called, etc.? 
>
>
> A huge thanks in advance and best regards, 
> Carsten 
>

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


ModelAdmin with inlines: How to learn if/what has changed before the models are saved?


Hi fellow Django developers,

using a model with several related models, for the Django Admin I have a 
ModelAdmin that uses several InlineModelAdmin objects, very much as in 
the example at 
<https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#inlinemodeladmin-objects>.


All works well, but when the user clicks the "Save" button in the change 
view, I would like to find out if anything has changed in the parent 
model or the related (inline) models, and depending on the result, 
update one of the parent model's fields before it is saved.


Can you please tell me how can this be achieved?


In more detail, having read all of 
https://docs.djangoproject.com/en/1.7/ref/contrib/admin/ and thinking 
that I have understood most of it, the ModelAdmin methods


save_model()
save_formset()
save_related()

seem to be the right approach to my problem, but are a complete mystery 
to me: How are the related to each other, and what is their purpose?


The documentation of all three begins with "The save_* method is given 
the HttpRequest, ...", but what follows it too sparse for my still 
limited Django knowledge, and unfortunately I cannot see yet the bigger 
picture about them, or how to proceed from there.


Could someone please explain how these methods work, when they are 
called, etc.?



A huge thanks in advance and best regards,
Carsten

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


Re: Modifying a ModelAdmin instance at runtime

Ohh. Yup. My bad :)

On Wednesday, November 12, 2014 5:01:03 PM UTC-5, Peter Sagerson wrote:
>
> I agree that setting self.exclude will set the instance attribute, thus 
> hiding the class attribute of the same name. However, it appears that a 
> given AdminSite instantiates each registered ModelAdmin once at 
> registration time.[1] The default AdminSite itself is a module global. 
> Thus, any long-running, multi-threaded Django application server (e.g. a 
> threaded uWSGI process) might be relying on a given ModelAdmin instance to 
> serve multiple requests concurrently. Neither AdminSite nor ModelAdmin 
> appear to have any thread-locality, suggesting that modifying self.exclude 
> (or anything else) for an individual request is a race condition waiting to 
> happen. 
>
> I believe this is essentially a subtle documentation bug, although it's 
> worth asking whether there are any deeper assumptions about ModelAdmin or 
> AdminSite having any kind of request isolation. 
>
> Thanks, 
> Peter 
>
>
> [1] 
> https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L104
>  
>
>
> > On Nov 12, 2014, at 1:36 PM, Collin Anderson <cmawe...@gmail.com 
> > wrote: 
> > 
> > On Tuesday, November 11, 2014 3:24:48 PM UTC-5, Peter Sagerson wrote: 
> > The documentation of ModelAdmin.get_form()[1] demonstrates modifying 
> self.exclude in order to modify the add/change form on a per-request basis. 
> However, looking at django.contrib.admin, it seems clear that ModelAdmin is 
> instantiated when it's installed, not for every request. It also doesn't 
> appear to be a subclass of threading.local. Is there some reason this isn't 
> a terrible idea or is the example just in error? 
> > 
> > Thanks, 
> > Peter 
> > 
> > 
> > [1] 
> https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form
>  
> > 
> > Hi Peter, 
> > 
> > I've never thought that way about admin classes before, but it should 
> work correctly. 
> > 
> > In Python, setting self.exclude = ['something'] will set a _new_ 
> attribute on on the object, the instance of the admin class, not the admin 
> class itself, even if there's a matching attribute on the class with that 
> name. You'll end up with two different exclude lists. One in 
> self.__class__.__dict__ (aka vars(type(self))) (which is now pretty hidden) 
> and one in self.__dict__ (aka vars(self)). 
> > 
> > Though, if you _mutate_ the original attribute, like 
> self.exclude.append('something'), it will mutate the exclude list on the 
> class. 
> > 
> > Collin 
> > 
> > 
> > -- 
> > 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/AmoUDtEefyA/unsubscribe. 
> > To unsubscribe from this group and all its topics, send an email to 
> django-users...@googlegroups.com . 
> > To post to this group, send email to django...@googlegroups.com 
> . 
> > Visit this group at http://groups.google.com/group/django-users. 
> > To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/be985862-c203-4358-bc78-8988a295f733%40googlegroups.com.
>  
>
> > For more options, visit https://groups.google.com/d/optout. 
>
>

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


Re: Modifying a ModelAdmin instance at runtime

> Your analysis is entirely correct, as far as I can tell. Setting
> attributes on `self` in a per-request method of a `ModelAdmin` is not
> concurrency-safe, and it should not be recommended or demonstrated in
> the docs. If you'd be willing to file a bug (or, better, a PR) to fix
> this documentation example, that would be excellent.

Will do, thanks for the sanity check.

-- 
You received this message because you are subscribed to the Google Groups 
"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/AC15DBCF-3DE0-4B23-89BD-040188CA81C5%40ignorare.net.
For more options, visit https://groups.google.com/d/optout.


Re: Modifying a ModelAdmin instance at runtime

Hi Peter,

On 11/12/2014 10:59 PM, Peter Sagerson wrote:
> I agree that setting self.exclude will set the instance attribute,
> thus hiding the class attribute of the same name. However, it appears
> that a given AdminSite instantiates each registered ModelAdmin once
> at registration time.[1] The default AdminSite itself is a module
> global. Thus, any long-running, multi-threaded Django application
> server (e.g. a threaded uWSGI process) might be relying on a given
> ModelAdmin instance to serve multiple requests concurrently. Neither
> AdminSite nor ModelAdmin appear to have any thread-locality,
> suggesting that modifying self.exclude (or anything else) for an
> individual request is a race condition waiting to happen.
> 
> I believe this is essentially a subtle documentation bug, although
> it's worth asking whether there are any deeper assumptions about
> ModelAdmin or AdminSite having any kind of request isolation.

Your analysis is entirely correct, as far as I can tell. Setting
attributes on `self` in a per-request method of a `ModelAdmin` is not
concurrency-safe, and it should not be recommended or demonstrated in
the docs. If you'd be willing to file a bug (or, better, a PR) to fix
this documentation example, that would be excellent.

I don't know of any bugs of this type in Django itself, but it's
certainly possible there are some. It shouldn't be too hard to audit for
them - if you find one, definitely file it as an issue.

Unfortunately I would expect bugs like this to become only more common
in user code going forward, since the class-based-views framework does
behind-the-scenes magic to make `self` concurrency-safe in CBVs, so it's
likely that users will transfer those expectations to their `ModelAdmin`
classes.

Thanks!

Carl



signature.asc
Description: OpenPGP digital signature


Re: Modifying a ModelAdmin instance at runtime

I agree that setting self.exclude will set the instance attribute, thus hiding 
the class attribute of the same name. However, it appears that a given 
AdminSite instantiates each registered ModelAdmin once at registration time.[1] 
The default AdminSite itself is a module global. Thus, any long-running, 
multi-threaded Django application server (e.g. a threaded uWSGI process) might 
be relying on a given ModelAdmin instance to serve multiple requests 
concurrently. Neither AdminSite nor ModelAdmin appear to have any 
thread-locality, suggesting that modifying self.exclude (or anything else) for 
an individual request is a race condition waiting to happen.

I believe this is essentially a subtle documentation bug, although it's worth 
asking whether there are any deeper assumptions about ModelAdmin or AdminSite 
having any kind of request isolation. 

Thanks,
Peter


[1] 
https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L104


> On Nov 12, 2014, at 1:36 PM, Collin Anderson <cmawebs...@gmail.com> wrote:
> 
> On Tuesday, November 11, 2014 3:24:48 PM UTC-5, Peter Sagerson wrote:
> The documentation of ModelAdmin.get_form()[1] demonstrates modifying 
> self.exclude in order to modify the add/change form on a per-request basis. 
> However, looking at django.contrib.admin, it seems clear that ModelAdmin is 
> instantiated when it's installed, not for every request. It also doesn't 
> appear to be a subclass of threading.local. Is there some reason this isn't a 
> terrible idea or is the example just in error?
> 
> Thanks,
> Peter
> 
> 
> [1] 
> https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form
> 
> Hi Peter,
> 
> I've never thought that way about admin classes before, but it should work 
> correctly.
> 
> In Python, setting self.exclude = ['something'] will set a _new_ attribute on 
> on the object, the instance of the admin class, not the admin class itself, 
> even if there's a matching attribute on the class with that name. You'll end 
> up with two different exclude lists. One in self.__class__.__dict__ (aka 
> vars(type(self))) (which is now pretty hidden) and one in self.__dict__ (aka 
> vars(self)).
> 
> Though, if you _mutate_ the original attribute, like 
> self.exclude.append('something'), it will mutate the exclude list on the 
> class.
> 
> Collin
> 
> 
> -- 
> 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/AmoUDtEefyA/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to 
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/be985862-c203-4358-bc78-8988a295f733%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

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


Re: Modifying a ModelAdmin instance at runtime

On Tuesday, November 11, 2014 3:24:48 PM UTC-5, Peter Sagerson wrote:
>
> The documentation of ModelAdmin.get_form()[1] demonstrates modifying 
> self.exclude in order to modify the add/change form on a per-request basis. 
> However, looking at django.contrib.admin, it seems clear that ModelAdmin is 
> instantiated when it's installed, not for every request. It also doesn't 
> appear to be a subclass of threading.local. Is there some reason this isn't 
> a terrible idea or is the example just in error?
>
> Thanks,
> Peter
>
>
> [1] 
> https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form
>

Hi Peter,

I've never thought that way about admin classes before, but it should work 
correctly.

In Python, setting self.exclude = ['something'] will set a _new_ attribute 
on on the object, the instance of the admin class, not the admin class 
itself, even if there's a matching attribute on the class with that name. 
You'll end up with two different exclude lists. One in 
self.__class__.__dict__ (aka vars(type(self))) (which is now pretty hidden) 
and one in self.__dict__ (aka vars(self)).

Though, if you _mutate_ the original attribute, like 
self.exclude.append('something'), it will mutate the exclude list on the 
class.

Collin

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


Modifying a ModelAdmin instance at runtime

The documentation of ModelAdmin.get_form()[1] demonstrates modifying 
self.exclude in order to modify the add/change form on a per-request basis. 
However, looking at django.contrib.admin, it seems clear that ModelAdmin is 
instantiated when it's installed, not for every request. It also doesn't 
appear to be a subclass of threading.local. Is there some reason this isn't 
a terrible idea or is the example just in error?

Thanks,
Peter


[1] 
https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form

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


Re: Rendering TabuarInline inside ModelAdmin without a foreign key

Thanks Collin. That's the path I've had to take.
On 03/11/2014 11:55 am, "Collin Anderson"  wrote:

> Hi Mario,
>
> If you are able to edit the model replacing the IntegerField with this
> should do what you want:
> user = models.ForeignKey(CRMUser, null=True, blank=True,
> on_delete=DO_NOTHING)
>
> Collin
>
>  --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/831261fb-2037-4ed1-8bb4-2a6ec7e6b33e%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Rendering TabuarInline inside ModelAdmin without a foreign key

Hi Mario,

If you are able to edit the model replacing the IntegerField with this 
should do what you want:
user = models.ForeignKey(CRMUser, null=True, blank=True, 
on_delete=DO_NOTHING)

Collin

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


Re: Rendering TabuarInline inside ModelAdmin without a foreign key

Here's the models code, DR:

class CRMUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='Email Address',
max_length=255,
unique=True,
)
first_name = models.CharField("First Name", max_length=50, blank=True)
last_name = models.CharField("Last Name", max_length=50, blank=True)
phone = models.CharField("Billing Country", max_length=30, null=True,
blank=True)
...

class Order(models.Model):
order_code = models.CharField("Order ID", null=True, max_length=10)
status = models.IntegerField("Order Status",
choices=ORDER_STATUS_CHOICES, null=True, default=1)
user_id = models.IntegerField("User ID", null=True, blank=True)
...

Thanks for all your help on SO and this list by the way. I seem to come
across your answers a lot and they're really useful. You're a champ!

On 30 October 2014 07:06, Mario Gudelj  wrote:

> I did not produce the original model so I wouldn't know. My thinking is
> that the order model had to be independent of the user model so that the
> deletion of the user doesn't cascade down to orders. It's a mezzanine site
> and that's how it handles fk from orders to users.
> On 29/10/2014 9:27 pm, "Daniel Roseman"  wrote:
>
>> On Wednesday, 29 October 2014 03:57:36 UTC, somecallitblues wrote:
>>>
>>> Hi list,
>>>
>>> I have a table of orders where one of the columns is a IntegerField
>>> containing the id of a user who created the order.
>>>
>>> Since it's not a FK field django admin can't display these orders inline
>>> inside the user details page.
>>>
>>> I would normally use something like:
>>>
>>> class OrderInline(admin.TabularInline):
>>> extra = 0
>>> model = Order
>>>
>>> And then add that to the user model like this:
>>>
>>> inlines = [OrderInline]
>>>
>>> But it won't work without the FK.
>>>
>>> I've Googled around and tried everything I found on SO but I can't
>>> figure out how to add orders inline to my user model.
>>>
>>> I'm looking at https://docs.djangoproject.com/en/dev/_modules/django/
>>> contrib/contenttypes/admin/#GenericTabularInline and I'm thinking do I
>>> need to write a similar class or is there something easy and simple I'm
>>> missing.
>>>
>>> Cheers,
>>>
>>> Mario
>>>
>>>
>>>
>> You don't show your models, but why is it not a ForeignKey? After all, a
>> FK field is exactly what you describe, an integer field that contains the
>> ID of the model it is pointing to. So why not declare it as one?
>> --
>> DR.
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/fc21c60e-5a33-4e10-9f48-42c2c8c43c7e%40googlegroups.com
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

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


Re: Rendering TabuarInline inside ModelAdmin without a foreign key

I did not produce the original model so I wouldn't know. My thinking is
that the order model had to be independent of the user model so that the
deletion of the user doesn't cascade down to orders. It's a mezzanine site
and that's how it handles fk from orders to users.
On 29/10/2014 9:27 pm, "Daniel Roseman"  wrote:

> On Wednesday, 29 October 2014 03:57:36 UTC, somecallitblues wrote:
>>
>> Hi list,
>>
>> I have a table of orders where one of the columns is a IntegerField
>> containing the id of a user who created the order.
>>
>> Since it's not a FK field django admin can't display these orders inline
>> inside the user details page.
>>
>> I would normally use something like:
>>
>> class OrderInline(admin.TabularInline):
>> extra = 0
>> model = Order
>>
>> And then add that to the user model like this:
>>
>> inlines = [OrderInline]
>>
>> But it won't work without the FK.
>>
>> I've Googled around and tried everything I found on SO but I can't figure
>> out how to add orders inline to my user model.
>>
>> I'm looking at https://docs.djangoproject.com/en/dev/_modules/django/
>> contrib/contenttypes/admin/#GenericTabularInline and I'm thinking do I
>> need to write a similar class or is there something easy and simple I'm
>> missing.
>>
>> Cheers,
>>
>> Mario
>>
>>
>>
> You don't show your models, but why is it not a ForeignKey? After all, a
> FK field is exactly what you describe, an integer field that contains the
> ID of the model it is pointing to. So why not declare it as one?
> --
> DR.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/fc21c60e-5a33-4e10-9f48-42c2c8c43c7e%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


Re: Rendering TabuarInline inside ModelAdmin without a foreign key

On Wednesday, 29 October 2014 03:57:36 UTC, somecallitblues wrote:
>
> Hi list,
>
> I have a table of orders where one of the columns is a IntegerField 
> containing the id of a user who created the order. 
>
> Since it's not a FK field django admin can't display these orders inline 
> inside the user details page.
>
> I would normally use something like:
>
> class OrderInline(admin.TabularInline):
> extra = 0
> model = Order
>
> And then add that to the user model like this:
>
> inlines = [OrderInline]
>
> But it won't work without the FK.
>
> I've Googled around and tried everything I found on SO but I can't figure 
> out how to add orders inline to my user model.
>
> I'm looking at 
> https://docs.djangoproject.com/en/dev/_modules/django/contrib/contenttypes/admin/#GenericTabularInline
>  
> and I'm thinking do I need to write a similar class or is there something 
> easy and simple I'm missing.
>
> Cheers,
>
> Mario
>
>
>
You don't show your models, but why is it not a ForeignKey? After all, a FK 
field is exactly what you describe, an integer field that contains the ID 
of the model it is pointing to. So why not declare it as one?
--
DR. 

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


Rendering TabuarInline inside ModelAdmin without a foreign key

Hi list,

I have a table of orders where one of the columns is a IntegerField
containing the id of a user who created the order.

Since it's not a FK field django admin can't display these orders inline
inside the user details page.

I would normally use something like:

class OrderInline(admin.TabularInline):
extra = 0
model = Order

And then add that to the user model like this:

inlines = [OrderInline]

But it won't work without the FK.

I've Googled around and tried everything I found on SO but I can't figure
out how to add orders inline to my user model.

I'm looking at
https://docs.djangoproject.com/en/dev/_modules/django/contrib/contenttypes/admin/#GenericTabularInline
and I'm thinking do I need to write a similar class or is there something
easy and simple I'm missing.

Cheers,

Mario

-- 
You received this message because you are subscribed to the Google Groups 
"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/CAHqTbjkzDTZ54v1-uZPTdTSgApQTnySKGAvZ%2BzZjqH0g4fUB%3DA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: FieldError with ManyToMany relationship in ModelAdmin list_display item when server is not in DEBUG mode

Hi,
Have you had any solutions to this yet?

-- 
You received this message because you are subscribed to the Google Groups 
"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/99c094c5-66dc-4c89-a378-be9fad2db1e6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: admin.py: putting "if condition" in ModelAdmin according to username

In the ModelAdmin I use a get_form() to test for conditions on the object.
Specifically, if this item has been published then make it read_only.  You
should be able to test for users as well.

I had to add the try/except in order to add new objects because
obj.published doesn't exist on a new object.

See:
https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form


Here is a snippet:
def get_form(self, request, obj=None, **kwargs):
try:
if obj.published:
self.readonly_fields =
['prj_name','published','schema_code','data_name','description','sem_attr','resource_uri','asserts',

'simple_units','coded_units','normal_status','reference_ranges','min_inclusive','max_inclusive',

'min_exclusive','max_exclusive','total_digits','fraction_digits','magnitude','error','accuracy','magnitude_status',]
except (AttributeError, TypeError) as e:
self.readonly_fields = ['published','schema_code']
return super(DvQuantityAdmin, self).get_form(request, obj, **kwargs)



On Wed, Oct 9, 2013 at 11:06 AM, Victor <vdem...@gmail.com> wrote:

> Yes, I know but unfortunately if in Admin Site you say that a user cannot
> Add, Delete, and Modify a model if that user is connected he/she doesn't
> see the model itself in the list but only those models for which it has
> some kind of permission. I instead would like to make the model visible but
> not editable for that user.
>
> Ciao
> Vittorio
>
> Il giorno 09/ott/2013, alle ore 14:14, Rafael E. Ferrero ha scritto:
>
> > In Admin Site, you can manage users permissions for Add, Delete, Modify
> of every model on your site.
> >
> >
> > 2013/10/9 Vittorio <ml-...@de-martino.it>
> > For the sake of simplicity let's suppose I have
> >
> > models.py
> >
> > class Book(models.Model):
> > title = models.CharField(max_length=100)
> > authors = models.ManyToManyField(Author)
> > publisher = models.ForeignKey(Publisher)
> >
> > Under admin I would like that some username (say "vic" and  "lucky") can
> edit every field of the change form while other users ("tom","sue") can
> only visualize the same data without modification.  I think to put some "if
> condition" in admin.py of this kind
> >
> >
> > class BookOption(admin.ModelAdmin):
> >if username  in ["tom", "sue"]:
> > readonly_fields = ['title','authors','publisher']
> > fields=(('title'),('authors', 'publisher'))..
> > .
> >admin.site.register(Book,BookOption)
> >
> >
> > How can I do it?
> >
> > Ciao
> > Vittorio
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "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/F0A087D2-8E11-4B0B-8D95-6FC131854994%40de-martino.it
> .
> > For more options, visit https://groups.google.com/groups/opt_out.
> >
> >
> >
> > --
> > Rafael E. Ferrero
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "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/CAJJc_8U3EbZXHVSucFndA25V%3DuYyen%3DGgUsyHmzLncD5DuGi2w%40mail.gmail.com
> .
> > For more options, visit https://groups.google.com/groups/opt_out.
>
> --
> You received this message because you are subscribed to the Google Groups
> "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/B4D514E2-7FA0-4CB3-A83E-82442A8DAFC6%40gmail.com
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>



-- 
MLHIM VIP Signup: http://goo

Re: admin.py: putting "if condition" in ModelAdmin according to username

It's easy, if you don't insist on making it part of the admin, to do this
with a custom view.  It can pay attention to whatever permissions you like.


On Wed, Oct 9, 2013 at 10:06 AM, Victor  wrote:

> Yes, I know but unfortunately if in Admin Site you say that a user cannot
> Add, Delete, and Modify a model if that user is connected he/she doesn't
> see the model itself in the list but only those models for which it has
> some kind of permission. I instead would like to make the model visible but
> not editable for that user.
>
> Ciao
> Vittorio
>
> Il giorno 09/ott/2013, alle ore 14:14, Rafael E. Ferrero ha scritto:
>
> > In Admin Site, you can manage users permissions for Add, Delete, Modify
> of every model on your site.
> >
> >
> > 2013/10/9 Vittorio 
> > For the sake of simplicity let's suppose I have
> >
> > models.py
> >
> > class Book(models.Model):
> > title = models.CharField(max_length=100)
> > authors = models.ManyToManyField(Author)
> > publisher = models.ForeignKey(Publisher)
> >
> > Under admin I would like that some username (say "vic" and  "lucky") can
> edit every field of the change form while other users ("tom","sue") can
> only visualize the same data without modification.  I think to put some "if
> condition" in admin.py of this kind
> >
> >
> > class BookOption(admin.ModelAdmin):
> >if username  in ["tom", "sue"]:
> > readonly_fields = ['title','authors','publisher']
> > fields=(('title'),('authors', 'publisher'))..
> > .
> >admin.site.register(Book,BookOption)
> >
> >
> > How can I do it?
> >
> > Ciao
> > Vittorio
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "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/F0A087D2-8E11-4B0B-8D95-6FC131854994%40de-martino.it
> .
> > For more options, visit https://groups.google.com/groups/opt_out.
> >
> >
> >
> > --
> > Rafael E. Ferrero
> >
> > --
> > You received this message because you are subscribed to the Google
> Groups "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/CAJJc_8U3EbZXHVSucFndA25V%3DuYyen%3DGgUsyHmzLncD5DuGi2w%40mail.gmail.com
> .
> > For more options, visit https://groups.google.com/groups/opt_out.
>
> --
> You received this message because you are subscribed to the Google Groups
> "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/B4D514E2-7FA0-4CB3-A83E-82442A8DAFC6%40gmail.com
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>

-- 
You received this message because you are subscribed to the Google Groups 
"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/CAB%2BAj0sAgp3NPgROdd4-ZuarKNGSe723Pon3aZA%2Bm1TqzGx5eg%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: admin.py: putting "if condition" in ModelAdmin according to username

Yes, I know but unfortunately if in Admin Site you say that a user cannot Add, 
Delete, and Modify a model if that user is connected he/she doesn't see the 
model itself in the list but only those models for which it has some kind of 
permission. I instead would like to make the model visible but not editable for 
that user.

Ciao
Vittorio 

Il giorno 09/ott/2013, alle ore 14:14, Rafael E. Ferrero ha scritto:

> In Admin Site, you can manage users permissions for Add, Delete, Modify of 
> every model on your site.
> 
> 
> 2013/10/9 Vittorio 
> For the sake of simplicity let's suppose I have
> 
> models.py
> 
> class Book(models.Model):
> title = models.CharField(max_length=100)
> authors = models.ManyToManyField(Author)
> publisher = models.ForeignKey(Publisher)
> 
> Under admin I would like that some username (say "vic" and  "lucky") can edit 
> every field of the change form while other users ("tom","sue") can only 
> visualize the same data without modification.  I think to put some "if 
> condition" in admin.py of this kind
> 
> 
> class BookOption(admin.ModelAdmin):
>if username  in ["tom", "sue"]:
> readonly_fields = ['title','authors','publisher']
> fields=(('title'),('authors', 'publisher'))..
> .
>admin.site.register(Book,BookOption)
> 
> 
> How can I do it?
> 
> Ciao
> Vittorio
> 
> --
> You received this message because you are subscribed to the Google Groups 
> "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/F0A087D2-8E11-4B0B-8D95-6FC131854994%40de-martino.it.
> For more options, visit https://groups.google.com/groups/opt_out.
> 
> 
> 
> -- 
> Rafael E. Ferrero
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "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/CAJJc_8U3EbZXHVSucFndA25V%3DuYyen%3DGgUsyHmzLncD5DuGi2w%40mail.gmail.com.
> For more options, visit https://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups 
"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/B4D514E2-7FA0-4CB3-A83E-82442A8DAFC6%40gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


Re: admin.py: putting "if condition" in ModelAdmin according to username

In Admin Site, you can manage users permissions for Add, Delete, Modify of
every model on your site.


2013/10/9 Vittorio 

> For the sake of simplicity let's suppose I have
>
> models.py
>
> class Book(models.Model):
> title = models.CharField(max_length=100)
> authors = models.ManyToManyField(Author)
> publisher = models.ForeignKey(Publisher)
>
> Under admin I would like that some username (say "vic" and  "lucky") can
> edit every field of the change form while other users ("tom","sue") can
> only visualize the same data without modification.  I think to put some "if
> condition" in admin.py of this kind
>
>
> class BookOption(admin.ModelAdmin):
>if username  in ["tom", "sue"]:
> readonly_fields = ['title','authors','publisher']
> fields=(('title'),('authors', 'publisher'))..
> .
>admin.site.register(Book,BookOption)
>
>
> How can I do it?
>
> Ciao
> Vittorio
>
> --
> You received this message because you are subscribed to the Google Groups
> "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/F0A087D2-8E11-4B0B-8D95-6FC131854994%40de-martino.it
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>



-- 
Rafael E. Ferrero

-- 
You received this message because you are subscribed to the Google Groups 
"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/CAJJc_8U3EbZXHVSucFndA25V%3DuYyen%3DGgUsyHmzLncD5DuGi2w%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.


admin.py: putting "if condition" in ModelAdmin according to username

For the sake of simplicity let's suppose I have

models.py

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)

Under admin I would like that some username (say "vic" and  "lucky") can edit 
every field of the change form while other users ("tom","sue") can only 
visualize the same data without modification.  I think to put some "if 
condition" in admin.py of this kind


class BookOption(admin.ModelAdmin):
   if username  in ["tom", "sue"]:
readonly_fields = ['title','authors','publisher']
fields=(('title'),('authors', 'publisher'))..
.
   admin.site.register(Book,BookOption)


How can I do it?

Ciao
Vittorio

-- 
You received this message because you are subscribed to the Google Groups 
"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/F0A087D2-8E11-4B0B-8D95-6FC131854994%40de-martino.it.
For more options, visit https://groups.google.com/groups/opt_out.


FieldError with ManyToMany relationship in ModelAdmin list_display item when server is not in DEBUG mode

I can not for the life of me figure out why my list_display works when the 
django server is in DEBUG=True but not when it is in DEBUG=False. I am 
using Django 1.4.3 (mod_wsgi 3.4/Python 2.7) 


 Here is the partial stack trace...


  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/manager.py", 
line 116, in all
return self.get_query_set()

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/fields/related.py",
 
line 565, in get_query_set
return super(ManyRelatedManager, self).get_query_set().using(
db)._next_is_sticky().filter(**self.core_filters)

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/query.py", 
line 624, in filter
return self._filter_or_exclude(False, *args, **kwargs)

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/query.py", 
line 642, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/sql/query.py", 
line 1250, in add_q
can_reuse=used_aliases, force_having=force_having)

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/sql/query.py", 
line 1122, in add_filter
process_extras=process_extras)

  File 
"/home/difuzi0n/webapps/wedding/lib/python2.7/django/db/models/sql/query.py", 
line 1316, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))

*FieldError: Cannot resolve keyword 'rsvp_guests' into field. Choices are: 
city, event, first_name, id, last_name, state, street, zip_code*

My models looks as follows...

class Guest(models.Model):
first_name = models.CharField(max_length=50,
  help_text="The Guest's given name.")
last_name = models.CharField(max_length=50,
 help_text="The Guest's surname.")
 ...
def __unicode__(self):
return u'{} {}'.format(self.first_name, self.last_name)

class RSVP(models.Model):
event = models.ForeignKey(Event, verbose_name='RSVP Event')
guests = models.ManyToManyField(Guest, verbose_name='Guests',
related_name='rsvp_guests',
limit_choices_to = { 'id__in': 
Event.objects.all().values('guests').query })
...

and the admin.py entry looks like so:

def guest_names(obj):
   return u', '.join([unicode(guest) for guest in obj.guests.all()])

class RSVPAdmin(admin.ModelAdmin):
list_display = ['event', guest_names, 'max_invites', 'response',
'response_datetime', 'updated_by']
filter_horizontal = ('guests', )


thanks, in advance, for your help!!!

/Eric

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




Re: a way to display a model formset in a ModelAdmin ?

>
>
> Create New adminmodel class and define fieldsets... For example
> http://www.f2finterview.com/web/Django/22/ it is clearly explain you
>
>
Hi Stephen, thanks for the reply, but it doesn't solve it since every field
specified
in the fieldset at the Model admin needs to either exist in Model or in the
ModelForm,
and since the number of Images that I want to display is variable (let's
say between 1 and N)
I can't have N Image fields at the form, what I need is somewhat of a field
that spawns
into multiple fields based on the amount of images that I want to display.
I'm starting
to think that maybe using a many-to-many field with a custom widget might
do the job.


> On Thu, Oct 25, 2012 at 3:51 AM, Nicolas Emiliani <or3s...@gmail.com>wrote:
>
>> Hi,
>>
>> As the subject states, is there a way to display a model formset in a
>> ModelForm?
>>
>> The thing is that I have a Verification model with its ModelAdmin, and
>> then I have
>> an ImageModel that has no ForeignKey to the Verification model (and I
>> intend to keep
>> it that way) so I can not inline it into the VerificationAdmin and I
>> would like to show
>> a list of Images in my VerificationAdmin based on a queryset performed (i
>> assume) at
>> __init__ method of VerificationAdminForm. How could this be accomplished?
>>
>> This is how it goes:
>>
>> class Image(models.Model):
>>
>>
>> class Verification(models.Model):
>>
>>
>> class VerificationAdminForm(forms.ModelForm):
>>
>>
>> class VerificationAdmin(admin.ModelAdmin):
>>form = VerificationAdminForm
>>model = Verification
>>fieldsets = [ ... ]
>>
>> Any ideas would be greatly appreciated.
>>
>> Thanks in advance.
>>
>> --
>> Nicolas Emiliani
>>
>> Lo unico instantaneo en la vida es el cafe, y es bien feo.
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To post to this group, send email to django-users@googlegroups.com.
>> To unsubscribe from this group, send email to
>> django-users+unsubscr...@googlegroups.com.
>> For more options, visit this group at
>> http://groups.google.com/group/django-users?hl=en.
>>
>
>
>
> --
> Thanks & Regards
> Stephen S
>
>
>
> Website: www.f2finterview.com
> Blog:  blog.f2finterview.com
> Tutorial:  tutorial.f2finterview.com
> Group:www.charvigroups.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.
>



-- 
Nicolas Emiliani

Lo unico instantaneo en la vida es el cafe, y es bien feo.

-- 
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: a way to display a model formset in a ModelAdmin ?

Hi,

Create New adminmodel class and define fieldsets... For example
http://www.f2finterview.com/web/Django/22/ it is clearly explain you

On Thu, Oct 25, 2012 at 3:51 AM, Nicolas Emiliani <or3s...@gmail.com> wrote:

> Hi,
>
> As the subject states, is there a way to display a model formset in a
> ModelForm?
>
> The thing is that I have a Verification model with its ModelAdmin, and
> then I have
> an ImageModel that has no ForeignKey to the Verification model (and I
> intend to keep
> it that way) so I can not inline it into the VerificationAdmin and I would
> like to show
> a list of Images in my VerificationAdmin based on a queryset performed (i
> assume) at
> __init__ method of VerificationAdminForm. How could this be accomplished?
>
> This is how it goes:
>
> class Image(models.Model):
>
>
> class Verification(models.Model):
>
>
> class VerificationAdminForm(forms.ModelForm):
>
>
> class VerificationAdmin(admin.ModelAdmin):
>form = VerificationAdminForm
>model = Verification
>fieldsets = [ ... ]
>
> Any ideas would be greatly appreciated.
>
> Thanks in advance.
>
> --
> Nicolas Emiliani
>
> Lo unico instantaneo en la vida es el cafe, y es bien feo.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>



-- 
Thanks & Regards
Stephen S



Website: www.f2finterview.com
Blog:  blog.f2finterview.com
Tutorial:  tutorial.f2finterview.com
Group:www.charvigroups.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.



a way to display a model formset in a ModelAdmin ?

Hi,

As the subject states, is there a way to display a model formset in a
ModelForm?

The thing is that I have a Verification model with its ModelAdmin, and then
I have
an ImageModel that has no ForeignKey to the Verification model (and I
intend to keep
it that way) so I can not inline it into the VerificationAdmin and I would
like to show
a list of Images in my VerificationAdmin based on a queryset performed (i
assume) at
__init__ method of VerificationAdminForm. How could this be accomplished?

This is how it goes:

class Image(models.Model):
   

class Verification(models.Model):
   

class VerificationAdminForm(forms.ModelForm):
   

class VerificationAdmin(admin.ModelAdmin):
   form = VerificationAdminForm
   model = Verification
   fieldsets = [ ... ]

Any ideas would be greatly appreciated.

Thanks in advance.

-- 
Nicolas Emiliani

Lo unico instantaneo en la vida es el cafe, y es bien feo.

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



Calculated attributes of ModelAdmin classes

I have a ModelAdmin class. 

Sometimes, I want it to include a certain field in the fieldsets, and sometimes 
I don't (whether it does or not would be the result of a calculation on the 
instance that is being edited in the admin). 

How can I make the fieldsets attribute a calculated value, calculated each time 
a different instance is loaded in the admin?

Another example: I might want a certain field to be a readonly_field - 
sometimes.

Is this possible? 

I have a feeling it won't be, because:

*   attributes like fieldsets and readonly_fields are set up in the __init__()
*   once set up, they don't seem modifiable
*   the __init__() doesn't have access to the instance, so use that to 
determine the attributes

Daniele

-- 
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: dynamic fildsets on ModelAdmin

On Sun, Aug 5, 2012 at 5:40 PM, Melvyn Sopacua <m.r.sopa...@gmail.com>wrote:

> On 5-8-2012 20:16, Nicolas Emiliani wrote:
> > Hi, I've been struggling with dynamic forms and until now I'm loosing the
> > battle :S
>
> > So, now I want the HomeAdmin to render all this stuff into the from, but
> > when I try to
> > add this fields into the fieldset attribute and load the page it fails
> > saying.
>
> Sorry to say this, but you have to go back to the drawing board. You
> cannot add random fields to fieldset. They *have* to be models.Field
> classes of the model attached the ModelAdmin so that the values get
> cleaned properly.
> If you want extra fields for the form, you do this via inlines for
> related objects or you subclass a ModelForm and set the form attribute
> of the ModelAdmin.
>
>
Ups. Well, thanks anyways. Since my drawing board is full of drawings,
and they are not happy faces, I'll create another post with what I want
to accomplish and maybe you can suggest something.



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


-- 
Nicolas Emiliani

Lo unico instantaneo en la vida es el cafe, y es bien feo.

-- 
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: dynamic fildsets on ModelAdmin

On 5-8-2012 20:16, Nicolas Emiliani wrote:
> Hi, I've been struggling with dynamic forms and until now I'm loosing the
> battle :S

> So, now I want the HomeAdmin to render all this stuff into the from, but
> when I try to
> add this fields into the fieldset attribute and load the page it fails
> saying.

Sorry to say this, but you have to go back to the drawing board. You
cannot add random fields to fieldset. They *have* to be models.Field
classes of the model attached the ModelAdmin so that the values get
cleaned properly.
If you want extra fields for the form, you do this via inlines for
related objects or you subclass a ModelForm and set the form attribute
of the ModelAdmin.

-- 
Melvyn Sopacua

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



dynamic fildsets on ModelAdmin

Hi, I've been struggling with dynamic forms and until now I'm loosing the
battle :S
The thing is that I have a HomeAdmin(ModelAdmin) that uses the form
HomeAdminForm(ModelForm)

The HomeAdminForm redefines the __init__ method to add a bunch a of hidden
input fields like this :

class HomeAdminForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
super(HomeAdminForm, self).__init__(*args, **kwargs)
#add all the attribute types
for at in HomeAttrType.objects.all():
self.fields['attr_type_%s' % at.name] = forms.CharField(
 widget=forms.HiddenInput(attrs={'class': 'hidden'}),
label='', bound=True)


So, now I want the HomeAdmin to render all this stuff into the from, but
when I try to
add this fields into the fieldset attribute and load the page it fails
saying.

Unknown field(s) (attr_type_foo, attr_type_prueba, attr_type_carnasa)
specified for Home


Those fields are the ones I added at HomeAdminForm.__init__ this way

class HomeAdmin(admin.ModelAdmin):

form = HomeAdminForm

def __init__(self, *args, **kwargs):
super(HomeAdmin, self).__init__(*args, **kwargs)
hidden_fields = []
for at in HomeAttrType.objects.all():
hidden_fields.append('attr_type_%s' % at.name)
self.fieldsets.append((None, {'fields' : hidden_fields, }))

The problem seems to be that the constructor for HomeAdminForm gets called
after
the constructor for HomeAdmin, so all the added fields are not there yet
when
HomeAdmin.__init__ is called.

Is what I'm trying do ok ?,  Is there any way to fix this ?

Thanks dudes,

-- 
Nicolas Emiliani

Lo unico instantaneo en la vida es el cafe, y es bien feo.

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



Adding Checkbox in ModelAdmin

Hello,

i have a little question which i could'nt answer myself reading the 
documentation.

i'm trying to modify the modelAdmin of my "Picture"-model
this is what i'm trying to do:


class PictureAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
# if mycheckbox = checked:
# obj.save_with_xmp()
# else:
# obj.save()
pass

So i'm wondering how i can add a checkbox to my ModelAdmin form which i can 
use.
The checkbox should only be a control element but no part of the database 
model.

-- 
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/-/PYhiflt-QvUJ.
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 render a modeladmin dynamically?

In a view, I need to get a modeladmin for a model provided
dynamically, change some of the attributes  of the modeladmin ( add an
aggregated field to the queryset, order the queryset by that field and
add a column for that new field in the list_display of the modeladmin
) and render the request using a custom template extending the normal
change_list template. I cannot add these things to the modeladmin of
the models in question, it has to be done at runtime.

-- 
Mvh/Best regards,
Thomas Weholt
http://www.weholt.org

-- 
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: Accessing request.user in a ModelAdmin function

Hi Alireza,

Yes, that did the trick!

Thank you,
Paulo

On Thursday, June 14, 2012 2:26:46 PM UTC+1, Alireza Savand wrote:
>
>
>
> On Thursday, June 14, 2012 3:04:54 PM UTC+4, Paulo Almeida wrote:
>>
>> Hi,
>>
>> I would like to access the request.user in a ModelAdmin function, so I 
>> can filter the results of a query based on the logged in user. I have these 
>> models:
>>
>> class Speaker(models.Model):
>> name = models.CharField(max_length=50)
>> endorsements = models.ManyToManyField(User,
>>
>>  through="Endorsement")
>>
>> class Endorsement(models.Model):
>> speaker = models.ForeignKey('Speaker')
>> user = models.ForeignKey(User)
>> endorsed = models.NullBooleanField()
>>
>> class Meta:
>> unique_together = ("speaker", "user")
>>
>> User comes from django.contrib.auth.models. In the ModelAdmin, I would 
>> like to have this:
>>
>> class SpeakerAdmin(admin.ModelAdmin):
>> def is_endorsed(self, obj):
>> 
>> endorsement = Endorsement.objects.get(speaker=obj,
>>   
>> user=request.user)
>> return endorsement.endorsed
>>
>> So then I could just add "is_endorsed" to the list_display variable to 
>> have the endorsement status for that user in the Speaker list, in the Admin 
>> site. Of course, this doesn't work because request isn't available in the 
>> is_endorsed function. I googled around and saw solutions for similar 
>> problems involving overrides of save_model, queryset or 
>> formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> because I'm creating a function in the ModelAdmin, where I only know how to 
>> pass self and obj. Suggestions?
>>
>> Thanks,
>> Paulo Almeida
>>
>
> I think you looking for this app
> http://pypi.python.org/pypi/django-cuser/
>
> Small piece of middleware to be able to access authentication data from
>  everywhere in the django code.
>
>
> Right ?
>
>
On Thursday, June 14, 2012 2:26:46 PM UTC+1, Alireza Savand wrote:
>
>
>
> On Thursday, June 14, 2012 3:04:54 PM UTC+4, Paulo Almeida wrote:
>>
>> Hi,
>>
>> I would like to access the request.user in a ModelAdmin function, so I 
>> can filter the results of a query based on the logged in user. I have these 
>> models:
>>
>> class Speaker(models.Model):
>> name = models.CharField(max_length=50)
>> endorsements = models.ManyToManyField(User,
>>
>>  through="Endorsement")
>>
>> class Endorsement(models.Model):
>> speaker = models.ForeignKey('Speaker')
>> user = models.ForeignKey(User)
>> endorsed = models.NullBooleanField()
>>
>> class Meta:
>> unique_together = ("speaker", "user")
>>
>> User comes from django.contrib.auth.models. In the ModelAdmin, I would 
>> like to have this:
>>
>> class SpeakerAdmin(admin.ModelAdmin):
>> def is_endorsed(self, obj):
>> 
>> endorsement = Endorsement.objects.get(speaker=obj,
>>   
>> user=request.user)
>> return endorsement.endorsed
>>
>> So then I could just add "is_endorsed" to the list_display variable to 
>> have the endorsement status for that user in the Speaker list, in the Admin 
>> site. Of course, this doesn't work because request isn't available in the 
>> is_endorsed function. I googled around and saw solutions for similar 
>> problems involving overrides of save_model, queryset or 
>> formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> because I'm creating a function in the ModelAdmin, where I only know how to 
>> pass self and obj. Suggestions?
>>
>> Thanks,
>> Paulo Almeida
>>
>
> I think you looking for this app
> http://pypi.python.org/pypi/django-cuser/
>
> Small piece of middleware to be able to access authentication data from
>  everywhere in the django code.
>
>
> Right ?
>
>

-- 
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/-/yJUcQhE-278J.
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: Accessing request.user in a ModelAdmin function


And if it's just for logged-in user, you can
do like
https://gist.github.com/2930287
at the ModelAdmin

-- 
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/-/mxxG2VwgMeMJ.
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: Accessing request.user in a ModelAdmin function



On Thursday, June 14, 2012 3:04:54 PM UTC+4, Paulo Almeida wrote:
>
> Hi,
>
> I would like to access the request.user in a ModelAdmin function, so I can 
> filter the results of a query based on the logged in user. I have these 
> models:
>
> class Speaker(models.Model):
> name = models.CharField(max_length=50)
> endorsements = models.ManyToManyField(User,
>
>  through="Endorsement")
>
> class Endorsement(models.Model):
> speaker = models.ForeignKey('Speaker')
> user = models.ForeignKey(User)
> endorsed = models.NullBooleanField()
>
> class Meta:
> unique_together = ("speaker", "user")
>
> User comes from django.contrib.auth.models. In the ModelAdmin, I would 
> like to have this:
>
> class SpeakerAdmin(admin.ModelAdmin):
> def is_endorsed(self, obj):
> 
> endorsement = Endorsement.objects.get(speaker=obj,
>   
> user=request.user)
> return endorsement.endorsed
>
> So then I could just add "is_endorsed" to the list_display variable to 
> have the endorsement status for that user in the Speaker list, in the Admin 
> site. Of course, this doesn't work because request isn't available in the 
> is_endorsed function. I googled around and saw solutions for similar 
> problems involving overrides of save_model, queryset or 
> formfield_for_manytomany, but I couldn't adapt them to list_display, 
> because I'm creating a function in the ModelAdmin, where I only know how to 
> pass self and obj. Suggestions?
>
> Thanks,
> Paulo Almeida
>

I think you looking for this app
http://pypi.python.org/pypi/django-cuser/

Small piece of middleware to be able to access authentication data from
 everywhere in the django code.


Right ?

-- 
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/-/7zNoE-as3asJ.
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: Accessing request.user in a ModelAdmin function

Hi again,

>From what I read in the 1.4 docs, the SimpleListFilter example is for 
list_filter and not list_display. To clarify what I wrote before, if a user 
endorses Speaker A and opposes Speaker B, I want the Speaker list in the 
admin site to show:

|Name | Is endorsed |
|A   | True|
|B   |  False |

Having a filter on "Is Endorsed" might be a nice addition, but the main 
goal is to have that table. Would there be a way to get the result of a 
SimpleListFilter into a callable that can be used in list_display? I didn't 
see that in the docs, and it's not obvious to me how to do it.

Thanks,
Paulo

On Thursday, June 14, 2012 1:09:58 PM UTC+1, Paulo Almeida wrote:
>
> Hi Melvyn,
>
> I've only been reading the Django 1.2 docs, because it's what's 
> immediately available in my Linux distribution, but that would be an 
> excellent reason to upgrade, if I can get it to work. 
>
> Thanks,
> Paulo
>
> On Thursday, June 14, 2012 12:33:34 PM UTC+1, Melvyn Sopacua wrote:
>>
>> On 14-6-2012 13:04, Paulo Almeida wrote: 
>>
>> > So then I could just add "is_endorsed" to the list_display variable to 
>> have 
>> > the endorsement status for that user in the Speaker list, in the Admin 
>> > site. Of course, this doesn't work because request isn't available in 
>> the 
>> > is_endorsed function. I googled around and saw solutions for similar 
>> > problems involving overrides of save_model, queryset or 
>> > formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> > because I'm creating a function in the ModelAdmin, where I only know 
>> how to 
>> > pass self and obj. Suggestions? 
>>
>> In 1.4 you have ModelAdmin.list_filter and can subclass 
>> SimpleListFilter. These get passed the request and the documentation 
>> provides a full example of what you're trying to do. 
>>
>> -- 
>> Melvyn Sopacua 
>>
>

-- 
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/-/xXv1KzZUaYUJ.
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: Accessing request.user in a ModelAdmin function

Hi Melvyn,

I've only been reading the Django 1.2 docs, because it's what's immediately 
available in my Linux distribution, but that would be an excellent reason 
to upgrade, if I can get it to work. 

Thanks,
Paulo

On Thursday, June 14, 2012 12:33:34 PM UTC+1, Melvyn Sopacua wrote:
>
> On 14-6-2012 13:04, Paulo Almeida wrote: 
>
> > So then I could just add "is_endorsed" to the list_display variable to 
> have 
> > the endorsement status for that user in the Speaker list, in the Admin 
> > site. Of course, this doesn't work because request isn't available in 
> the 
> > is_endorsed function. I googled around and saw solutions for similar 
> > problems involving overrides of save_model, queryset or 
> > formfield_for_manytomany, but I couldn't adapt them to list_display, 
> > because I'm creating a function in the ModelAdmin, where I only know how 
> to 
> > pass self and obj. Suggestions? 
>
> In 1.4 you have ModelAdmin.list_filter and can subclass 
> SimpleListFilter. These get passed the request and the documentation 
> provides a full example of what you're trying to do. 
>
> -- 
> Melvyn Sopacua 
>

-- 
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/-/VGhuIwcMj9sJ.
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: Accessing request.user in a ModelAdmin function

On 14-6-2012 13:04, Paulo Almeida wrote:

> So then I could just add "is_endorsed" to the list_display variable to have 
> the endorsement status for that user in the Speaker list, in the Admin 
> site. Of course, this doesn't work because request isn't available in the 
> is_endorsed function. I googled around and saw solutions for similar 
> problems involving overrides of save_model, queryset or 
> formfield_for_manytomany, but I couldn't adapt them to list_display, 
> because I'm creating a function in the ModelAdmin, where I only know how to 
> pass self and obj. Suggestions?

In 1.4 you have ModelAdmin.list_filter and can subclass
SimpleListFilter. These get passed the request and the documentation
provides a full example of what you're trying to do.

-- 
Melvyn Sopacua

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



Accessing request.user in a ModelAdmin function

Hi,

I would like to access the request.user in a ModelAdmin function, so I can 
filter the results of a query based on the logged in user. I have these 
models:

class Speaker(models.Model):
name = models.CharField(max_length=50)
endorsements = models.ManyToManyField(User,
   
 through="Endorsement")

class Endorsement(models.Model):
speaker = models.ForeignKey('Speaker')
user = models.ForeignKey(User)
endorsed = models.NullBooleanField()

class Meta:
unique_together = ("speaker", "user")

User comes from django.contrib.auth.models. In the ModelAdmin, I would like 
to have this:

class SpeakerAdmin(admin.ModelAdmin):
def is_endorsed(self, obj):

endorsement = Endorsement.objects.get(speaker=obj,
  
user=request.user)
return endorsement.endorsed

So then I could just add "is_endorsed" to the list_display variable to have 
the endorsement status for that user in the Speaker list, in the Admin 
site. Of course, this doesn't work because request isn't available in the 
is_endorsed function. I googled around and saw solutions for similar 
problems involving overrides of save_model, queryset or 
formfield_for_manytomany, but I couldn't adapt them to list_display, 
because I'm creating a function in the ModelAdmin, where I only know how to 
pass self and obj. Suggestions?

Thanks,
Paulo Almeida

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



  1   2   3   >