tags:

views:

32

answers:

2

I have a form that I use to display several fields from a record to the user. However, the user should not be able to update all the fields that are displayed. How do I enforce this? It would nice if I could specify which fields to save when calling form.save, but I couldn't get this to work. Here's some of the code:

obj = get_object_or_404(Record, pk=record_id)
if request.method == 'POST':
    form = forms.RecordForm(request.POST, instance=obj)
    if form.is_valid():
        form.save()

I don't think using exclude or fields in the form's Meta definition will work as this will only display the fields the user is allowed to update.

+1  A: 

Option 1: exclude those fields, and use your template to display the data that should not be changed completely outside of the form itself. It sounds to me like they're not really part of the form, if the user can't change them.

Option 2: http://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be

take this answer to mark your fields as read only... but understand there's no server side security here, so you would want to do something like getting the target model before you update it, and update those offending form fields to the existing data, before you save the form.

andyortlieb
Thanks. I went with the option of displaying the read only fields from the object and only the editable ones via the form. I used form fields to ensure only the editable fields could be saved.
swisstony
+1  A: 

You can override the form's save() method:

class MyModelForm(forms.ModelForm):
    def save(self, commit=True):
        if self.instance.pk is None:
            fail_message = 'created'
        else:
            fail_message = 'changed'
        exclude = ['field_a', 'field_b'] #fields to exclude from saving
        return save_instance(self, self.instance, self._meta.fields,
                             fail_message, commit, construct=False,
                             exclude=exclude)
lazerscience
This looks very promising. However, I just couldn't get it to work. It continued to save the fields I put in exclude.
swisstony