Django:如何在手动表单字段中显示模型的外键对象作为选择
Posted
技术标签:
【中文标题】Django:如何在手动表单字段中显示模型的外键对象作为选择【英文标题】:Django: How to display foreign key objects of a model in manual form field as choices 【发布时间】:2020-05-15 01:32:03 【问题描述】:所以我有 2 个模型,称为 Billing 和 Organization,如下所示。管理站点中的计费按预期工作,即组织字段显示列出的所有组织,并让我可以选择一个。如果我为计费实现一个模型表单,它不会显示我可以选择的所有组织。如何实施?我在下面分享了forms.py、views.py的代码。
models.py
class Organization(models.Model):
name = models.CharField(max_length=255, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.name)
class Billing(models.Model):
invoice_name = models.CharField(max_length=50)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
product = models.ManyToManyField(Product)
def __str__(self):
return str(self.invoice_name)
views.py
class BillingCreateView(AdminStaffRequiredMixin, SuccessMessageMixin, CreateView):
model = Billing
form_class = forms.BillingCreateForm
template_name = 'dashboard/billing_new.html'
success_message = 'Invoice has been created successfully!'
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
dashboard/billing_new.html
<!-- start form -->
<div class="col-lg-12">
<form method="post" action="% url 'product_create' %" class="mailform off2" enctype="multipart/form-data">
<div class="row">
% csrf_token %
<div class="col-md-6 offset-md-3">
form.invoice_name
</div>
<div class="col-md-6 offset-md-3">
form.organization
</div>
<div class="col-md-6 offset-md-3">
form.product
</div>
% if redirect_field_value %
<input type="hidden" name=" redirect_field_name " value=" redirect_field_value " />
% endif %
<div class="mfControls col-md-12 offset-md-3 text-left mt-2">
<button type="submit" class="btn white">% trans "CREATE" %</button>
</div>
</div>
</form>
</div>
<!-- end form -->
forms.py
class BillingCreateForm(forms.ModelForm):
class Meta:
model = models.Billing
fields = ['invoice_name', 'organization', 'product']
widgets =
'invoice_name': forms.TextInput(attrs='type': 'text', 'name': 'name', 'placeholder': 'Invoice Name:'),
'organization': forms.TextInput(attrs='type': 'text', 'name': 'name', 'placeholder': 'Company:'),
'items': forms.TextInput(attrs='type': 'text', 'name': 'name', 'placeholder': 'Items:'),
【问题讨论】:
你可以用 ajax 和 rest api 实现 @AsaduzzamanSohel 这是一个简单的问题。我已经在下面发布了修复程序。谢谢! 【参考方案1】:我通过在 forms.py 中使用forms.select
小部件解决了这个问题,如下所示:-
class BillingCreateForm(forms.ModelForm):
class Meta:
model = models.Billing
fields = ['invoice_name', 'organization', 'product']
widgets =
'invoice_name': forms.TextInput(attrs='type': 'text', 'name': 'name', 'placeholder': 'Invoice Name:'),
'organization': forms.Select(attrs='type': 'text', 'name': 'name', 'placeholder': 'Company:'),
'items': forms.TextInput(attrs='type': 'text', 'name': 'name', 'placeholder': 'Items:'),
【讨论】:
以上是关于Django:如何在手动表单字段中显示模型的外键对象作为选择的主要内容,如果未能解决你的问题,请参考以下文章