2012-08-02 4 views
0

외부 소스에서 제공된 초기 데이터로 장고 모델 폼을 채우려고합니다. 내가 풀하여 외부 소스에서 필요한 모든 데이터를 시작하는 것이 달성하기 위하여 다음Django가 초기 데이터 형식으로보기를 설정했습니다.

data = {} 
for field in my_model._meta.fields: 
    if field.name == 'name': 
     data[field.name] = api_data_name 
form = MyEditForm(initial=data) 

내가 전달 해요 : 내 양식에 같은 초기 데이터를 제공하는 딕셔너리를 채워 이어

url =('http://myapi.example.com') 
data = urllib2.urlopen(url) 
result = json.load(data) 

api_data_name = result['properties']['name'] 
api_data_type = result['properties']['type'] 

서식 및 초기 데이터 양식을 예상대로 내 텍스트 필드를 채우는 있지만 지금은 외부 소스에서받은 문자열을 기반으로 선택 필드의 값을 설정할 수 있어야합니다 및 방법을 얻을 수 없습니다. 그 후, 다음과 같이하면 :

if field.name == 'type': 
    data[field.name] = api_data_type 

실례로, 선택 요소가 "0", "1", "2"등의 옵션 값을 가지므로 자세한 설명이 없으므로 api_data_type 변수에서 가져옵니다.

api_data_type과 각각을 비교할 수 있도록 내 선택 필드의 모든 옵션 <option value="1">long_description</option>에서 long_description을 어떻게 얻을 수 있습니까? Heres는

내 models.py 및 forms.py의 샘플 :

#models.py 

TYPE = (
    ('0',_(u'Type1')), 
    ('1',_(u'Type2')), 
    ('2',_(u'Type3')), 
) 

class MyModel(models.Model): 
    ... 
    type=models.CharField(max_length=30,choices=TYPE,blank=True) 
    ... 

#forms.py 
class MyEditForm(forms.ModelForm): 
    class Meta: 
     model = MyModel 

     widgets = { 
      ... 
      'type': Select(attrs={'class':'select-small span2'}), 
      ... 
     } 

답변

0

내가 무엇을 요구 수행하는 방법을 알게되었습니다. 내가 직접 데이터베이스 액세스가 있다면

# For select fields 
if field.name == 'classification': 
    for choice in field.choices: 
     if choice[1].lower() == api_poi_classification.lower(): 
      data[field.name] = choice[0] 

그리고 (내 경우에는 체크 박스로) 다 대다 필드를 채우는 데 노력 나중에 어떤을위한

# Many to many fields populate   
for field in hotel_poi._meta.many_to_many: 
    if field.name == 'views': 
     if u'Vista' in api_poi_review_fields: 
      api_vistas = api_poi_review[u'Vista'] 
      # The api_vistas string comes from api in the format (v1; v2; v3; v4) 
      views = api_vistas.split(';') 
      choices = field.get_choices() 
      temp = [] 
      for view in views: 
       for choice in choices: 
        if view.lower().strip() == choice[1].lower().strip(): 
        temp.append(choice[0])   
      data[field.name]=temp 

이 모든 것은 피할 수 ... 이 경우 나는 단지 m = MyModel.objects.filter(id=1)과 같은 객체 인스턴스를 설정해야하고 form = MyEditForm(instance=m)

을 호출해야합니다.