Проблема с добавлением и изменением инстанса в админке django
Я пытаюсь из админки добавить или изменить экземпляр модели - CompletedWork. Ошибка:
TypeError at /admin/ReportingTool/completedwork/68/change/ init() отсутствует 1 необходимый позиционный аргумент: 'user'
моя модель:
class CompletedWork(models.Model):
period = models.ForeignKey(directory.Period,
on_delete=models.SET('deleted date'),
)
worker = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET('deleted worker'),
related_name='worker_do', default=settings.AUTH_USER_MODEL
)
work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type'))
work_scope = models.FloatField(blank=True, null=True)
work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, )
record_author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET('deleted user'),
related_name='record_author', auto_created=True,
)
record_date = models.DateTimeField(auto_now=True)
checked_by_head = models.BooleanField(default=False)
active = models.BooleanField(default=True)
def __repr__(self):
return f'{self.period}, {self.worker}, {self.work_done}'
def __str__(self):
return self.__repr__()
def is_active(self):
if self.active:
return True
return False
моя форма:
class CompletedWorkForm(forms.ModelForm):
class Meta:
model = CompletedWork
fields = (
'period',
'worker',
'work_done',
'work_scope',
'work_notes',
)
def __init__(self, user, *args, **kwargs):
if kwargs.get('record_author'):
self.user = kwargs.pop('record_author')
super(CompletedWorkForm, self).__init__(*args, **kwargs)
if user.struct_division:
if user == user.struct_division.head:
self.fields['worker'] = forms.ModelChoiceField(
queryset=
CustomUser.objects.filter(struct_division=
user.struct_division).order_by('last_name') |
CustomUser.objects.filter(struct_division__management_unit=
user.struct_division).order_by('last_name')
)
elif StructuralDivisions.objects.filter(curator=user):
sd_user_curator = StructuralDivisions.objects.filter(curator=user)
self.fields['worker'] = forms.ModelChoiceField(
queryset=
CustomUser.objects.filter(struct_division__in=sd_user_curator) |
CustomUser.objects.filter(id=user.pk)
)
else:
self.fields['worker'] = forms.ModelChoiceField(
queryset=CustomUser.objects.filter(id=user.pk)
)
self.fields['work_done'] = forms.ModelChoiceField(
queryset=WorksType.objects.filter(available_to=user.struct_division)
)
def save(self, commit=True):
obj = super(CompletedWorkForm, self).save(commit=False)
if commit:
obj.user = self.instance.record_author
obj.save()
return obj
Мое мнение:
class EditCompletedWorkView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = CompletedWork
form_class = CompletedWorkForm
template_name = 'completed_work_edit.html'
context_object_name = 'editcompletedwork'
success_url = None
success_message = 'Record successfully updated'
def get_form_kwargs(self):
kwargs = super(EditCompletedWorkView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
def get(self, request, *args, **kwargs):
print(self)
EditCompletedWorkView.success_url = request.META.get('HTTP_REFERER')
return super().get(request, *args, **kwargs)
когда я делаю это с сайта - у меня нет проблем. только когда я делаю это из Django admin. В admin.py у меня вот так:
class CompletedWorkAdmin(admin.ModelAdmin):
form = CompletedWorkForm
list_display = ['period', 'worker', 'work_done', 'work_scope', 'work_notes', 'checked_by_head', 'active',
'record_author', 'record_date', ]
readonly_fields = ['record_author', 'record_date']
list_filter = (
('period', RelatedOnlyDropdownFilter),
('worker', RelatedOnlyDropdownFilter),
('record_author', RelatedOnlyDropdownFilter),
('checked_by_head', DropdownFilter),
('active', DropdownFilter),
)
ordering = ['period', 'worker']
search_fields = ('worker__last_name', 'worker__first_name', 'worker__middle_name', 'work_done__name')
def save_model(self, request, obj, form, change):
obj.record_author = request.user
super().save_model(request, obj, form, change)
Пожалуйста, помогите мне, если знаете, что не так