I put together a form to save the recipe. It uses a form and an integrated set of forms. I have users with text files containing recipes, and they would like to cut and paste the data to make recording easier. I have developed how to fill out part of the form after processing the original text input, but I cannot figure out how to fill out the inline set of forms.
It seems like the solution is almost spelled out here: http://code.djangoproject.com/ticket/12213 , but I canβt completely compose the fragments.
My models:
#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
A recipe form is created using ModelForm:
class AddRecipeForm(ModelForm): class Meta: model = Recipe extra = 0
And the corresponding code in the view (calls to parse form inputs are deleted):
def raw_text(request): if request.method == 'POST': ... form_data = {'title': title, 'description': description, 'directions': directions, } form = AddRecipeForm(form_data)
With FormSet () empty as above, I can successfully launch the page. I tried several ways to feed a set of forms with the quantity, unit of measurability, and the ingredients that I identified, including:
- setting the initial data, but this does not work for inline forms.
- dictionary submission but which generates control form errors
- played with init , but I'm a bit out of depth.
Any suggestions that were highly appreciated.
python django forms inline-formset
Sinidex
source share