Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

How do you make the fields read-only in a Django form when a specific condition is met?

$
0
0

Based on the following image, I am trying to make the fields category and current points non-editable when the status of the task is Finalized or Cancelled, otherwise the fields should be editable.

enter image description here

Below is the code from my html file.

{% extends "base.html" %} {% load widget_tweaks %} 
{% block content %}

<div id="form-group">
    <form method="POST" action="." enctype="multipart/form-data">
    {% csrf_token %}
    <label>Select your category</label>
        {{ form.category|add_class:"card" }}
    <label>What's the status of the task?</label>
        {{ form.status|add_class:"card" }}
    <label>Current points:</label>
        {{ form.points|add_class:"card" }}
    <label>Finalized date:</label>
        {{ form.ending_date|add_class:"card" }}
   <button type="submit" class="btn btn-success">Send</button>
   </form>
</div>

Below is the code from my forms.py file.

class TaskModelForm(forms.ModelForm):
    class Meta:
        model= Task
        fields = ['category', 'status', 'points']

    def __init__(self, *args, **kwargs):
        super(TaskModelForm, self).__init__(*args, **kwargs)
        self.fields['status'].required = False
        self.fields['points'].required = False

When I want to edit the contents of this form I need to verify if the status is Finalized, so the fields are non-editable, otherwise the fields should be editable and I am thinking something about:

{% extends "base.html" %} {% load widget_tweaks %} 
{% block content %}

{% if form.status.value == 'Active' %} <!--make the fields editable -->
<div id="form-group">
    <form method="POST" action="." enctype="multipart/form-data">
    {% csrf_token %}
    <label>Select your category</label> 
        {{ form.category|add_class:"card" }} 
    ...
   <button type="submit" class="btn btn-success">Send</button>
   </form>
</div>
{% endif %}

{% if form.status.value == 'Finalized' %} <!--make the fields non-editable -->
<div id="form-group">
    <form method="POST" action="." enctype="multipart/form-data">
    {% csrf_token %}
    <label>Select your category</label> 
        {{ form.category|add_class:"card" }} 
   ...
   <button type="submit" class="btn btn-success">Send</button>
   </form>
</div>
{% endif %}

However, I believe my approach might not work because this could be a more front-end problem rather than back-end one (just a guess). Can you point me out to the right direction to solve this problem?


Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>