2

I am trying to implement a function in which when I click on Activate button, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active. If deactivate is clicked, the text changes to deactive along with it's value in the django database.

This is my current 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">
          <b>Status</b>: Active
          <span style="padding-left:20px;"></span>
          <button type="button" class="btn btn-primary">Activate</button>
          <button type="button" class="btn btn-primary">Deactivate</button>
          <button type="button" class="btn btn-primary">Dissolve</button>

      </div>
     </div>
     </div>

And my models.py is as follows:

class Job(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField('Job Name',max_length=128)
    # when the job was created
    date_created = models.DateTimeField('Date Created', auto_now=True)
    # what entity/organization needs this job?
    client_organization = models.CharField('What organization do you represent?', max_length=64)
    # short description
    description = models.TextField('Job Description', max_length=256)
    # end product to be delivered
    deliverable = models.TextField('Deliverable', max_length=256)
    # when Job is due for completion
    duedate = models.DateTimeField('Date Due')
    # all persons who may be affected by project
    #stakeholders = models.TextField('Stakeholders')
    # important technical requirements
    #additional_information = models.TextField('Additional Information', blank = True)
    # budget estimate
    #budget = models.CharField('Budget', max_length=64)
    # file attachments
    #attachments = models.FileField(upload_to='job', blank = True)
    creator = models.ForeignKey(User,related_name = 'jobs')
    organizations = models.ManyToManyField(Organization, through = 'JobRequest', blank=False, null=True)
    #organizations = models.CharField(default="nothing",null=True,max_length = 256)
    contact_information = models.CharField('Contact Information', max_length = 256, blank = False, null=True)
    skill_required = models.CharField('Volunteer skills required', max_length=256, blank = False, null=True)
    hours_day = models.CharField('Number of hours per day', max_length=256, blank = False, null=True)
    #  Job is closed after a jr is confirmed
    closed = models.BooleanField(default = False)
    # some tags to determine what organizations to submit job to
    categories = models.ManyToManyField(Category, related_name = 'jobs')
    #categories = models.CharField(default="nothing",null=True, max_length = 256)
    status = models.IntegerField(default = 0, choices = ((0, 'Pending'), (1, 'Approved'), (2, 'Disapproved'), (3, 'Closed')))
    class Meta:
       permissions = (
           ( 'view_job','Can view Job' ),
           ( 'edit_job','Can edit Job'),
           ( 'is_creator', 'Is a creator of Job')
           )

I need help in adding a field to models.py which changes according to the button click in HTML and displays active/ deactive in the HTML page according to the button clicked. I also need help in modifying the HTML page accordingly

4
  • If you are trying to do this change in the database without reloading the page, then you need to make a call to an ajax function to update this value in database. If it is not your case, then you only need to do a standard form submit. Commented Apr 27, 2018 at 21:36
  • I do want to reload the page while making a change to the database. Commented Apr 27, 2018 at 21:38
  • I need help in writing the code. Commented Apr 27, 2018 at 21:41
  • write a view in you django codes which will change the value from your db, then call the view with js (ajax) when the button [active,inactive] has been triggered by the user Commented Apr 27, 2018 at 22:11

1 Answer 1

9

If you need only two states (active and innactive) you need a BooleanField, so in your model you add something like this:

active = models.BooleanField(default = False)

Then, you need to create a function in your views.py to update the model in the database (I will name it ajax_change_status):

from django.http import JsonResponse
from xxx.models import Job

def ajax_change_status(request):
    active = request.GET.get('active', False)
    job_id = request.GET.get('job_id', False)
    # first you get your Job model
    job = Job.objects.get(pk=job_id)
    try:
        job.active = active
        job.save()
        return JsonResponse({"success": True})
    except Exception as e:
        return JsonResponse({"success": False})
    return JsonResponse(data)

Then, you add the url for you ajax function in the urls.py:

url(r'^ajax/change_status/$', views.ajax_change_status, name='ajax_change_status')

and finally in you HTML, you need to call the function each time you click the button:

<script>
    $("#button_id").on('click', function () {
      var username = $(this).val();
      var active = <true> // or false, you have to set it
      var active = <id> // you have to set it
      $.ajax({
        url: '/ajax/validate_username/',
        data: {
          'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
          'active': active
          'job_id': username
        },
        dataType: 'json',
        success: function (data) {
          if (data.success) {
            alert("ajax call success.");
            // here you update the HTML to change the active to innactive
          }else{
            alert("ajax call not success.");
          }
        }
      });

    });
  </script>

finally, don't forget to put the csrf tag in you HTML:

{% csrf_token %}
Sign up to request clarification or add additional context in comments.

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.