使ModelForm与Django中的中间模型具有ManyToMany关系的步骤是什么?
发布于 2021-01-29 15:09:27
- 我有一个 客户 和 群组 模型。
- 一个 客户端 可以是多个的一部分 群体 。
- __属于组的 客户 可以随时使用其组的免费租金,但只能使用一次。这就是中间模型( ClientGroupe )附带这些额外数据的地方。
现在,当我尝试保存m2m数据时,它消失了,并说我应该使用ClientGroupe Manager …所以缺少了什么?
这是我的模型:
class Groupe(models.Model):
nom = models.CharField(max_length=1500, blank=True)
class Client(models.Model):
nom = models.CharField(max_length=450, blank=True)
prenom = models.CharField(max_length=450, blank=True)
groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe')
class ClientGroupe(models.Model):
client = models.ForeignKey(Client)
groupe = models.ForeignKey(Groupe)
dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate
class Meta:
db_table = u'clients_groupes'
这是我的看法:
def modifier(request, id):
client = Client.objects.get(id=id)
form = ClientForm(instance = client)
dict = {
"form": form
, "instance" : client
}
if request.method == "POST":
form = ClientForm(request.POST, instance = client)
if form.is_valid():
client_mod = form.save()
id = client_mod.id
return HttpResponseRedirect(
"/client/%(id)s/?err=success" % {"id" : id}
)
else:
return HttpResponseRedirect(
"/client/%(id)s/?err=warning" % {"id" : id}
)
return render_to_response(
"client/modifier.html"
, dict
, context_instance=RequestContext(request)
)
编辑 :
这是ClientForm代码:
class ClientForm(ModelForm):
class Meta:
model = Client
编辑#2 :这是错误消息:
AttributeError at /client/445/
Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead.
Request Method: POST
Request URL: http://localhost/client/445/
Exception Type: AttributeError
Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead.
Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574
Python Executable: C:\xampp\apache\bin\apache.exe
Python Version: 2.5.2
关注者
0
被浏览
55
1 个回答