简体   繁体   中英

Django inlineformset_factory and ManyToManyField field, once again

first of all, sorry for my English! I have a little problem with "inlineformset_factory" and "ManyToManyField". Perhaps the option "inlineformset_factory" isn't the right choice. I have two classes, Prodotti and Categoria. In models.py are

class Categoria(models.Model):
    ''' tabella delle Categorie dei prodotti '''
    NomeCategoria = models.CharField(max_length=50,blank=True,null=True)
class Prodotti(models.Model):
    ''' tabella Prodotti a catalogo '''
    NomeProdotto = models.CharField(max_length=50,blank=True,null=True)
    CategoriaProdotto = models.ManyToManyField(Categoria, related_name='prodotti_categoria')

I need a form to modify the name of a specific Categoria, es. Antiossidante, and eventually change the list of Prodotti that have this Categoria. I try a lot with "inlineformset_factory" and the use of "Prodotti.CategoriaProdotto.through" but I have problems with fields, only "id" is accepted. ie

ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',))

But, changing the name of Categoria it isn't saved. This is my project:

views.py

def ModificaCategoria(request, pk):
    # recuperiamo la categoria da modificare, bisogna passare l'ID
    categoria = get_object_or_404(Categoria, pk=pk)
    ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',))

    if request.method == "POST":
        form = CategoriaModelForm(request.POST, request.FILES, instance=categoria)
        formset = ProdottiFormset(request.POST, instance=categoria)
        if formset.is_valid():
            formset.save()
            return render(request, "dopo_modifica_categoria.html")
            # return redirect(...)
    else:
        categoria = Categoria.objects.get(pk=pk)
        form = CategoriaModelForm(instance=categoria)
        formset = ProdottiFormset(instance=categoria)

    context = {
        "form": form,
        "formset": formset,
        }
    return render(request, "modifica_categoria.html", context)

Template:

{% extends 'base.html'%}
{% block head_title %}{{ block.super }} - Modifica categoria{% endblock head_title %}
{% load crispy_forms_tags %}
{% block content %}
    <form method="post">
        {% csrf_token %}
        {{ form.NomeCategoria|as_crispy_field }}
        {{ formset.as_p }}
        <button type="submit" class="btn btn-primary btn-sm">Modifica</button>
        <br>
    </form>
{% endblock content %}

And form.py

class CategoriaModelForm(forms.ModelForm):
    class Meta:
        model = Categoria
        fields = "__all__"

Thank you very much for every suggestion!

The next step should create a new Categoria and Prodotti in that Categoria.

If you are trying to save NomeCategoria then currently you are saving formset but not the form. Save the form and I guess this will solve your problem.

By modifying view I was also able to save new products in that specific category:

def ModificaCategoria(request, pk):
    # recuperiamo la categoria da modificare, bisogna passare l'ID
    categoria = get_object_or_404(Categoria, pk=pk)
    ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, exclude=['id',])

    if request.method == "POST":
       form = CategoriaModelForm(request.POST, request.FILES, instance=categoria)
       formset = ProdottiFormset(request.POST, instance=categoria)
       if formset.is_valid() and form.is_valid():
          formset.save()
          form.save()
          return render(request, "dopo_modifica_categoria.html")
    else:
        categoria = Categoria.objects.get(pk=pk)
        form = CategoriaModelForm(instance=categoria)
        formset = ProdottiFormset(instance=categoria)

    context = {
       "form": form,
       "formset": formset,
       }
    return render(request, "modifica_categoria.html", context) 

Goal!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM