【问题标题】:required authentication in forms需要在表单中进行身份验证
【发布时间】:2015-02-20 22:11:13
【问题描述】:

我在某些模板中遇到了身份验证问题。 在我传递基于模型的表单的模板中,我只能在登录时访问, 但是在模板中的表单不是基于模型的,我可以在不登录的情况下访问

基于非模型的表单:

class ProvSearchForm(forms.Form):
      proveedor = forms.ModelChoiceField(queryset=Proveedor.objects.all(),required=True)
      mes = forms.ChoiceField(
               choices = (
                          ('1',"Enero"),
                          ('2',"Febrero"),
                          ('3',"Marzo"),
                          ('4',"Abril"),
                          ('5',"Mayo"),
                          ('6',"Junio"),
                          ('7',"Julio"),
                          ('8',"Agosto"),
                          ('9',"Septiembre"),
                          ('10',"Octubre"),
                          ('11',"Noviembre"),
                          ('12',"Diciembre"),
                          ),
               widget = forms.Select()
              )
      def __init__(self, *args, **kwargs):
          super(ProvSearchForm, self).__init__(*args, **kwargs)
          self.helper = FormHelper()

我的看法:

@login_required(login_url='/login/')
def BuscarView(request):
    if request.method == 'POST':
       form = ProvSearchForm(request.POST)
       nombre = request.POST.get('proveedor')
       mes = request.POST.get('mes')
       usuario = request.user
       if form.is_valid():
          cargaftp = Lectura_FTP()
          spftp = cargaftp.leer_ftp()
          carga = Actualizar_Descarga()
          sp = carga.actualiza(nombre,mes,usuario)
          return HttpResponseRedirect('/archivo/')
    else:
       form = ProvSearchForm()
    return render_to_response('buscarform.html',
                              {'form':form})

我的网址:

url(r'^buscar/$', 'pc.views.BuscarView', name='buscar'),

这个表单需要一些参数并将其传递给存储过程,我需要传递登录用户的用户名,但我得到一个空(或 null)值。

在我的模板的导航栏中,我有标签{{ user.username }} 来呈现用户名,但在我传递基于非模型的表单的模板中,我看不到任何用户名,我可以在没有登录的情况下访问。

如何在非基于模型的表单中启用身份验证,或者如何将登录用户的用户名传递给此表单。

提前致谢

【问题讨论】:

    标签: django django-forms django-views django-authentication


    【解决方案1】:

    你没有通过@987654321@render_to_response

    return render_to_response('buscarform.html',
                                  dict, context_instance=RequestContext(request))
    

    【讨论】:

    • 谢谢@Raja Simon。抱歉,我可以投票,但我需要 15 分才能投票。我忘记了上下文实例
    • @joselegit 如果答案是正确的,那么您可以通过单击对勾来接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多