Reach django user from javascript template

Question:

I’m following Corey Shafer’s django guide and I have run into some problems he doesn’t cover. I’m trying to make profiles that are visible to everyone but only editable by the user itself. In my views.py I have a boolean "editable", and this part is working. However, I can’t get that boolean to my js file… Code below.

const button = document.getElementById("button");


button.addEventListener("click", () => {
    const form = document.getElementById("form");
    var bool = {{ user.profile.editable }};

    if(form.style.display == "none" && bool){
        form.style.display = "block";
    }else{
        form.style.display = "none";
    }
});

When I inspect it in the browser it gives me a syntaxError because I’m using ‘{‘.
And here is the code from my views.py:

@login_required
def profile(request, username):

    user = User.objects.get(username=username)
    Profile.objects.get_or_create(user=request.user)
    editable = False

    if request.method == "POST":
        user_form = UserUpdateForm(request.POST, instance=request.user)
        profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request, f"Profile successfully updated!")
            return redirect("profile")
    else:
        user_form = UserUpdateForm(instance=request.user)
        profile_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        "user_form": user_form,
        "profile_form": profile_form
    }

    if request.user == user:
        editable = True

    return render(request, "users/profile.html", context)
Asked By: pfeidewigo100

||

Answers:

Firstly, if you want to access the editable variable, you just need to pass it into your context:

context['editable'] = editable

Secondly, it’s considered bad practice to pass Django variables directly into JS <script> tags. If you want to access this data then either create a hidden input with the value or use the json_script tag:

https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#json-script

Thirdly, it seems your code just renders and processes a profile form. I would suggest putting the editable check at the start of the view and redirecting if the user is not accessing their own profile.

Answered By: 0sVoid

get the value as a str and check like this: "{{ user.profile.editable }}"==="True"

const button = document.getElementById("button");


button.addEventListener("click", () => {
    const form = document.getElementById("form");
    var bool = "{{ user.profile.editable }}"==="True";

    if(form.style.display == "none" && bool){
        form.style.display = "block";
    }else{
        form.style.display = "none";
    }
});
Answered By: Mukhtor