#django #django-views #django-contenttypes
#django #django-представления #django-contenttypes
Вопрос:
Я не могу сохранить свои интерфейсные варианты, используя 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})
Любой совет приветствуется.
Ответ №1:
Найдено решение.
Изменен # PROBLEM PART
:
sports_formset = SportTypeFormSet(data=request.POST, instance=company_profile)
sports_formset.save()
При company_profile
условии, что мы позволим Django выяснить, какой тип content_type
и object_id
использовать.