我无法使用generic_inlineformset_factory
保存我的前端选择。
如果我没有在前端选择任何内容,则行sports = sports_formset.save(commit=False)
不会产生任何错误,但如果我选择了任何内容,我会'NoneType' object has no attribute '_meta'
代码底部的# PROBLEM PART
。
# models
class M2MProfilesToSportTypeGroups(models.Model):
MASTERY_CHOICES = (
(1, _('newby')),
(2, _('amateur')),
(3, _('semi-pro')),
(4, _('pro'))
)
mastery = models.IntegerField(_('mastery'), null=True, blank=True, choices=MASTERY_CHOICES)
sport_type_group = models.ForeignKey(SportTypesGroups, verbose_name=_('sport type group'))
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
# views
class CompanyProfileCreateView(LoginRequiredMixin, TemplateView):
template_name = 'profiles/create_n_update.html'
def get(self, request, *args, **kwargs):
profile_form = CompanyProfileForm() #show_criterias=False)
PlaceTypeFormSet = inlineformset_factory(CompanyProfiles, M2MCompanyProfilesToPlaceTypeGroups,
fields='__all__', can_delete=False)
SportTypeFormSet = generic_inlineformset_factory(M2MProfilesToSportTypeGroups,
can_delete=False)
places_formset = PlaceTypeFormSet()
sports_formset = SportTypeFormSet()
return self.render_to_response({'form': profile_form,
'places_formset': places_formset,
'sports_formset': sports_formset})
def post(self, request, *args, **kwargs):
profile_form = CompanyProfileForm(data=request.POST)
PlaceTypeFormSet = inlineformset_factory(CompanyProfiles, M2MCompanyProfilesToPlaceTypeGroups,
fields='__all__', can_delete=False)
SportTypeFormSet = generic_inlineformset_factory(M2MProfilesToSportTypeGroups,
can_delete=False)
places_formset = PlaceTypeFormSet(data=request.POST)
sports_formset = SportTypeFormSet(data=request.POST)
if profile_form.is_valid() and places_formset.is_valid() and sports_formset.is_valid():
profile_form.instance.created_by = request.user
company_profile = profile_form.save()
places = places_formset.save(commit=False)
for place in places:
place.company_profile = company_profile
place.save()
# PROBLEM PART
sports = sports_formset.save(commit=False)
for sport in sports:
obj.content_object = company_profile
obj.save()
return redirect(company_profile)
return self.render_to_response({'form': profile_form,
'places_formset': places_formset,
'sports_formset': sports_formset})
任何建议表示赞赏。
答案 0 :(得分:0)
找到解决方案。
# PROBLEM PART
已更改:
sports_formset = SportTypeFormSet(data=request.POST, instance=company_profile)
sports_formset.save()
提供company_profile
我们让Django找出要使用的content_type
和object_id
类型。