How do I toggle boolean field

MrHize

I am working on a project where user have his own profile, I want to create a BooleanField on model so that user can set profile privacy, private or public. I have added a BooleanField to modal (is_private). Also i have a toggle switch on template but i do not know how to go with it with Django. I want when a user click on switch boolean field is true (private), when user click again on switch boolean field is false (public). Jquery maybe needed as well.

enter image description here

Model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) 
    is_private = models.BooleanField(default=False)

Views:

def profile_edit_view(request):
    p = Profile.objects.filter(user=request.user).order_by('-id')
    context = {'p':p}
    return render(request, 'profile_edit.html', context)

urls:

path('account/edit/', profile_edit_view, name ='profile-edit'),

Profile Edit Template:

<form method="POST" name="is_private">
 {% csrf_token %}
<div class="custom-control custom-switch">
 <input type="checkbox" class="custom-control-input" id="customSwitches" name="is_private">
 <label class="custom-control-label" for="customSwitches">Private Account</label>
 </div>
 </form>
<p class="text-muted font-weight-normal font-small">
  When your account is private, only people you approve can see your photos and videows on Pixmate. Your existing followers won't be affected.
</p>
AchuthVarghese
  1. In template file change the input tag as shown
<!-- Mark the checkbox as checked or not by is_private -->
<input type="checkbox" class="custom-control-input" id="customSwitches" {% if p.is_private %}checked{% endif %}>

In that same template file add this script

<script type="text/javascript">
    $(document).ready(function() {
        // send request to change the is_private state on customSwitches toggle
        $("#customSwitches").on("change", function() {
            $.ajax({
                url: "{% url 'change_privacy' %}",
                data: {
                    csrfmiddlewaretoken: "{{ csrf_token }}",
                    is_private: this.checked // true if checked else false
                },
                type: "POST",
                dataType : "json",
            })
            // $.ajax().done(), $.ajax().fail(), $ajax().always() are upto you. Add/change accordingly
            .done(function(data) {
                console.log(data);
                // show some message according to the response. 
                // For eg. A message box showing that the status has been changed
            })
            .always(function() {
                console.log('[Done]');
            })
        })
    });
</script>
  1. Add a new path in your urls file of the app which binds to a view. Say: a function named change_privacy() in your views
path('changeprivacy', change_privacy, name="change_privacy"),
  1. In views file add a new function. You need to import JsonResponse
from django.http import JsonResponse

def change_privacy(request):
    if request.is_ajax() and request.method=='POST':

        profile = Profile.objects.get(user=request.user)

        profile.is_private = True if request.POST.get('is_private') == 'true' else False
        profile.save()
        data = {'status':'success', 'is_private':profile.is_private}
        return JsonResponse(data, status=200)
    else:
        data = {'status':'error'}
        return JsonResponse(data, status=400)

enter image description here enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I toggle an ng-show in AngularJS based on a boolean?

How to toggle a Boolean field in Firebase 9

jquery: How do I toggle password for 1 input field?

How do I get the value of a boolean from a database field?

How do i update boolean field on Django model?

QML: How do you toggle boolean?

How to toggle a boolean relative to what i click on?

Using FXML and JavaFX, how do I set a boolean variable using toggle button?

How do I set state to toggle a boolean value that sits inside an array of JSON object?

How do I toggle a .setAttribute?

In awk, how can I make a boolean value that I can toggle it?

How to toggle a boolean?

How do I toggle field required attribute after ng-click?

Elasticsearch: how can I filter on a boolean field

How can I toggle a class using a boolean in a Polymer template?

How can i toggle a Boolean value correctly for specific object in a array?

How can I toggle between two flags boolean?

Spring MVC Controller Unit Testing : How do I set private instance boolean field?

How do I efficiently update a field within a dataframe based on boolean operators on 4 other fields in the record?

How do I return a boolean field value based on if there's a reference in another table?

How do I use pfquery in parse.com filtering on a boolean field in ios?

How do I add a link to a Custom Boolean Field and pass parameters using Django_Tables2

How do I update a postgres boolean field using Active Record in Rails 5?

Toggle a boolean field in all mongodb subdocuments

How do I toggle a SwiftUI toggle when a view is tapped?

What is the "nationality toggle" and how do I reset it?

How do I toggle sound with amixer?

How do I toggle comments with German keyboard?

how do I toggle between text and a table?