I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in database for this field changes to ‘Active’ and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it’s value in the database and show De-Activated message
HTML page:
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Job activation status</h3>
</div>
<div class="panel-body">
<td> Campus Name </td>
<td> hod_name </td>
<td>
<select name="status" class="form-control">
<option value="1">Active</option>
<option value="2">Disabled</option>
</select>
</td>
</div>
</div>
</div>
Model:
class Campus(models.Model):
STATUS = (
('Active', 'Active'),
('Disabled', 'Disabled'),
)
campus_name = models.CharField(blank=True, max_length=30)
hod_name = models.CharField(blank=True, max_length=25)
status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True)
def __str__(self):
return self.campus_name
View:
def status_update(request, pk):
campus_status = get_object_or_404(Campus, pk=pk)
campus_status.status = 'Active' if campus_status.status == 'Disabled' else 'Disabled'
campus_status.save(update_fields=['status'])
messages.success(request, '{} Status: {} successfully'.format(campus_status.campus_name, campus_status.status))
return redirect('/dashboard/create_campus/')
2
Answers
HTML page :
URL.py
View:
Model:
AJAX is basically an asynchronous request from client side code (i.e JavaScript) and not a Django server side feature. AJAX can be implemented in your Django application using jQuery or any other JavaScript library or framework.
Refer the below two links for how to implement AJAX in a DJANGO application
Ajax with jQuery Django example
Here is the link to another SO answer which has more details.
I did not modify your code to work with Ajax, I believe you can do it yourself by referring the provided links.
Please let me know if you have any questions.
Thanks