2

In some of my models I have used the primary key defined by the system (Django) whereas in some others I have defined my own primary keys.

In the second instance (i.e. for models with custom primary keys), while updating / changing a record, I am able to show the primary key (as a readonly field) in the page being presented to the user (through a template). This is what I am unable to replicate for models with system defined primary key.

2
  • 1
    You can just reference the id in the template Commented Dec 28, 2019 at 20:36
  • Also include the relevant code for the second example where you want to display the primary key field. Commented Dec 28, 2019 at 20:40

1 Answer 1

0

If you want to display the primary key of a model instance, just use {{ your_model_instance.pk }} in your template.

3
  • Thanks . In my template I am looping through the form fields to display them. Where I need to, I capture the field name like {% if field.name == "<field_name>" %} {{ field }} {% endif %}. But somehow my code {% if field.name == "id" %} is NOT WORKING. If I use {{ <table_name>.id }} OR {{ <table_name>.pk }} OR even {{ form.instance.id }} without a conditional statement, I am able to display the model's "id". If I may ask, is there a way to capture the <field_name> for id so that I may use the existing for..loop without additional formatting of table field (using css).
    – Stop War
    Commented Dec 29, 2019 at 5:30
  • If your field is called id (which is not a good name for a field btw), you can try {% if field.id_for_label == id_id %} (or just print {{ field.id_for_label }} to see what you should set if it not id_id.
    – KrazyMax
    Commented Dec 29, 2019 at 17:00
  • Like I have already mentioned, the key field is system generated source.
    – Stop War
    Commented Dec 30, 2019 at 6:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.