1

Say I have a model


class MyModel(model.Models):
    name = model.CharField()
    age = model.IntField()

Then in my template I want to display the name but only allow age to be changed i.e the user should not be able to modify what is written in the name field but it should just be there to show, which name they are editing the age for.

My template is as the following


{% extends "myapp/base.html" %}

{% load static %}

{% block content %}
{% load crispy_forms_tags %}

<div class="content-section">

  <div class="form-group">
    

    {{form.name|as_crispy_field}} <!--   Can still edit this field -->

    <form method="POST">
      {% csrf_token %}
      {{form.age|as_crispy_field}}
      <button class="btn btn-outline-success" type="submit">Update</button>
      <a role="button" class="btn btn-outline-info" href="{% url 'my_list' %}"> Wups, take me back!</a>
  </div>
  </form>
</div>
{% endblock content %}

CutePoison
  • 4,679
  • 5
  • 28
  • 63
  • Why are you adding `name` to the model form? You can just leave it out and pass name to the template as a variable, then render it. –  May 13 '21 at 15:11
  • I like formatting of the fields, thus I tried to keep it, instead of writing the html/css my self for a box with the link in it etc. – CutePoison May 13 '21 at 15:18
  • have a look on this https://stackoverflow.com/questions/1827526/django-creating-a-form-field-thats-read-only-using-widgets – Sumithran May 13 '21 at 15:19

1 Answers1

1

As mentioned by @Melvyn, you dont't need to pass name to the form. Just pass it as a variable to your template, then create a read only input field and customize it as you want:

<input value="{{ name }}" readonly/>

mendespedro
  • 466
  • 3
  • 8
  • Yes, but it won't be actually used, because `name` is not on the form. There is no such thing as client-side safety, users can submit whatever they want. – mendespedro May 13 '21 at 15:23