django 在ModelChoiceField中使用'request'的更好方法是什么

rlcwz9us  于 2023-04-13  发布在  Go
关注(0)|答案(2)|浏览(110)

有没有办法在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')
wyyhbhjk

wyyhbhjk1#

你不能直接访问模型定义中的request对象,因为模型是在worker启动时解析的,远早于有人发出请求。但是你可以在constructor中传递对象。

class AlbumForm(forms.Form):

    def __init__(self,*args,**kwargs):
        user=kwargs.pop('user',None)
        super(AlbumForm, self).__init__(*args, **kwargs)
        if user:
            self.fields['album'].queryset = Album.objects.filter(user=user)

    album = ModelChoiceField(queryset=Album.objects.none())

然后,在视图中,您必须像这样创建表单:

def some_view(request):
    form = AlbumForm(user=request.user)
    ...
    return render(request, 'template.html', {"form": form})
f87krz0w

f87krz0w2#

我之所以得到NameError是因为请求对象在表单定义的范围内不可用。
我重写了表单的__init__方法,并将user对象作为参数传递给表单:

class AlbumForm(forms.Form):
    album = ModelChoiceField(queryset=Album.objects.none())

    def __init__(self, *args, **kwargs):
        super(AlbumForm, self).__init__(*args, **kwargs)
        self.fields['album'].queryset = Album.objects.filter(user=user)

在我的CreateOurColumn视图中,内部:get_context_data方法,我忘记将user对象传递给AlbumForm

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(user=self.request.user)
    return context

这样,AlbumForm将根据传递给它的用户对象过滤queryset
感谢answer

相关问题