django 前端传参(变量、数据库)

本文介绍了前端如何将变量传入后端函数,通过替换URL模板字符串并利用location.href实现跳转。后端通过接收URL参数,展示实验项目申请信息管理页面。同时,也展示了后端如何将context字典传回前端,包括使用Ajax调用和URL调用两种方式,以及前端如何接收和使用这些参数。
摘要由CSDN通过智能技术生成

一、将变量传入后端函数

1、前端function

var url = "{% url 'apply_experiments:change_experiments' 'school_year' 'term' 'course' %}";
url = url.replace('school_year/term/course', row.school_year+'/'+row.term+'/'+row.course);
window.location.href=url;

2、路由

path('change-experiments/<school_year>/<term>/<course>/', change_experiments, name='change_experiments'),

3、视图views.py

def change_experiments(request, school_year=None, term=None, course=None):
context = {
    'status': True,
}
this_logger.info('实验项目申请信息管理页面视图,接收到:学年:'+str(school_year)+' 学期:'+str(term)+' 课程:'+str(course))
return render(request, 'apply_experiments/change_experiments.html', context)

二、将context上下文的字典传回后端

1、后端获得参数示例

def question_content(request, question_id):
    question = Question.objects.get(id=question_id)
    question_2 = Question.objects.all().order_by('-views', 'created', 'questionTitle')[:10]
    question.views = question.views + 1
    question.save()
    answer_list = AnswerModel.objects.filter(question_id=question_id)
    questions = Question.objects.all()
    context = {
        "question": question,
        "question_id": question_id,
        "answer_list": answer_list,
        "questions": questions,
        "question_2": question_2,
    }
    return render(request, "question/content.html", context=context)

2、前端传回有两种

1) Ajax调用
 <form class="form-horizontal" id="modalForm_Content" method="post"  action="">{% csrf_token %}
  <input type="text" class="form-control" id="form_name" name="name" placeholder="实验/文件夹名称">
   <input type="text" class="form-control" id="form_question_id" name="question_id" value="{{ question_id }}"  requiredplaceholder="" hidden>
    <button type="submit" class="btn btn-default" onclick="submit_type=1">SAVE</button>

重点在于value={{ question_id }}

2) href/url 调用
<a href="{% url 'question:question_content' question_id=question.id %}" class="news-item">

传参就直接在url 后就可以了(但是不能传变量)请添加图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值