2010-01-19 1 views

답변

4

이 문제에 대한 좋은 해결책이 있는지 알고 싶습니다.

book = models.Book(title='Foo') 
chapter = models.Chapter(parent=book, title='dummy') 
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter) 

기본적으로, 내가 먼저 올바른 부모 관계 더미 객체 (이 경우 chapter)를 만든 다음에 instance 인수로 되었 우아한 거리가 멀다 내 자신의 솔루션은이 작업을 수행하는 것입니다 폼의 생성자. 양식은 요청에 제공된 데이터로 더미 객체를 만드는 데 사용한 데이터를 덮어 씁니다. 마지막에 진짜 자식 개체를 얻기 위해, 나는 같은 것을 할 :

if form.is_valid(): 
    chapter = form.save() 
    # Now chapter.parent() == book 
+0

나는 그것이 작동하는 것을 확인합니다. 좀 더 우아한 해결책을 위해 조금 기다릴 것이고, 아무 것도 나타나지 않으면 당신의 대답을 받아 들일 것입니다. 고마워, 당신은 10 점을 얻었습니다. –

+0

불행히도 현재이 방법이 최선의 방법입니다. –

0

나는 djangoforms.ModelForm을 서브 클래스 및 작성 방법 * 추가 ​​:

class ModelForm(djangoforms.ModelForm): 
    """Django ModelForm class which uses our implementation of BoundField. 
    """ 

    def create(self, commit=True, key_name=None, parent=None): 
    """Save this form's cleaned data into a new model instance. 

    Args: 
     commit: optional bool, default True; if true, the model instance 
     is also saved to the datastore. 
     key_name: the key_name of the new model instance, default None 
     parent: the parent of the new model instance, default None 

    Returns: 
     The model instance created by this call. 
    Raises: 
     ValueError if the data couldn't be validated. 
    """ 
    if not self.is_bound: 
     raise ValueError('Cannot save an unbound form') 
    opts = self._meta 
    instance = self.instance 
    if self.instance: 
     raise ValueError('Cannot create a saved form') 
    if self.errors: 
     raise ValueError("The %s could not be created because the data didn't " 
         'validate.' % opts.model.kind()) 
    cleaned_data = self._cleaned_data() 
    converted_data = {} 
    for name, prop in opts.model.properties().iteritems(): 
     value = cleaned_data.get(name) 
     if value is not None: 
     converted_data[name] = prop.make_value_from_form(value) 
    try: 
     instance = opts.model(key_name=key_name, parent=parent, **converted_data) 
     self.instance = instance 
    except db.BadValueError, err: 
     raise ValueError('The %s could not be created (%s)' % 
         (opts.model.kind(), err)) 
    if commit: 
     instance.put() 
    return instance 

사용법은 간단하다 :

book = models.Book(title='Foo') 
form = forms.ChapterForm(request.POST) 
chapter = form.create(parent=book) 

request.POST에서 key_name을 지정할 수있는 코드를 복사하거나 붙여 넣지 않았으므로 대신 인수로 전달해야합니다.

* 코드는 google.appengine.ext.db.djangoforms의 원래 모델 폼의 저장 방법에서 수정되었습니다.