自定义外键的inline_formset字段显示
我有一个名为 Access 的模型,它链接到其他两个模型。
class Access (models.Model):
portfolio_id = models.ForeignKey(Portfolio)
user_id = models.ForeignKey(User)
title = models.CharField(max_length=30, null=True, blank=True)
access_rights = models.PositiveIntegerField(choices=ACCESS_CHOICES)
我已经创建了这个表格。
class UserAccessForm(forms.ModelForm):
class Meta:
model = Access
我有这个想法。
AccessFormSet = inlineformset_factory(Portfolio,
Access,
form=UserAccessForm,
extra=1,
can_delete=False)
cAccessFormSet = AccessFormSet(instance=cPorfolio)
问题出在网页中,user_id 显示为选择字段,为我提供所有用户的列表(即“jane15”、“tom54”)。我希望它是一个文本字段,有人必须输入用户名。当我尝试如下自定义它时,它显示“用户 ID”而不是“用户名”(即“1”、“2”)。
class UserAccessForm(forms.ModelForm):
user_id = forms.ChoiceField(required=True, widget=forms.TextInput)
class Meta:
model = Access
如何让表单集显示并接受用户名(即“jane15”)作为文本字段而不是选择字段?
I have a model called Access that links to two other models.
class Access (models.Model):
portfolio_id = models.ForeignKey(Portfolio)
user_id = models.ForeignKey(User)
title = models.CharField(max_length=30, null=True, blank=True)
access_rights = models.PositiveIntegerField(choices=ACCESS_CHOICES)
I have created this form.
class UserAccessForm(forms.ModelForm):
class Meta:
model = Access
I have this in the view.
AccessFormSet = inlineformset_factory(Portfolio,
Access,
form=UserAccessForm,
extra=1,
can_delete=False)
cAccessFormSet = AccessFormSet(instance=cPorfolio)
The issue is in the web page, user_id displays as a choicefield giving me a list of all my users (i.e. "jane15", "tom54"). I want it to be a text field that someone has to type in the username. When I try to customize it as below, it displays "user ids" instead of the "username" (i.e. "1", "2").
class UserAccessForm(forms.ModelForm):
user_id = forms.ChoiceField(required=True, widget=forms.TextInput)
class Meta:
model = Access
How do I get the formset to display and accept usernames (i.e. "jane15") as a textfield instead of as a choicefield?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,如果您想输入用户名,选择字段并不是正确的选择。
使用
CharField
(它是)并重写
clean_FOO
方法来验证用户实例中的输入或提出错误消息。将其传递到您的表单集中即可完成。
Well, if you wanted to type in usernames, a choice field is not the way to go.
Use a
CharField
which is a<input type='text'>
and override theclean_FOO
method to validate the input into a user instance or raise an error message.Pass that into your formset and you're done.