andermic
andermic

Reputation: 43

Django Form with extra information

I'm have a model that has some fields that should never be edited, such as "date created." I want to display a form that has some text fields with the extra information, probably just the data itself in a <span>. A person can edit a few fields and at the same time they can see the extra information about the instance of the model, such as created, last modified, or even related objects in the database for this object. Is there a way to do this using Django's built in framework, or will I have to create my own custom form by passing the whole object to a template?

If this needs more clarification, feel free to ask.

Upvotes: 2

Views: 3991

Answers (2)

forivall
forivall

Reputation: 9911

The best way I know to do this is to initialize the fields before you pass the form to the template by passing an initial dictionary to the form or by passing a instance object to the form.

You should then make sure that the fields are disabled, or you should make them hidden fields and then display the fields as regular text.

Most importantly, if you're passing data to the client that will then be sent back in a form, you should make sure that the data coming in is the same as the data that went out (for security's sake). Do this with at clean_[field] function on the Form. It should look like the following.

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def clean_date_created(self):
        if self.cleaned_fields['date_created'] != self.instance.date_created:
            raise ValidationError, 'date_created has been tampered'
        self.cleaned_fields['date_created']

[Edit/Addendum] Alternatively, you can pass the data directly to your template to render separately, and then tack on the data to your form after you get it back into your view. It should go something like this:

def recieve_form(request, ...):
    ...
    f = MyForm(request.POST, instance=a)
    new_model_instance = f.save(commit=False)
    new_model_instance.date_created = <whatever>
    new_model_instance.save()

Upvotes: 1

Claude Vedovini
Claude Vedovini

Reputation: 2481

To do that I usually customize the form in order for the widget to be read only, like the following:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'my_field': forms.TextInput(attrs={'disabled':'disabled'}),
        }

This will output a read only text field but I guess you can also create a Widget that will just output a <div> or a <p> (or whatever you need)

Upvotes: 1

Related Questions