I have following simplified setup:
A model based on legacy data which can't be changed. Therefore I raise a ValidationError to make the user aware that there was no change made. The form fields are readonly and I could use a simple 'pass' but I prefer to get the message that save() didn't do what it was intended to do instead of just do silently nothing.
Now I'm extending the legacy data with a 2nd model which should be editable. It is included it into the legacy model's ModelAdmin as inline. I could include the CommentModel itself as a ModelAdmin, but as the LegacyModel inherits lots of functionality from parent-classes this gets complicated and un-dry.
What I want is to perform the "save" operation only on the inline-model. I thought as all fields are readonly it should work fine. Can someone give me a hint to do this in clean way?
class Legacy(models.Model):
legacyData = models.TextField()
def clean(self):
raise ValidationError("%s model is readonly." % self._meta.verbose_name.capitalize())
class Comment(models.Model):
legacy = models.OneToOneField(Legacy)
comment = models.TextField()
class LegacyAdmin(admin.ModelAdmin):
def __init__(self, *args, **kwargs):
self.readonly_fields = self.fields
super(LegacyAdmin, self).__init__(*args, **kwargs)
model = Legacy
inlines = (CommentInline, )
Thanks a lot for your time! :)
Rather than raising an exception in clean(), you could override the legacy's save() and use http://docs.djangoproject.com/en/dev/ref/contrib/messages/ to tell your user what didn't happen.
Related
I'm using django admin and adding a TabularInline to my ModelAdmin class. Think Author and the inline is Books. How do I make some of those inlines appear read only and some appear editable based on certain characteristics of the model instance for each specific inline? Say I wanted all the books written before 2001 to be read only. And all the books written after that to be editable.
I've tried overriding has_change_permission() on the TablularInline and using the obj param, but it is receiving the parent and not the instance of this specific inline.
You have to override your inline form and check the value on the instance in the __init__().
Example:
class AuthorBookInlineForm(forms.ModelForm):
model = Book
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance and self.instance.created_ts.year <= 2001:
for f in self.fields:
self.fields[f].widget.attrs['readonly'] = 'readonly'
Don't forget to set the form value on your inline...
class AuthorBookInline(admin.TabularInline):
model = Book
form = AuthorBookInlineForm
extra = 0
I am learning django form and want to know how to make a model form generated display only.
models.py
class Person(models.Model):
first_name = models.CharField(max_length=40, null=True)
last_name = models.CharField(max_length=40, null=True)
#more fields
forms.py
class PersonForm(ModelForm):
class Meta:
model = Person
To generate a form with some existing data in the database:
person=Person.objects.get(id=someid)
person_form = PersonForm(instance = person)
All the fields in the form are editable in the page. However, I just want to display the data.
After some searching in StackOverflow I found a similar solution how to show a django ModelForm field as uneditable , which teaches how to set individual field uneidtable.
But I want to make the whole form uneditable. Is there any better way to do so instead of setting all the fields as uneditable one by one?
Thank you very much for your help.
Updates: I find the flowing code helps make the form uneditable, but still not sure whether this is the correct way to do it.
for field in person_form.fields:
person_form.fields[field].widget.attrs['readonly'] = True
Thank you for giving your advice.
There is no attribute called editable or something similar on the form which can act on all the fields. So, you can't do this at form level.
Also, there is no such attribute on Field class used by django forms as well, so it wouldn't be possible to set such attribute and make the field read only. So, you will have to operate on on the fields of the form in __init__ of your form.
class PersonForm(ModelForm):
class Meta:
model = Person
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
for name, field in self.fields.iteritems():
field.widget.attrs['readonly'] = 'true'
In case, you only want to make some fields uneditable, change the __init__.
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
uneditable_fields = ['first_name', 'last_name']
for field in uneditable_fields:
self.fields[field].widget.attrs['readonly'] = 'true'
Another solution perhaps, do not have to do any processing, just display like this..
<table border='1'>
{% for field in form%}
<tr>
<td>{{field.label}}</td>
<td>{{field.value}}</td>
</tr>
{% endfor%}
</table>
I know, old question, but since I had the same question this week it might help other people.
This technique only works if you want the whole form to be readonly. It overrides any posted data (see def clean(self)) and sets the widget attributes to readonly.
Note: Setting the widget attributes to readonly does not prevent altering the model object instance.
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
if self.is_readonly():
for k,f in self.fields.iteritems():
f.widget.attrs['readonly'] = True
def clean(self):
if self.is_readonly():
return {}
return super(CompanyQuestionUpdateForm, self).clean()
def is_readonly(self, question):
if your_condition:
return True
return False
class Meta:
model = MyModel
It is possible to implement field widget to render bound ModelForm field values wrapped into div or td, sample implementation is there
https://github.com/Dmitri-Sintsov/django-jinja-knockout/blob/master/django_jinja_knockout/widgets.py
# Read-only widget for existing models.
class DisplayText(Widget):
Then a form metaclass can be implemented which will set field widget to DisplayText for all ModelForm fields automatically like that:
https://github.com/Dmitri-Sintsov/djk-sample/search?utf8=%E2%9C%93&q=DisplayModelMetaclass
class ClubDisplayForm(BootstrapModelForm, metaclass=DisplayModelMetaclass):
class Meta(ClubForm.Meta):
widgets = {
'category': DisplayText()
}
Feel free to use or to develop your own versions of widget / form metaclass.
There was discussion about read-only ModelForms at django bug ticket:
https://code.djangoproject.com/ticket/17031
closed as "Froms are for processing data, not rendering it."
But I believe that is mistake for these reasons:
ModelForms are not just processing data, they also map forms to models. Read-only mapping is the subset of mapping.
There are inline formsets and having read-only inline formsets is even more convenient, it leaves a lot of burden from rendering relations manually.
Class-based views can share common templates to display and to edit ModelForms. Thus read-only display ModelForms increase DRY (one of the key Django principles).
I have a subclass of models.ForeignKey, the only purpose of which is to use a custom widget:
from django.db import models
from .models import Images
class GAEImageField(models.ForeignKey):
def __init__(self, **kwargs):
super(GAEImageField, self).__init__(Images, **kwargs)
def formfield(self, *args, **kwargs):
field = forms.ModelChoiceField(self, widget=ImageUploadWidget, *args, **kwargs)
field.queryset = Images.objects.all()
return field
The problem is, when I try to use this field, any parameters to __init__ are ignored. For instance, if I try this model:
class SomethingWithImage(models.Model):
name = models.CharField('Awesome name', max_length=64)
image = GAEImageField(verbose_name='Awesome image', blank=True)
...despite the fact I specified verbose_name, the label on a generated form will be "Image" and trying to specify empty value will raise an error even though I use blank=True
Well, the problem is with your formfield method. If you look at the implementation used in the default ForeignKey for example, you'll see it calls super. I'd recommend something like this:
def formfield(self, **kwargs):
defaults = {
'widget': ImageUploadWidget,
}
defaults.update(kwargs)
return super(GAEImageField, self).formfield(**defaults)
The problem is, form fields don't extract any information from model fields. Form fields can be used completely independently from models, they don't have to be necessarily backed by a model field. That means all settings, like whether the field is required or not, its label etc. have to be passed as parameters to their constructors. It is the responsibility of the model field to create an appropriate instance of a form field, all settings included. The default implementation of django.db.models.fields.Field.formfield takes care of that which is why you usually want to call the parent's method.
As for the blank issue, try also setting null=True, otherwise even though the form will accept a blank value, the database will reject it. Also, note that modifying the value of null after syncdb has been run requires a database migration.
Trying to save a bunch of objects but with a custom form:
class CustomForm(forms.ModelForm):
class Meta:
model = Widget
complexify = models.BooleanField()
When complexify is checked, i need to do some complex operations on the widget object.
I can't do:
for object in formset.save(commit=False):
...
because it won't have the complexify flag.
And going through each form seems to be the wrong way:
for form in formset.forms:
...
because it includes the extra (empty) forms and the deleted forms.
Any ideas on how to get this done?
The best answer i could find to this problem was overriding the save on the form:
class CustomForm(forms.ModelForm):
class Meta:
model = Widget
complexify = models.BooleanField()
def save(self, *args, **kwargs):
obj = super(CustomForm, self).save(*args, **kwargs)
obj.complexify = self.cleaned_data.get("complexify")
return obj
then it will be available for you when you handle them:
for object in formset.save(commit=False):
if object.complexify:
object.do_complicated()
I ran into a similar problem, needing to update a field in my forms before saving them. My solution was to do something like what you suggested above, but then skip over forms that hadn't been changed by using the method has_changed, like so:
for form in formset.forms:
object = form.save(commit=False)
if form.has_changed():
#make additions to object here
object.save()
I've never worked with the complexify flag, but your question seemed to run along the lines of my own problem, so I thought I'd pass the info along. Of course, if anyone sees anything that will lead to problems later with this approach, please let me know, I'm still a Django beginner.
How do I allow fields to be populated by the user at the time of object creation ("add" page) and then made read-only when accessed at "change" page?
The simplest solution I found was to override the get_readonly_fields function of ModelAdmin:
class TestAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
'''
Override to make certain fields readonly if this is a change request
'''
if obj is not None:
return self.readonly_fields + ('title',)
return self.readonly_fields
admin.site.register(TestModel, TestAdmin)
Object will be none for the add page, and an instance of your model for the change page.
Edit: Please note this was tested on Django==1.2
There's two thing to address in your question.
1. Read-only form fields
Doesn't exist as is in Django, but you can implement it yourself, and this blog post can help.
2. Different form for add/change
I guess you're looking for a solution in the admin site context (otherwise, just use 2 different forms in your views).
You could eventually override add_view or change_view in your ModelAdmin and use a different form in one of the view, but I'm afraid you will end up with an awful load of duplicated code.
Another solution I can think of, is a form that will modify its fields upon instantiation, when passed an instance parameter (ie: an edit case). Assuming you have a ReadOnlyField class, that would give you something like:
class MyModelAdminForm(forms.ModelForm):
class Meta:
model = Stuff
def __init__(self, *args, **kwargs):
super(MyModelAdminForm, self).__init__(*args, **kwargs)
if kwargs.get('instance') is not None:
self.fields['title'] = ReadOnlyField()
In here, the field title in the model Stuff will be read-only on the change page of the admin site, but editable on the creation form.
Hope that helps.
You can edit that model's save method to handle such a requirement. For example, you can check if the field already contains some value, if it does, ignore the new value.
One option is to override or replace the change_form template for that specific model.