English 中文(简体)
django 习俗
原标题:django Custom ManyToMany save on model Formset Options

I have a formset that is setup to use a join table. The join table joins a Recipe table and an Ingredient table and looks like thus

class RecipeIngredient(models.Model): 
       intermediate model between Ingredient and recipe.models.recipe 
for many to many    
    quantity =  models.IntegerField() 
    measurement = models.CharField(max_length=200) 
    ingredient = models.ForeignKey(Ingredient) 
    preparation = models.CharField(max_length=100, blank=True, 
null=True) 
    recipe    = models.ForeignKey(Recipe) 

我创造了这样的表格。

IngFormSet = inlineformset_factory(Recipe, RecipeIngredient, 
formset=BaseIngFormSet, extra=5) 

The BaseIngFormSet was created to turn the default drop down menu for the ingredient field (many to many with the Ingredient table), into a input box so that I could then later use jquery-autocomplete on the input box. This would save some time from users having to scroll a very long list of ingredients to select from.

class BaseIngFormSet(BaseModelFormSet): 
    def add_fields(self, form, index): 
        super(BaseIngFormSet, self).add_fields(form,index) 
        form.fields["ingredient"] = forms.CharField() 

That part that I am currently stuck on is, when the form is submitted it fails because the ingredient is no longer in instance of the ingredient table

Cannot assign "u Ground Turkey ": "RecipeIngredient.ingredient" must be a "Ingredient" instance.

I figured I need to take what is typed into the input box, then do a search on it against the Ingredient model something like Ingredient.objects.get(title="blah")

Then somehow set that object to the RecipeIngredient.ingredient in the formset, before the formset is validated. Sadly though I do not know where or how to do this. I tried going into the shell and setting up the formset then doing a dir(formset) on it to see if that would shed any light on my issue but I didn t come up with anything. Does anyone have any suggestions on how to take what is passed in the ingredient input for the formset, and turn that into an object from the Ingredient table? I know at some point a user may type in an ingredient that is not in the database, and I plan on doing a lookup on what is passed, and if it is not found in the database, I would create it and then pass that new object to the formset. Here is what I currently have in my view for this form

from django.shortcuts import render_to_response, get_object_or_404, 
get_list_or_404, redirect 
from django.template import RequestContext 
from django.contrib.auth.decorators import login_required 
from django.forms.models import modelformset_factory, 
inlineformset_factory 
from models import Recipe, RecipeIngredient 
from ingredient.models import Ingredient 
from forms import RecipeForm, BaseIngFormSet 
@login_required 
def recipe(request): 
    IngFormSet = inlineformset_factory(Recipe, RecipeIngredient, 
formset=BaseIngFormSet, extra=5) 
    if request.method== POST : 
        form = RecipeForm(request.POST, request.FILES) 
        formset = IngFormSet(request.POST) 
        if form.is_valid() and formset: 
            new_recipe = form.save() 
            instances = formset.save(commit=False) 
            for instance in instances: 
                instance.recipe_id = new_recipe.id 
                instance.save() 
            return redirect(new_recipe.get_absolute_url()) 
    else: 
        form = RecipeForm() 
        formset = IngFormSet(queryset=RecipeIngredient.objects.none()) 
    return render_to_response( recipe/recipe_form.html , { form : 
form,  formset  : formset,}, context_instance=RequestContext(request)) 

感谢您能够提供的任何帮助。

问题回答

您是否考虑使用一只杂草料,而后再作验证。 或许如。 ? 如果确实如此,请看<代码>fields.py文档及其习惯形式领域。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签