回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>首先,对不起我的英语!
我对“inlineformset_工厂”和“ManyToManyField”有点问题。也许“inlineformset_工厂”选项不是正确的选择。
我有两门课,Prodotti和Categoria。在models.py中是</p>
<pre><code>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')
</code></pre>
<p>我需要一个表单来修改特定类别的名称。抗骨化剂,并最终改变具有此分类的Prodotti的列表。
我在“inlineformset_factory”和“Prodotti.CategoriaProdotto.through”的使用方面做了很多尝试,但是我在字段方面遇到了问题,只接受了“id”。i、 e</p>
<pre><code>ProdottiFormset = inlineformset_factory(Categoria, Prodotti.CategoriaProdotto.through, fields=('id',))
</code></pre>
<p>但是,更改Categoria的名称不会保存。
这是我的项目:</p>
<pre><code>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)
</code></pre>
<p>模板:</p>
<pre><code>{% 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 %}
</code></pre>
<p>和form.py</p>
<pre><code>class CategoriaModelForm(forms.ModelForm):
class Meta:
model = Categoria
fields = "__all__"
</code></pre>
<p>非常感谢你的每一个建议</p>
<p>下一步应该创建一个新的Categoria和该Categoria中的Prodotti</p>