Skip to main content
 首页 » 编程设计

python之Django CreateView之仅显示外键字段中的特定对象

2024年08月19日29dflying

我有一个 CreateView View ,其中包含一系列需要用户在创建新联系人时填写的字段。现在,我希望用户能够仅从他们创建的类别中查看和选择。 这是类别的模型:

class Category(models.Model): 
    class Meta: 
        verbose_name = _('category') 
        verbose_name_plural = _('categories') 
 
    name = models.CharField(max_length=100, unique=True) 
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE) 
 
    def __unicode__(self): 
        return self.name 

这是 View :

class ContactCreate(LoginRequiredMixin, generic.edit.CreateView): 
    model = models.Contact 
    success_url = reverse_lazy('site:contacts') 
    fields = ['firstname', 'lastname', 'phone1', 'phone2', 'email', 'city', 'category'] 
    template_name = 'site/contacts.html' 
    context_object_name = 'all_contacts' 

我需要用户看到的是一个选择,其中仅包含与其关联的适当配置文件外键的类别。

我很乐意在这方面得到一些帮助。谢谢!

请您参考如下方法:

可以重写 View 的get_form方法,设置相应字段的queryset:

class ContactCreate(LoginRequiredMixin, generic.edit.CreateView): 
    # ... 
    def get_form(self, *args, **kwargs): 
        form = super(ContactCreate, self).get_form(*args, **kwargs) 
        form.fields['categories'].queryset = Category.objects.filter(profile=self.request.user.profile) 
        return form 

当然,这假设您的 Profile 模型有一个 OneToOneField 到 User with related_name 'profile',否则你必须调整过滤。