【问题标题】:Accessing model attributes in the template in django在 django 中访问模板中的模型属性
【发布时间】:2017-09-12 15:58:21
【问题描述】:

这是我的 django 应用程序的 views.py 的 sn-p。我使用 modelform 创建了一个表单。 models.py 有一个类用户,它有一个属性用户名。我想将注册页面重定向到“重定向”视图,但我还想传递在我们点击表单上的提交按钮并且数据存储在实例“new_form”中之后获得的用户名。

def registration(request):
    if request.method=='POST':
        form=userForm(request.POST)
        if form.is_valid():
            name=form.cleaned_data['username']
            new_form=form.save()

            return HttpResponseRedirect(reverse('redirect'))
    else:
        form=userForm()
    return render(request,'student/registration.html',{'form':form})

我的 redirect.html 看起来像这样。

<h1>You have signed up.</h1>
<p>hello {{field.name}}</p>

但问题是在你好之后没有显示名称,这很明显,因为我没有通过反向('redirect')传递任何东西。那么我该怎么做呢?我的redirect.html 也有问题吗?

【问题讨论】:

    标签: django forms


    【解决方案1】:

    而不是return HttpResponseRedirect(reverse('redirect'))

    使用return render(request, 'redirect.html', {'name': name})

    并将您的redirect.html 编辑为

    <h1>You have signed up.</h1>
    <p>hello {{name}}</p>
    

    希望这会有所帮助。

    【讨论】:

    • 是的,这有帮助...谢谢..还有其他方法吗?
    • 你能解释一下你问的其他方式吗?
    • 我们在模板中使用 {{field.name}} 的那种...有没有这样的方法,或者我可能在某个地方误读了?...
    【解决方案2】:

    制作上下文字典并发送。

    def registration(request):
        context ={}
        if request.method=='POST':
            form=userForm(request.POST)
            if form.is_valid():
                name=form.cleaned_data['username']
                context['name']=name
                new_form=form.save()
    
                return render(request,'student/registration.html',context)
        else:
            form=userForm()
            context['form']=form
        return render(request,'student/registration.html',context)
    

    现在html

    <h1>You have signed up.</h1>
    <p>hello {{name}}</p>
    

    【讨论】:

    • @Shefali,通过这种方式,您可以发送任意数量的字段,例如 nameformlocation 以及您需要的任何内容,只需添加到 context字典和发送。
    • {{field.name }} 如果您在一个字段中有多个信息,例如 user 有姓名、职务、位置,则可以使用。然后你可以使用{{user.name}}{{user.designation}}等。
    • 请投票并选择答案,如果它有助于您的查询。感谢合作。
    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2013-06-18
    • 2018-01-17
    • 2014-02-16
    • 2011-06-06
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多