Wednesday, March 6, 2013

Re: dynamic form fields in admin?

Hm, but you use 1 Form in save method. I need to show/hide/change Form while generating change view.
save() method is just to late for me.

On Thursday, March 7, 2013 1:51:36 AM UTC+1, Bulkan-Savun Evcimen wrote:
Hi,

I've done something similar just recently where I generate a "key" field in a ModelAdmin to display in django admin. 
 
from django  import forms
from django.contrib import admin
 
class MyForm(forms.ModelForm):
    key = forms.CharField(max_length=256)
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['key'].initial = self.instance.key

class MyModelAdmin(admin.ModelAdmin):
     form = MyForm
     def save(self, request, obj, form, change):
          # save
          if "key" in self.form.cleaned_data:
                del self.form.cleaned_data['key']
          super(MyModelAdmin, self).__init__(request, obj, form, change)
admin.site.register(MyModel, MyModelAdmin)


In the save method of MyModelAdmin you can do your logic that you have mentioned. 

Hope that helps




On Thu, Mar 7, 2013 at 3:43 AM, galgal <weglare...@gmail.com> wrote:

I want to make some advanced customization of admin form.

While editing an object, I want to show, dynamically, different fields depending of 1 obj field (they are not visible while adding the obj.). There can be a situation, to validate that extra fields. For example, when object has a 'temporary' type, I must show 2 fields with dates, and validate them. If object is 'renewable' I need to show 2 different fields with different validation.

What is the best approach to do that?

  • Make separate Form for each object type and set form attrib of ModelAdmin? If yes, in whichModelAdmin method do that (change_view()?)?
  • Dynamically update fields in get_form() method?

What is the best approach to do that?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
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+unsubscribe@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.
 
 

No comments:

Post a Comment