【问题标题】:How to change variable in html template DJANGO如何更改 html 模板 DJANGO 中的变量
【发布时间】:2021-03-14 04:35:57
【问题描述】:

我在上下文字典中写了这个变量(重构)。

@login_required(login_url='/login')
def lessont(request, id):
if request.method == 'POST':
    form = ChapterForm(request.POST, request.FILES)
    if form.is_valid():
        new_chapter = Chapter.objects.create(lesson_id=id)
        new_chapter.name = form.cleaned_data['name']
        new_chapter.description = form.cleaned_data['description']
        new_chapter.document = form.cleaned_data['document']
        new_chapter.save()
        return redirect('/lessont/lesson/<int:id>')
get_lessons = Lesson.objects.get(id=id)
get_chapter = Chapter.objects.all().filter(lesson=id)
get_group = StudentsGroup.objects.all().filter(lessons=id)
form = ChapterForm()
refactor = False
refactor_id = 0
context = {
    'get_lesson': get_lessons,
    'get_chapter': get_chapter,
    'get_group': get_group,
    'form': form,
    'refactor': refactor,   <----- HERE
    'refactor_id': refactor_id,
}
template = 'core/lessont.html'
return render(request, template, context) <----- pass it here

然后在我的 HTML 模板中,我可以访问“重构”变量,我想通过单击按钮来更改它

<button type="submit" name="button">Add</button>

我想做类似的东西:

<button type="submit" name="button" onClick={set "refactor" to True}>Add</button>

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    在这种情况下,refactor 是字典的值,而不是变量。

    要在 django 模板中管理它,您可以尝试其中之一:

    • 如果你想使用变量而不是字典,则传递 locals() 而不是 context
    • 如果你想使用context作为字典,在模板中你必须使用{{context.refactor}}取值(doc)
    • 如果您使用sw-django-utils 等外部工具,请考虑使用get_key_from_dict

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2018-07-21
      • 2011-09-26
      • 1970-01-01
      • 2021-09-15
      • 2019-03-05
      相关资源
      最近更新 更多