我正在尝试使用内联formset创建公司开盘和收盘时间,即周一至周五,每天的开盘和收盘时间不同。
公司简介表格是常规模型。 我在它下面加载的公司时间是一个模型形式集,其id从公司简介表格中传递。
模型形式和modelformset加载精细以创建。 modelform在编辑时加载预先选择的值,但不加载modelformset。 我不知道我是否在创建时保存了任何内容,因为当我尝试编辑实例时,我得到一个空的模型集。
我应该在这里做些什么来确保modelformset保存选定的选项或在编辑时加载预先选择的选项?
def addprofile(request):
current_user = request.user
company = Company() ##To create new instance
#company = Company.objects.get(id= request.session['my_ids']) ## To get old instance
OpeningHourslineFormSet = inlineformset_factory(Company, OpeningHours, form=OpeningHoursForm, extra=7 )##fields=("weekday", "fromHour","fromMinute", "toHour", "toMinute")
if request.session['entry_count'] > 1:
messages.success( request, 'You can only create two business profiles now' )
return HttpResponseRedirect( reverse('home') )
else:
if request.method == 'POST':
hourformset = OpeningHourslineFormSet(request.POST, request.FILES, instance=company)
form = CompanyForm(request.POST)
###### deal with hourformset here
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.pub_date= timezone.now()
model_instance.user= current_user.id
model_instance.save()
else:
print("companyform not saved")
###################
if hourformset.is_valid():
hourformset.save(commit=False)
for product in hourformset:
if product.is_valid():
product.save(commit=False)
product.company = model_instance.id
product.save()
instances = hourformset.save()
else:
print(" modelform not saved")
return HttpResponseRedirect('/bizprofile/success')
else:
hourformset = OpeningHourslineFormSet(instance=company)
form = CompanyForm()
context = {'hourformset': hourformset, 'form': form}
return render_to_response('bizprofile/addprofile.html', context, context_instance=RequestContext(request))
答案 0 :(得分:0)
我认为您需要为formset提供一个查询集,以便显示已保存的实例:
# hours is a queryset that you got from company, pseudo code here
hours = company.hours.all()
hourformset = OpeningHourslineFormSet(request.POST,
request.FILES,
queryset=hours)
答案 1 :(得分:0)
通过以下链接回答:
Django modelform not saving input choices and not returning errors
将不同的数据类型保存到不同的模型字段类型时出现问题。