Opened 9 years ago

Closed 9 years ago

#25023 closed Cleanup/optimization (invalid)

Many to Many through - save new Data

Reported by: trap12 Owned by: nobody
Component: Forms Version: 1.8
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,

I am new in Django and have problems with the M2M-Fields with a custom join table (through). I want to to save new Data (no duplicate). But the form shows me just the data in the db, which I can select.
I have no access to the through-table "RecipeIngredients" which links the ingredient with the recipe and holds the quantity.

I want to have a dynamic field, where I can add also new ingredient, which are not in the db. And I want to add the field quanity in the RecipeForm. (problem: the quantity field is not in the model Recipe, it is in the RecipeIngredients)

models.py:

class Ingredient(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

class Recipe(models.Model):
    id = models.AutoField(primary_key=True)
    recipename = models.CharField(max_length=200)
    author = models.ForeignKey(Student, null=True)
    pub_date = models.DateTimeField('date published', editable=False)
    ingredients = models.ManyToManyField(Ingredient, through='Recipeingredients')
    description = models.CharField(max_length=20000)

     
class Recipeingredients(models.Model):
    id = models.AutoField(primary_key=True)
    ingredient = models.ForeignKey(Ingredient)
    recipe = models.ForeignKey(Recipe)
    quantity = models.CharField(max_length=30)

forms.py:

class RecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        exclude = ('id', 'author', 'pub_date')

views.py:

@login_required
def create(request):
    if request.method == 'POST':
        form = RecipeForm(user=request.user, data=request.POST)
        if form.is_valid():
            recipe = form.save()
            
            return HttpResponseRedirect(recipe.get_absolute_url())
    else:
        form = RecipeForm()
        
    return render(request, 'recipes/create.html', {'form': form}}

create.html:

<form action="{{ action_url }}" method="post" accept-charset="utf-8">
    {{ form.as_p }}
    {% csrf_token %}
    
    <p><input type="submit" value="Save"/></p>
</form>

Like I said, I have no textfield to add new ones.

Do you know what I have to change?

thanks in advance!!!

regards,
trap123

Change History (1)

comment:1 by Moritz Sichert, 9 years ago

Resolution: invalid
Severity: Release blockerNormal
Status: newclosed

This is the django bug tracker. It's used for the development of django itself.

If you need help try #django on irc.freenode.net or the django users mailing list:
https://groups.google.com/forum/#!forum/django-users

Note: See TracTickets for help on using tickets.
Back to Top