Поле django manytomany с использованием сквозного и formwizard

Я пытаюсь создать довольно сложную форму и разбить ее с помощью мастера форм. Первое, что я пытаюсь сделать, это использовать ManyToManyField для отображения. Затем мне нужно выяснить, как все это сохранить.

#models.py
----------------------

class Meat(models.Model):
    name = models.charField(max_length=200)
    company = models.CharField(max_length = 200)

class Starch(models.Model):
    name = models.CharField(max_length=200)
    company = models.CharField(max_length=200)



class Recipe(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(help_text='Please describe the finished dish')
    meat = models.ManyToManyField('Meat' through='RecipeMeat')
    meat_notes = models.TextField()
    starch = models.ManyToManyField('Starch' through='RecipeStarch')
    starch_notes = models.TextField()



class RecipeMeat(models.Model):
    recipe = models.ForeignKey(Recipe)
    meat = models.ForeignKey(Meat)
    qty = models.FloatField()

class RecipeStarch
    recipe = models.ForeignKey(Recipe)
    starch = models.ForeignKey(Starch)
    qty = models.FloatField()

.

#forms.py
-------------------

class RecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('name', 'description')


class RecipeMeatForm(forms.ModelForm):
    class Meta:
        model = RecipeMeat

class RecipeMeatNotesForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('meat_notes',)

class RecipeStarch(forms.ModelForm):
    class Meta:
        model = RecipeStarch

class RecipeStarchNotesForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('starch_notes')

MeatFormSet = inlineformset_factory(Recipe, RecipeMeat, form=RecipeMeatForm, extra=1)

.

#views.py
---------------------------


class CreateRecipeWizard(SessionWizardView):
    template_name = "create-recipe.html"
    instance =  None
    file_storage = FileSystemStorage(location= 'images')

    def dispatch(self, request, *args, **kwargs):
        self.instance = Recipe()
        return super(CreateRecipeWizard, self).dispatch(request, *args, **kwargs)

    def get_form_instance( self, step ):
        return self.instance

    def done( self, form_list, **kwargs ):
         self.instance.save()
        return HttpResponseRedirect(reverse(all-recipes))

.

#urls.py
------------------------------

 url(r'^create-recipe/$', views.CreateRecipeWizard.as_view([RecipeForm, MeatFormSet, RecipeMeatNotesForm, RecipeStarchNotesForm]), name='create-recipe'),

.

Я немного новичок в этом django. Часть «Рецепт» намного длиннее и сложнее, но примерно такая же схема. Если бы кто-нибудь мог помочь мне правильно указать, как заставить мой ManyToManyField использовать сквозную часть, выясненную или указывающую в правильном направлении, я был бы очень признателен.


person user3184091    schedule 16.01.2014    source источник


Ответы (1)


Чтобы сохранить отношение ManyToMany в процессе мастера форм, вы можете сделать что-то вроде этого;

def done(self, form_list, **kwargs):
    form_data_dict = self.get_all_cleaned_data()
    m2mfield = form_data_dict.pop('m2mfield')

    instance = form_list[0].save()
    for something in m2mfield:
        instance.m2mfield.add(something)

    return render_to_response(
        'done.html', {},
        context_instance=RequestContext(self.request)
    )

В этом примере первая форма в списке — это ModelForm для вещи, которую я пытаюсь создать, и она имеет ManyToManyField для другой модели, для которой у меня есть форма, вторая в процессе. Итак, я беру эту первую форму и сохраняю ее, затем беру поле из очищенных данных из второй формы и сохраняю выбранные параметры в поле M2M.

person markwalker_    schedule 24.04.2015