开发者

Django: Can I restrict which fields are saved back to the database using forms?

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.


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)


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: In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜