forms.ModelForm限制为创建模型的用户

时间:2015-06-30 07:17:23

标签: python django forms

简单地问:在表单中,如何限制用户自己定义的记录的多对多关系的显示?

为了尽可能保持干净,我使用forms.ModelForm

在示例中,用户可以创建按计划运行的订阅源项。从技术上讲,提要和项目通过user = models.ForeignKey(User)连接到用户,但是这本身不足以通过用户自己限制两者的关联。

虽然我喜欢固有地限制两个用户的关联,但我很乐意通过用户简单地限制项目的显示,然后简单地验证。以下示例数据:

class Example(models.Model):

    global CHOICES_DAYS
    global CHOICES_HOURS

    user = models.ForeignKey(User)  
    label = models.CharField(max_length=180)    
    title = models.CharField(max_length=1000, blank=True)
    content = models.TextField(max_length=10000, blank=True)

    Example_feeds = models.ManyToManyField(ExampleFeed, blank=True)

    hourly_schedule = models.CharField(choices=CHOICES_HOURS, max_length=2, default=4)
    weekly_schedule = models.CharField(choices=CHOICES_DAYS, max_length=5, default=1)
    last_used = models.DateTimeField(default=timezone.now, blank=False)     

    def __str__(self):            
        return self.label

    class Meta:
        ordering = ('last_used',)

以下是我使用forms.ModelForm将表格尽可能保持干净的形式:

class ExampleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = ''
        self.helper.form_class = ''
        self.helper.form_method = 'post'

        self.helper.add_input(Submit('submit', 'Submit'))
        super(ExampleForm, self).__init__(*args, **kwargs)

    class Meta():
        model = Example
        fields = [
            'label', 
            'title', 
            'content', 
            'example_feeds', 
            'hourly_schedule', 
            'weekly_schedule']

1 个答案:

答案 0 :(得分:3)

当您在视图中对其进行实例化时,需要pass the request.user to the form,然后将该请求对象用于restrict the form field's queryset

class ExampleForm(forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.fields['mym2mfield'].queryset = Example.objects.filter(example_feeds__user=request.user)

并在您的视图中(假设它是基于类的视图):

class MyView(FormView):
    def get_form(self, form_class):
        return form_class(self.request, self.get_form_kwargs())