2016-07-26 1 views
0

장고에 대한 새로운 기능이며 제출 양식을 제출할 때 양식을 작성 중입니다. 전에 본 적이없는 오류가 발생했습니다. TypeError at /catalog/ coercing to Unicode: need string or buffer, function found유니 코드로 강제 변환 : 장고 양식에서 발견 된 문자열 또는 버퍼, 기능

def main(request): 
    if validateToken(request): 
     appList = getDetailsApplications(request) 
     polList = getDetailsApplicationPolicies(request) 
     message = None 
     if request.method == 'POST' and 'deployButton' in request.POST: 
      form = AppsForm(request.POST, policiesList=polList, applicationList=appList) 
      if form.is_valid(): 
       deploy(request, form) 
      else: 
       form = AppsForm(policiesList=polList, applicationList=appList) 
       message = 'Form not valid, please try again.' 
     elif request.method == 'POST' and 'undeployButton' in request.POST: 
      form = AppsForm(request.POST, policiesList=polList, applicationList=appList) 
      if form.is_valid(): 
       undeploy(request, form) 
      else: 
       form = AppsForm(policiesList=polList, applicationList=appList) 
       message = 'Form not valid, please try again.' 
     else: 
      form = AppsForm(policiesList=polList, applicationList=appList) 
     return render_to_response('catalog/catalog.html', {'message': message, 'form': form}, 
          context_instance=RequestContext(request)) 
    else: 
     return render_to_response('menu/access_error.html') 

오류가 deploy(request, form) 및에서 발생 :

class AppsForm(forms.Form): 
    def __init__(self, *args, **kwargs): 
     policiesList = kwargs.pop('policiesList', None) 
     applicationList = kwargs.pop('applicationList', None) 
     super(AppsForm, self).__init__(*args, **kwargs) 
     if policiesList and applicationList: 
      self.fields['appsPolicyId'] = forms.ChoiceField(label='Application Policy', choices=policiesList) 
      self.fields['appsId'] = forms.ChoiceField(label='Application', choices=applicationList) 
     else: 
      self.fields['appsPolicyId'] = forms.ChoiceField(label='Application Policy', 
                    choices=('No application policies found', 
                      'No application policies found')) 
      self.fields['appsId'] = forms.ChoiceField(label='Application', choices=('No applications found', 
                    'No applications found')) 

views.py은 다음과 같습니다처럼

forms.py 보인다, 그들은 다른 앱에 있으며 나는 app/views.py에서 가져옵니다. 여기

나는 모두가 동일합니다에 문제를 생각하기 때문에 내가 그들 중 하나를 보여,하지만 난 그것을 해결 할 수없는 아니에요 ...

def deploy(request, form): 
    if validateToken(request): 
     policy = form.cleaned_data['appsPolicyId'] 
     applicationID = form.cleaned_data['appsId'] 
     headers = {'Content-Type': 'application/json'} 
     deployApp = apacheStratosAPI + applications + '/' + applicationID + '/' + deploy + '/' + policy 
     req = requests.post(deployApp, headers=headers, auth=HTTPBasicAuth(request.session['stratosUser'], 
                     request.session['stratosPass']), 
         verify=False) 
     if req.status_code == 202: 
      serverInfo = json.loads(req.content) 
      message = '(Code: ' + str(req.status_code) + ') ' + serverInfo['message'] + '.' 
      return render_to_response('catalog/catalog.html', {'message': message, 'form': form}, 
        context_instance=RequestContext(request)) 
     elif req.status_code == 400 or req.status_code == 409 or req.status_code == 500: 
      serverInfo = json.loads(req.content) 
      message = '(Error: ' + str(req.status_code) + ') ' + serverInfo['message'] + '.' 
     return render_to_response('catalog/catalog.html', {'message': message, 'form': form}, 
        context_instance=RequestContext(request)) 
    else: 
     return render_to_response('menu/access_error.html') 

는 라인의 오류 :

deployApp = apacheStratosAPI + applications + '/' + applicationID + '/' + deploy + '/' + policy 

디버깅 할 때 변수가 정확하고 형식이 u'value' 인 것으로 나타났습니다. 왜 다른 형식의 값이이 형식에 있고 어떤 오류도 발생하지 않기 때문에 왜 유니 코드 오류가 발생하는지 알 수 없습니다.

지금 왜이 오류가 발생합니까? 고마워, 안부.

답변

1

문자열 연결에 포함 할 항목 중 하나는 deploy입니다. 파이썬은 현재 범위 내에서 정의되지 않았으므로, 파이썬은 현재 함수 자체 인 가장 가까운 이름 선언을 찾습니다. 따라서 오류가 발생합니다.

그 이름이 실제로 정의되어 있어야할지 모르지만 함수 내에서 수행해야합니다. 어쨌든 변수 또는 함수의 이름을 바꿔야합니다.

+0

당신의 의견이 내 눈을 열었습니다! 'deploy' 변수는'app/views.py'의 최상위 레벨에 정의 된 다음 함수의 이름을'deploy'로 변경하고 변수의 이름을 바꾸는 것을 잊었습니다. 나는 파이썬이 그것들을 구별 할 수 없다는 것을 잊었다. 무슨 어리석은 실수 야. 감사! – Aker666

관련 문제