簡體   English   中英

如何更改 html 模板 DJANGO 中的變量

[英]How to change variable in html template DJANGO

我在我的上下文字典中寫了這個變量(重構)。

@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>

在這種情況下, refactor是字典的值而不是變量。

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

  • 如果你想使用變量而不是字典,則傳遞locals()而不是context
  • 如果你想使用context作為字典,在模板中你必須使用{{context.refactor}}來獲取值( doc
  • 如果您使用sw-django-utils等外部工具,請考慮使用get_key_from_dict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM