OneToOne related other model fields converted to boolean field check box in form to show or hide model fields doesn't work

I have these two blog models in models.py

class Snippet(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    ...

class Post(models.Model):
    # id = models.AutoField(primary_key=True) # the same field in comment model for multi-inheritance (post_id)
    id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True, editable=False) # add unique=True in slug (never repeat)
    title = models.CharField(max_length=200, db_index=True, default='')
    tag = models.ManyToManyField(Tag, blank=True, help_text="Select a tag for this post", related_name='post_tags')
    snippet = models.OneToOneField(Snippet, on_delete=models.CASCADE, related_name='post_snippets')
    ...

and i have forms to add new post as follows

class PostModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "Post #%s) %s" % (obj.id, obj.title)
class SnippetForm(forms.ModelForm):
    post = PostModelChoiceField(queryset=Post.objects.all())
    class Meta:      
        model = Snippet
        fields = '__all__'

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        #fields = '__all__'
        #fields = ['title', 'tag', 'maintainer', 'post_img', 'content', 'snippet', 'genre', 'language', 'video', 'post_type', 'urls', 'views', 'status' ]
        labels = {'snippet': _('Add Code'),}
        exclude = ('creator', 'slug',)
        widgets = {
            'snippet': forms.CheckboxInput(attrs={'type': 'checkbox', 'class': 'checkbox', 'id': 'post-snippet'})
        }
    def clean(self):
        snippet = self.cleaned_data.get('snippet')
        if snippet:
            self.fields_required(snippet.title, snippet.code, snippet.title, snippet.linenos, snippet.language, snippet.style, snippet.highlighted) # ['title', 'code', 'linenos', ....]
        else:
            self.cleaned_data['snippet'] = False
        return self.cleaned_data
    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)
        self.queryset = Post.objects.filter(snippet=True)

and views to render template

def add_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST, request.FILES, instance=request.user)
        snippet = post_form.cleaned_data['snippet']
        if snippet:
            #snpt = modelformset_factory(Snippet, fields=('title', 'code', 'linenos', 'language', 'style', 'highlighted'))
            snpt = Snippet.objects.create(post = request.post, snippet_id = request.post.id)
            snippet_form = SnippetForm(request.POST, instance=snpt)
        if post_form.is_valid() and snippet_form.is_valid():
            post = post_form.save(commit=False)
            snpt = snippet_form.save(commit=False)
            post.creator = request.user
            post.snippet = snpt
            post.slug = slugify(post_form.cleaned_data['title'])
            post.save() and snpt.save()
            obj = post_form.instance
            alert = True
            return redirect('blog:post_list')
            #return render(request, "add_post.html",{'obj':obj, 'alert':alert})
            #return HttpResponseRedirect('blog/post_list/success/')
    else:
        post_form = PostForm()
    return render(request, 'blog/add_post.html', {'form': post_form})

Now i can’t get the snippet fields in my template when i tick the check box in the template

Here is the form

                    <form method='POST' class="form" enctype='multipart/form-data'>
                        {{ form.non_field_errors }} {% csrf_token %} {% for field in form %}
                        <div class="apply">
                            {% if field.errors %}
                            <ol>
                                {% for error in field.errors %}
                                <li><strong>{{ error|escape }}</strong></li>
                                {% endfor %}
                            </ol>
                            {% endif %} {% if field.help_text %}
                            <p class="help">{{ field.help_text|safe }}</p>
                            {% endif %}
                        </div>
                        {% endfor %} {% bootstrap_form form %}
                        <button class="boxed-btn3 w-100" type="submit">Post</button>
                    </form>

Screenshot 2022-11-08 at 12.44.52 AM

what’s wrong in this logic why the snippet form doesn’t show up in the template and how to get it live immediately when i check the boolean field add code (snippet) in the page form
please help me bro

@KenWhitesell please some help brother if you logged in

This type of dynamic update to a page requires JavaScript involvement. You would need to create an event handler for that widget and provide the JavaScript to change that portion of the page to what you want it to be. (Whether you write the JavaScript directly or use something like HTMX doesn’t fundamentally change this.)

Django templates are rendered in the server. One the page has been rendered and returned to the browser, Django is done.

So, you’ve got a couple different options for doing this (with numerous variations of each):

  • Pre-render the entire template and show or hide divs as appropriate.

  • Issue an AJAX request to a different view that is written to return an HTML fragment and inject that fragment into the page.

may i ask you bro to provide some references or docs for starting examples or i have to search and try some self thinking ideas

The specifics are really going to depend upon what JavaScript framework or library you’re going to use. Each of raw JavaScript, jQuery, HTMX, Vue, React, Angular, etc are going to have their own ways of doing this - and each site has their own documentation, usually with examples.

You first need to decide just how much JavaScript you’re going to work into your site. If this one component is the only instance you ever see using anywhere on your site, then you may find raw JavaScript to be adequate.

Or, you may realize that this is just the first of many such UI-enhancements you wish to incorporate into your site, in which case you might want to investigate a more full-featured framework.

In either case, you may also want to take into account how much JavaScript you already know, and what your comfort level is with adding another dependency into your project - and whether or not this particular objective is worth the effort that is going to go into it.

You’re also going to want to understand the implications of the specific implementation of your selected solution.

For example, you’re adding a check box to “Add Code”. Now, assume that someone checks that box to display the additional form fields and they enter code into that field. What do you want to have happen if they then uncheck that box? Sure, the form field may no longer be present, but is it still there? Do you want the data that was entered to be submitted? If they uncheck the box and then check it again, do you want any previous data to still be available?

These are just some of the questions you’re going to want to consider when implementing a solution - or at least understand what the default behavior is going to be.

This is the only features up to now cause i am also not going to use any frontend framework or then
why using django as long as i can use express and jasmine and angular to do the site,

i am just use javascript as needed as it’s easier to use django on this blog site and
all other templates that doesn’t need js will be just rendered from the server, so i just need raw js or maybe jquery but the problem is with this context variable {{ form }} how to implement that event,

i think i should use all fields individually in the template,
so i just want some starting guids in this special case as you have explained with that check box to just add the code snippet or uncheck case to hide the fields immediately and throw the data away

if you have some docs i would be really grateful to you bro, and if not too never mind thanks anyway so much for caring and helping bro

It’s not necessary to do that. You’ve got a couple of other options.

Using raw JS, you can use addEventListener to listen for a change event on that element.

Or, I think you could use the attrs attribute for the widget to add an onclick handler reference directly to the element.

I actually don’t have any substantial references for doing this using raw JS as we use a lot of either jQuery or HTMX.

okay bro if you have jQuery method or function example no problem give me any of that or even HTMX n problem just any starting example

i will search for all kinds of ways to choose which is better and for future requiring tasks that need that kinds of work

also i will try both addEventListener on a js file or in a script tag and will add attribute on click to call a function but how to put that listener on the form context variable in template as long as there is no individual field in that template to listen to the forms.py just send all form into the template without any check box tag as it’s already been identified by python in forms not html, so as i have said if you got some already worked examples

please help me with that and i would appreciate to you saving my time

i am really trying to accomplish this site as soon as possible and i got a lot of other stuff that need to be done but i am stuck on this only feature that draw on me a lot of additional time wasting

and thanks again bro from deep of my heart

Don’t confuse the construct of the form with it being rendered. The two operations are different.

See the docs and examples at:

jQuery - see .hide() | jQuery API Documentation and .show() | jQuery API Documentation

htmx - see the htmx docs, there are a lot of examples scattered around in there.

I will try all buddy and thanks for your efforts and explanations appreciated

My guess would be that one or more of your jQuery selectors are not correct. You would be able to try those commands in the console of your browser’s developer tools to see what elements are referenced to verify that you’re pointing to what you think you’re referencing.

For me to help you at this point, I would probably need to see the entire template along with what was actually rendered in the browser.

(Note: please don’t post images of code, templates, or html here. Copy/paste the text.)

Looking at your logic here:

This is interpreted as:

if (
    ($(this).prop('checked') === true)
         || 
     'checked'
   ) {`

That means that this expression will evaluate to true if either
$(this).prop('checked') === true is true, or ‘checked’ is true (“truthy”).

This condition is not checking to see if $(this).prop('checked') equal to either true or ‘checked’.

(See Operator precedence - JavaScript | MDN)

Non-empty strings (including the strings ‘false’, ‘0’, or ‘none’) evaluate as “truthy”, which means your condition will always be true - the else clause will never execute.

You Saved me bro, i removed checked and it works fine What the Hell of this trivial messy bug that causing me circling

around for long time, it was really just checked and i added true and false cause i wasn’t convinced that

the check box has this property and remembered that it’s a Boolean field but forgot to remove checked

and try again
Thanks so so so much for you