0

Say I have a model in which I have a class variable called documentation. I want to access the documentation class variable in the given models change form template. How can I do this? After the instance has been saved I can access the class variable in the template with {{original.documentation}}.

Example Model

class Person(models.Model):
    # How do I access this variable in my change form template 
    # before saving the new instace?
    documentation = "The Person model will be used for all staff including researchers, professors, and authors."

    first_name = models.CharField(max_length=255)

2 Answers 2

3

This can be done by updating Django view methods in the ModelAdmin class https://docs.djangoproject.com/en/dev/ref/contrib/admin/#other-methods.

def add_extra_context(model, kwargs):
        kwargs.setdefault("extra_context", {})
        kwargs["extra_context"]["documentation"] = model.__dict__.get('documentation','')


class DocumentableAdmin(admin.ModelAdmin):
    def add_view(self, *args, **kwargs):
        add_extra_context(self.model, kwargs)
        return super(DocumentableAdmin, self).add_view(*args, **kwargs)

    def changelist_view(self, *args, **kwargs):
        add_extra_context(self.model, kwargs)
        return super(DocumentableAdmin, self).changelist_view(*args, **kwargs)

    def change_view(self, *args, **kwargs):
        add_extra_context(self.model, kwargs)
        return super(DocumentableAdmin, self).change_view(*args, **kwargs)

admin.site.register(Person, DocumentableAdmin)

Now the documentation class variable defined in the model will be available in the change form admin template accessible using {{ documentation|safe }}

Sign up to request clarification or add additional context in comments.

Comments

0

You can use ModelForms for this. Create a form and refer that in your view like formname = forms.formname(). They you can display whole form using {formname} tag.

Its better to manipulate your variables in forms.py instead for templates. But you can access your variable in template if you want by defining a get_context_data(self, **kwargs) function in your view class like:

def get_context_data(self, **kwargs):
        context = super(view_name, self).get_context_data(**kwargs)
        context['model_field_list'] = Modelname.objects.get(pk=self.kwargs["modelname_pk"])
        return context

And now you can access your variables using {model_field_list.fieldname} tags in templates. Check the documentation on get_context_data function here: documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.