内联表单集只保存最后一个表单 [英] inline formset only save the last form
问题描述
我尝试了很多方法并搜索了很多(谷歌搜索)但没有人为我工作.每当我保存内联表单集时,它只会保存最后一个表单,我的模型.py
class Book(models.Model):book = models.CharField(max_length=20,unique=True)author = models.ForeignKey(Author,on_delete=models.CASCADE)类作者(模型.模型):author = models.CharField(max_length=30,unique=True)count = models.IntegerField()
这是我的forms.py
class AuthorForm(ModelForm):元类:模型 = 作者字段 = ['作者','计数']类 BookForm(ModelForm):元类:模型 = 书字段 = ['书']InlineFormset_Author = inlineformset_factory(Author,Book,form=BookForm,extra=1)
这是我的看法
class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView):模型 = 作者form_class = AuthorFormdef get_context_data(self,*args,**kwargs):context = super(CreateBookView,self).get_context_data(*args,**kwargs)如果 self.request.POST:context['book'] = InlineFormset_Author(self.request.POST)context['book'] = InlineFormset_Author()返回上下文def form_valid(self,form):上下文 = self.get_context_data()上下文 = 上下文['书']使用 transaction.atomic():self.object = form.save()如果 context.is_valid():context.instance = self.object上下文.save()return super(CreateBookView,self).form_valid(form)
这是我的模板
<div class='modal-footer'></form><脚本>$(document).ready(function(){$('#BOOKBTN').on('click',function () {让 allValue=[];让 numberOfInput=$('#count').val();让所有内容='';让 justforName=0;let numOfContent=$('.modal-body input').length;for(let j=0;j 我使用小部件调整为我的输入字段提供类和 ID我错过了什么吗?或者我可能做错了什么?!我准备付钱让它工作感谢您的建议 我已经好几年没有在 Django 上做过任何工作了,但我会尝试对您的代码进行注释并添加我的想法. 就像我说的,我已经好几年没有做过任何 Django 了,所以我只是指的是我的一些旧代码(可能已经过时)来自 https://github.com/timhughes/django-cbv-inline-formset/blob/master/music/views.py#L26 我会用评论来注释. i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form ,
my models.py this is my forms.py this is my view and this is my template i have used widget tweaks to provide classes and ids to my input fields
does i have missed something ? or i maybe i do something wrongly ?!
and i'm ready to pay to get it working
thanks for any advice It is several years since I did any work on Django but I will have a go at annotating your code and adding my thoughts. Like I said, I haven't done any Django in several years, so I am just referring to some of my old code (which may be outdated) from https://github.com/timhughes/django-cbv-inline-formset/blob/master/music/views.py#L26 which I will annotate with comments.
这篇关于内联表单集只保存最后一个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!def form_valid(self,form):context = self.get_context_data() # 这一行看起来不错context = context['book'] # 你在这里覆盖你的上下文,调用这个使用 transaction.atomic():self.object = form.save() # 你在这里保存,再往下保存,这也是设置 self 对象,可能不正确.如果 context.is_valid():context.instance = self.object上下文.save()return super(CreateBookView,self).form_valid(form)
def form_valid(self, form):context = self.get_context_data(form=form) # 获取相关表单的上下文数据.formset = context['track_formset'] # 从上下文中提取表单集.if formset.is_valid(): # 验证表单集是否有效response = super().form_valid(form) # 调用父类的form_valid.formset.instance = self.object # 设置formset类型(self.object的实例),让django知道如何保存.formset.save() # 在这里保存表单集return response # 向用户发送响应别的:return super().form_invalid(form) # 向用户发送无效表单信息的响应.
class Book(models.Model):
book = models.CharField(max_length=20,unique=True)
author = models.ForeignKey(Author,on_delete=models.CASCADE)
class Author(models.Model):
author = models.CharField(max_length=30,unique=True)
count = models.IntegerField()
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['author','count']
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['book']
InlineFormset_Author = inlineformset_factory(Author,Book,form=BookForm,extra=1)
class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView):
model = Author
form_class = AuthorForm
def get_context_data(self,*args,**kwargs):
context = super(CreateBookView,self).get_context_data(*args,**kwargs)
if self.request.POST:
context['book'] = InlineFormset_Author(self.request.POST)
context['book'] = InlineFormset_Author()
return context
def form_valid(self,form):
context = self.get_context_data()
context = context['book']
with transaction.atomic():
self.object = form.save()
if context.is_valid():
context.instance = self.object
context.save()
return super(CreateBookView,self).form_valid(form)
<form method="POST">{% csrf_token %}
{{book.management_form}}
{{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}}
{{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}}
<button class="col-4 mx-auto shadow-lg border-right border-left">insert</button>
<div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true">
<div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header">
<h5 class="modal-title" id="my-modal-title">BOOK</h5>
<p class="close" data-dismiss="modal" aria-label="Close">
<div class="modal-body">
<button type="submit" class="btn btn-success">save</button></dic>
</div>
<div class='modal-footer'></form>
<script>
$(document).ready(function(){
$('#BOOKBTN').on('click',function () {
let allValue=[];
let numberOfInput=$('#count').val();
let allContent='';
let justforName=0;
let numOfContent=$('.modal-body input').length;
for(let j=0;j<numOfContent;j++){
justforName=j+1;
allValue.push($('input[name="BOOK'+justforName+'"').val());
}
if(numOfContent!=numberOfInput){
for(let i=0;i<numberOfInput;i++){
justforName=i+1;
{% for i in book.forms %}
allContent+='{{i.book}}';
{% endfor %}
}
$('.modal-body').html(allContent);
}
for(let j=0;j<allValue.length;j++){
justforName=j+1;
$('input[name="BOOK'+justforName+'"').val(allValue[j])
}})})
</script>
def form_valid(self,form):
context = self.get_context_data() # This line looks fine
context = context['book'] # You are overwriting your context here, call this
with transaction.atomic():
self.object = form.save() # Your have a save here and one further down, this is also setting self object which may be incorrect.
if context.is_valid():
context.instance = self.object
context.save()
return super(CreateBookView,self).form_valid(form)
def form_valid(self, form):
context = self.get_context_data(form=form) # Get the context data for the form in question.
formset = context['track_formset'] # Extract the formset out of the context.
if formset.is_valid(): # Validate the formset is valid
response = super().form_valid(form) # Call the parent class's form_valid.
formset.instance = self.object # Set the formsets type (instance of self.object) so that django knows how to save it.
formset.save() # Save the formset here
return response # Send a response to the user
else:
return super().form_invalid(form) # Send a response to the user with invalid form information.