英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论