什么是在ModelChoiceField中更好的使用 ‘request’ 的方式

huangapple go评论55阅读模式
英文:

What is a better way to use 'request' in a ModelChoiceField

问题

ModelChoiceField内使用user=request.user的方式,会导致错误NameError: name 'request' is not defined。这是因为在这个上下文中,request对象未被定义。

以下是您提供的代码的翻译:

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 HttpResponseRedirect('List-Of-Column')

请注意,尽管我已经提供了翻译,但问题中的代码片段可能仍然存在问题,需要根据您的项目上下文进行进一步检查和调整。

英文:

Is there any way to use user=request.user inside ModelChoiceField when I use this method I got an error: NameError: name 'request' is not defined.

class AlbumForm(forms.Form):
    album = ModelChoiceField(queryset=Album.objects.filter(user=request.user)

The model:

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')

答案1

得分: 2

You can't directly access the request object in the model definition, because the models are parsed at the worker startup, way before someone makes a request. However you can pass the objects in the 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())

Then in your view you have to create your form like this:

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

You can't directly access the request object in the model definition, because the models are parsed at the worker startup, way before someone makes a request. However you can pass the objects in the 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())

Then in your view you have to create your form like this:

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

答案2

得分: 0

我之所以收到NameError的原因是因为请求对象在表单定义的范围内不可用。

我重写了表单的__init__方法并将用户对象作为参数传递给表单:

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方法内,我忘记将用户对象传递给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

感谢这个答案

英文:

The reason why I'm getting the NameError is because the request object is not available in the scope of the form definition.

I override the form's __init__ method and pass the user object as an argument to the form:

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)

In my CreateOurColumn view, inside: get_context_data method, I forgot to pass the user object to the 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

This way, the AlbumForm will filter the queryset based on the user object passed to it.

Thanks to this answer

huangapple
  • 本文由 发表于 2023年3月31日 19:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定