django forms怎么获取登录用户
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django forms怎么获取登录用户相关的知识,希望对你有一定的参考价值。
参考技术A Django获取登陆用户的手段就是request.user。如果你想传给form字段,可以先做一个model的object实例,把request.user传给这个object实例的相关字段,然后把这个实例传给forms实例即可。本回答被提问者采纳
根据当前登录的用户自定义django表单
这是我的forms.py的一部分
class SubjectForm(forms.ModelForm):
title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150,
'placeholder':'Write here. . .'}))
body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'}))
board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board')
class Meta:
model = Subject
fields = ('title','body','board')
现在它在板形式字段中渲染所有Board对象,但我想只渲染用户订阅的那些板。如何让用户获得表单并进行操作?
答案
forms.朋友:
class SubjectForm(forms.ModelForm):
title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150,
'placeholder':'Write here. . .'}))
body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'}))
board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(SubjectForm, self).__init__(*args, **kwargs)
if user is not None:
self.fields['board'].queryset = Board.objects.filter(user=user)
class Meta:
model = Subject
fields = ('title','body','board')
views.朋友:
使用CreateView进行演示:
class SubjectCreateView(CreateView):
form_class = SubjectForm
template_name = 'subject/create.html'
success_url = '/'
def get_form_kwargs(self):
kwargs = super(SubjectCreateView, self).get_form_kwargs()
if self.request.method == 'GET':
kwargs.update({
'user': self.request.user,
})
return kwargs
要么
form = SubjectForm(**{'user': request.user})
以上是关于django forms怎么获取登录用户的主要内容,如果未能解决你的问题,请参考以下文章