具有特定字段的自定义查询集的 Django ModelForm 实例

标签 django django-forms modelform

我有一个与以下类似的模型:

class Bike(models.Model):
    made_at = models.ForeignKey(Factory)
    added_on = models.DateField(auto_add_now=True)

所有用户可能在多个工厂工作,因此他们的用户文件都有一个 ManyToManyFieldFactory .

现在我想构建一个 ModelFormBike但我想要 made_at列表仅包含当前用户工作的工厂。这个想法是,用户应该能够添加他们已经组装的自行车,并进入制造自行车的工厂。

我怎么做?

最佳答案

您的问题可能是 dupe of this .

S. Lottanswer有一张票可以解决您的问题。
他回答:

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

关于具有特定字段的自定义查询集的 Django ModelForm 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1821289/

相关文章:

django - 如何使用 CreateView 将用户对象传递到 Modelform

python - django modelchoicefield 与未保存的模型

python - 如何从表单集中删除表单

django - 如何在 Django 3 中使用 RelatedFieldWidgetWrapper

database - 在 Django 中查询

Django Form 将 ChoiceField 选项设置为 Form 被调用

python - 如何解决 django 的 did not return httpresponse 错误?

python - 保存表单后如何为当前用户设置多对多字段

python - 根据ManyToMany关系存在过滤Django QuerySet

python - Django 1.3.7 TemplateDoesNotExist 错误 admin/index.html