N
N
Nikolai Savelyev2018-11-14 20:20:42
Django
Nikolai Savelyev, 2018-11-14 20:20:42

Why do some django videos check for a non-passing variable in the template?

I'm still tinkering with Django for fun, and I've run into a strange thing.
In some manuals, something like the following code works:
views.py

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug = post, status='published', publish__year = year,
                             publish__month=month, publish__day=day)
    comments = post.comments.filter(active = True)
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
  

    return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'comment_form': comment_form})

detail.html
{% if new_comment %}
        <h2>Your comment has been added.</h2>
    {% else %}

In my template, new_comment is always False. Yes, I can pass it to render and assign False where it is not needed.
But why does it work for others?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Pronin, 2018-11-14
@YellowTriangleMKV

As far as I know the code is like this:

{% if new_comment %}
        <h2>Your comment has been added.</h2>
{% else %}

Will work correctly in Django template, even if this variable was not passed during rendering. It will just have the None value there.
Perhaps in your manual this variable was added to the template "for the future" and in the next lessons of the manual it will be passed during rendering. Or maybe just a mistake or a stupid copy-paste from some other resource, I can’t guess.

D
Denis Ivlev, 2018-11-20
@ivlevdenis_ru

Just forgot to put it in context

K
Konstantin Malyarov, 2018-11-14
@Konstantin18ko

Not sure but worth a try

return render(request, 'blog/post/detail.html', locals())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question