有没有办法在ModelChoiceField
内部使用user=request.user
当我使用这个方法时,我得到了一个错误:NameError: name 'request' is not defined
。
class AlbumForm(forms.Form):
album = ModelChoiceField(queryset=Album.objects.filter(user=request.user)
型号:
class Album(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class CreateOurColumn(CreateView):
model = Column
success_url = reverse_lazy('List-Of-Column')
form_class = ColumnForm
template_name = 'create_column.html'
def get_context_data(self, *args, **kwargs):
context = super(CreateOurColumn, self).get_context_data(**kwargs)
context['formset'] = ColumnFormSet(queryset=Column.objects.none())
context['album_form'] = AlbumForm()
return context
def post(self, request, *args, **kwargs):
formset = ColumnFormSet(request.POST)
album_form = AlbumForm(data=request.POST)
if formset.is_valid() and album_form.is_valid():
return self.form_valid(formset, album_form)
def form_valid(self, formset, album_form):
album = album_form.cleaned_data['album']
instances = formset.save(commit=False)
for instance in instances:
instance.album = album
instance.save()
return HtppResponseRedirect('List-Of-Column')
2条答案
按热度按时间wyyhbhjk1#
你不能直接访问模型定义中的request对象,因为模型是在worker启动时解析的,远早于有人发出请求。但是你可以在
constructor
中传递对象。然后,在视图中,您必须像这样创建表单:
f87krz0w2#
我之所以得到
NameError
是因为请求对象在表单定义的范围内不可用。我重写了表单的
__init__
方法,并将user对象作为参数传递给表单:在我的
CreateOurColumn
视图中,内部:get_context_data
方法,我忘记将user对象传递给AlbumForm
:这样,
AlbumForm
将根据传递给它的用户对象过滤queryset
。感谢answer