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.
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>
<!-- 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>
change_privacy()
in your viewspath('changeprivacy', change_privacy, name="change_privacy"),
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments