【问题标题】:Use value from one form as value for another form in redirected template (Django)使用一个表单中的值作为重定向模板(Django)中另一个表单的值
【发布时间】:2021-05-12 13:26:45
【问题描述】:

我有两个模型


def CarModel(models.Model):
   type = models.CharField()
   price = models.FloatField()
   img = models.URLfield()



def WrongCar(models.Model):
    wrong_type = models.CharField()
    correct_type = models.CharField()
    price = models.FloatField()

我有一个产品列表,例如使用 CarModel 的汽车,但如果汽车分类错误,用户应该能够通过单击名为“正确的类型”,然后用户被重定向到wrong_car-模板,其中来自WrongCar 的字段可以填写。发生这种情况时,wrong_type 应自动使用来自CarModel 的值type 填写,这样用户只需填写correct_typeprice。我想我可以从request 对象中提取它,但我真的不知道该怎么做。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以通过将值存储在 request.session(字典)中的重定向来传递值,例如:

    正确的汽车视图.py

    request.session['wrong_car_type'] = 'type_you_want'
    return redirect(reverse('wrong_car_url'))
    

    wrong_car_view.py

    try:
        wrong_car_type = request.session['wrong_car_type']
    except KeyError:
        wrong_car_type = None
    else:
        del request.session['wrong_car_type']
    

    【讨论】:

    • 我最终使用了 pk 键和 MyClass.get.object() 结合使用 - 尽管您的答案可能也有效
    猜你喜欢
    • 2020-08-31
    • 2015-06-09
    • 1970-01-01
    • 2014-03-14
    • 2016-01-17
    • 2020-07-09
    • 2012-02-10
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多