我想向项目添加一项功能,只有经过身份验证的用户才能访问其内容。但是,当我编写queryset时,它会引发类似ModelNameFormSet object has no request attribute
views.py
class BaseAuthorFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queryset = Project.objects.filter(author_id=self.request.user.pk)
def add_object(request):
ProjectFormSet = modelformset_factory(Project, formset=BaseAuthorFormSet, fields=( 'service_name', 'service_code', 'report_month', 'report_year', 'last_year'), extra=1)
if request.method == "POST":
form = ProjectFormSet(request.POST)
form.author = request.user
if form.is_valid():
form.save()
form = ProjectFormSet()
return render(request, 'app1/home.html',{'form':form})
我只有这个代码。我该如何解决这个问题?预先谢谢你!
答案 0 :(得分:0)
如果您需要表单集中的请求,则需要将其传递给表单。另外请注意,将作者添加到表单集不会执行任何操作,您需要将其添加到每个表单保存的结果中。
class BaseAuthorFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
self.queryset = Project.objects.filter(author_id=self.request.user.pk)
def add_object(request):
ProjectFormSet = modelformset_factory(Project, formset=BaseAuthorFormSet, fields=( 'service_name', 'service_code', 'report_month', 'report_year', 'last_year'), extra=1)
if request.method == "POST":
formset = ProjectFormSet(request.POST, request=request)
if formset.is_valid():
for form in formset:
obj=form.save(commit=False)
obj.author = request.user
obj.save()
return redirect('somewhere')
form = ProjectFormSet(request=request)
return render(request, 'app1/home.html',{'form':form})