【问题标题】:Django, passing data through a view context, preferred storage methodDjango,通过视图上下文传递数据,首选存储方法
【发布时间】:2018-03-28 22:16:36
【问题描述】:

我正在尝试通过 django 上下文传递一些数据,但发现它有点麻烦。我对 Python 很陌生,对存储数据有点不熟悉,我在代码中显示了一些建议: 1. 传递数据的表单:

def formview(request):
    if request.method == 'POST':
        form=LogonForm(request.POST)
        if form.is_valid():
            request.session['firstname']=form.cleaned_data['entrykey']
            request.session['lastname']=form.cleaned_data['firstfield']
            request.session['age']=form.cleaned_data['secondfield']
            request.session['location']=form.cleaned_data['thirdfield']
            return HttpResponseRedirect('thanks')
    else:
        form=LogonForm()

    return render(request, 'logon/form.html', {'form': form})

对提交的数据做出反应但不来自数据库的视图:

def thanksforform(request):
    try:
        #Using class
        class thanksclass():
            firstname=request.session['firstname']
            lastname=request.session['lastname']
            age=request.session['age']
            location=request.session['location']
            under18='Come back in %s years' % str(18-age)
            over18='Step right up!'
        #Using array
        data=np.empty(6, dtype=object)
        data[0]=request.session['firstname'] #etc. etc. ect.
        #using list
        listdata=[request.session['firstname']] #etc etc etc
    except KeyError:
        return HttpResponseRedirect('/logon/')
    request.session.flush()
    return render(request, 'logon/thanks.html', {'thanksclass': thanksclass})

为了这种目的,Django 首选哪种类型的对象,是否有更好的方法通过视图上下文传递数据?

PS。请忽略源是会话数据,这只是我胡闹的一个例子,我知道您也可以直接从模板中调用会话数据。

【问题讨论】:

    标签: python django list class


    【解决方案1】:

    就我自己而言,取决于我检索/创建数据的方式。

    一般来说,如果您想进行一些验证或允许用户提交数据,或者如果您从 ORM 表示某些内容,但 Django 的模板接受很多数据类型,那么表单是一种很好的方式。

    否则,我建议创建一个字典并将内容设置为与其相等。即。

    varOne = '1'
    varTwo = 'Two'
    varThree = 3.0
    myPassThrougData = 
      {'variableOne': varOne, 'variableTwo': varTwo, 'VariableThree': 
      varThree }
    return render(request, 'logon/form.html', {'form': form}, content=myPassThoughData)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 2017-11-24
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多