2010-07-19 2 views
6

레시피를 저장하기위한 양식을 작성했습니다. 그것은 양식과 인라인 formset을 사용합니다. 나는 레시피가 들어있는 텍스트 파일을 가진 사용자를 확보하고 데이터를 쉽게 잘라내어 붙여 넣기를 원합니다. 원시 텍스트 입력을 처리 한 후 양식 부분을 채우는 방법을 알아 냈지만 인라인 formset을 채우는 방법을 알 수는 없습니다.Django 인라인 Formset의 초기 데이터

해결책은 거의 여기에 나와 있습니다 : http://code.djangoproject.com/ticket/12213하지만 나는 함께 조각을 넣을 수는 없습니다.

내 모델 : 레시피 양식이 ModelForm 사용하여 만들어집니다

#models.py 

from django.db import models 

class Ingredient(models.Model): 
    title = models.CharField(max_length=100, unique=True) 

    class Meta: 
     ordering = ['title'] 

    def __unicode__(self): 
     return self.title 

    def get_absolute_url(self): 
     return self.id 

class Recipe(models.Model): 
    title = models.CharField(max_length=255) 
    description = models.TextField(blank=True) 
    directions = models.TextField() 

    class Meta: 
     ordering = ['title'] 

    def __unicode__(self): 
     return self.id 

    def get_absolute_url(self): 
     return "/recipes/%s/" % self.id 

class UnitOfMeasure(models.Model): 
    title = models.CharField(max_length=10, unique=True) 

    class Meta: 
     ordering = ['title'] 

    def __unicode__(self): 
     return self.title 

    def get_absolute_url(self): 
     return self.id 

class RecipeIngredient(models.Model): 
    quantity = models.DecimalField(max_digits=5, decimal_places=3) 
    unit_of_measure = models.ForeignKey(UnitOfMeasure) 
    ingredient = models.ForeignKey(Ingredient) 
    recipe = models.ForeignKey(Recipe) 

    def __unicode__(self): 
     return self.id 

:보기에

class AddRecipeForm(ModelForm): 
    class Meta: 
     model = Recipe 
     extra = 0 

그리고 관련 코드를 (입력이 삭제 된 양식을 구문 분석 호출) :

def raw_text(request): 
    if request.method == 'POST': 

    ...  

     form_data = {'title': title, 
        'description': description, 
        'directions': directions, 
        } 

     form = AddRecipeForm(form_data) 

     #the count variable represents the number of RecipeIngredients 
     FormSet = inlineformset_factory(Recipe, RecipeIngredient, 
         extra=count, can_delete=False) 
     formset = FormSet() 

     return render_to_response('recipes/form_recipe.html', { 
       'form': form, 
       'formset': formset, 
       }) 

    else: 
     pass 

    return render_to_response('recipes/form_raw_text.html', {}) 

위와 같이 FormSet()이 비어있어 페이지를 성공적으로 시작할 수 있습니다. 내가 포함 식별 한 양, unit_of_measure과 재료의 formset을 공급하는 몇 가지 방법이 시도 :

  • 초기 설정 데이터를하지만 사전을 통과 인라인 formsets
  • 작동하지 않습니다,하지만 관리를 생성 형식 오류는
  • 초기화와 함께 놀았지만이

내 깊이 크게 감사 어떤 제안 밖으로 조금 있어요.

답변

19

나의 첫번째 제안은 간단한 방법을 가지고하는 것입니다 다음 FormSet을 할 때 다음 인스턴스와 결과 Recipe를 사용 RecipeRecipeIngredient의 저장합니다. 양식 세트가 사용자에 의해 승인되었는지 여부를 나타 내기 위해 조리법에 "검토 됨"부울 필드를 추가 할 수 있습니다. 당신이 어떤 이유로 그 길을 가고 싶어하지 않는 경우

그러나이처럼 formsets을 채울 수있을 것입니다 :

우리는 당신이 조리법 성분에 텍스트 데이터를 분석 한 것으로 가정합니다

recipe_ingredients = [ 
    { 
     'ingredient': 2, 
     'quantity': 7, 
     'unit': 1 
    }, 
    { 
     'ingredient': 3, 
     'quantity': 5, 
     'unit': 2 
    }, 
] 

은 "성분"및 "부"필드의 수는 측정 대상의 각 성분 단위의 주요 키 값은 다음과 이와 같은 사전의 목록을 갖는다. 이미 텍스트를 데이터베이스의 재료와 일치 시키거나 새로운 재료를 작성하는 방법을 공식화했다고 가정합니다.

그런 다음 수행 할 수 있습니다

RecipeFormset = inlineformset_factory(
    Recipe, 
    RecipeIngredient, 
    extra=len(recipe_ingredients), 
    can_delete=False) 
formset = RecipeFormset() 

for subform, data in zip(formset.forms, recipe_ingredients): 
    subform.initial = data 

return render_to_response('recipes/form_recipe.html', { 
    'form': form, 
    'formset': formset, 
    }) 

이것은 당신의 recipe_ingredients 목록에서 사전에 해당 formset에서 각 양식의 initial 속성을 설정합니다. 그것은 formset 표시의 측면에서 나를 위해 작동하는 것,하지만 난 아직 저장을 시도하지 않았습니다.django.utils.functional -

+0

대단히 감사합니다. 아람, 정말 고마워요. 나는 오늘 옵션을 시도 할 것이다. 나는 특히 쉬운 옵션을 가지고있는 것을 좋아합니다 ... – Sinidex

+0

지퍼 사용은 분명히 작동하며 일반적인 패션에서 양식을 저장하는 것이 잘 작동하는지 확인할 수 있습니다. 필자가 지적한 바와 같이 구문 분석 된 텍스트를 관련 재료와 측정 단위 개체와 조화시켜야하지만, 관리가 가능해야한다고 생각합니다. 훌륭한 해결책. – Sinidex

+1

예 예 및 예. 이것은 훌륭한 해결책입니다! 나는이 일에 어려움을 겪었다. 처음에는 세트의 각 양식을 작성하는 방법을 살펴 보았습니다. 그런 다음 실현 된 초기 *는 form (formset이 아닌) 기준으로 작동합니다. In zip we trust ™ – Flowpoke

0

나는 아람 Dulyan 코드가 나는 cached_property에게

형태를 반복 할 수 분명히 뭔가 장고 1.8에서 변경이

for subform, data in zip(formset.forms, recipe_ingredients): 
    subform.initial = data 

에서 작동 할 수 없었다. 0x7efda9ef9080

에서 cached_property 객체는이 오류를 가지고

https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform

:

우편 인수가 1이 반복

을 지원해야하지만 난 여전히 사전을 내 해당 formset에 직접 할당하고이 일을, 내가 여기에서 예를했습니다 from django.forms import formset_factory myapp.forms에서 가져온 에서 가져 오기 ArticleForm

ArticleFormSet = formset_factory(ArticleForm, can_order=True) 
formset = ArticleFormSet(initial=[ 
    {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)}, 
    {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, 
]) 

formset을 템플릿에 할당하는 코드

return self.render_to_response(
self.get_context_data(form=form, inputvalue_numeric_formset=my_formset(initial=formset_dict)