使用ModelForm从Django模型中过滤选择

时间:2015-12-18 10:05:07

标签: python django django-models django-forms

我必须将一些数据发送到我的数据库,我有一个电话对象。为此,我需要选择所需的电话号码并将所需的信息插入数据库。 要求是显示属于当前登录用户的电话号码 我使用名为Phone的Django模型和名为phoneForm的modelForm。

class Phone(models.Model):
    user = models.ForeignKey(User)
    phone_num = models.ForeignKey(Sim, null=True)
    imei = models.CharField(max_length=30, primary_key=True)
    num_calls = models.CharField(max_length=20, null=True, blank=True)
    time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
    psap = models.CharField(max_length=30, null=True, blank=True)

class Sim(models.Model):
    phone_num = models.CharField(max_length=30, primary_key=True)
    pin = models.CharField(max_length=15)
    puk = models.CharField(max_length=15)

class phoneForm(ModelForm):

    class Meta:
        model = Phone
        fields = ['phone_num', 'num_calls', 'time_btwn_calls', 'psap']
        widgets = {'phone_num': Select(attrs={'class': 'form-control'}), 
                'num_calls': TextInput(attrs={'class': 'form-control'}),
                'time_btwn_calls': TextInput(attrs={'class': 'form-control'}), 
                'psap': TextInput(attrs={'class': 'form-control'})
                  }
        labels = {
                'phone_num': ('Select phone number'),
                'num_calls': ('Number of calls'),
                'time_btwn_calls': ('Time between calls'),
                'psap': ('PSAP'),
        }

        def __init__(self, *args, **kwargs):
            super(phoneForm, self).__init__(*args, **kwargs)
            self.queryset = Phone.objects.filter(user_id = request.user.id).values('phone_num')

如何正确访问数据库以过滤属于当前用户的phone_num值,然后在phone_num选项中设置它们?

我的模板是:

<div class="row">
    <div class="col-md-6 col-sm-offset-3">
        <form method="post" action="" enctype="multipart/form-data">
            {% csrf_token %}  <!-- obligatorio para protegerse de ataques maliciosos -->
            {{ form.as_p }} <!-- pasamos la variable form y con as_p conseguimos <p> -->
            <button type="submit" class="btn btn-primary">Send to TCU</button>
        </form>
    </div>

我的view.py:

def phone_config(request):
    phone = Phone.objects.get(phone_num=611111111)

    if request.method == 'POST':
        form = phoneForm(request, request.POST, instance=phone)
        if form.is_valid():
            form.save()
            return redirect(reverse('gracias'))
    else:
        form = phoneForm(request, instance=tcu)
    return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})


def gracias_view(request):
    return render(request, 'heroconfigurer/gracias.html')

1 个答案:

答案 0 :(得分:3)

要修改表单中的phone_num字段,您可以使用表单的self.fields['phone_num']方法访问__init__

class phoneForm(ModelForm):

    class Meta:
        model = Phone
        ...

    def __init__(self, user, *args, **kwargs):
        super(phoneForm, self).__init__(*args, **kwargs)
        phone_nums = Phone.objects.filter(user=user).values_list('phone_num', flat=True)
        self.fields['phone_num'].queryset = Sim.objects.filter(phone_num__in=phone_nums)

在视图中初始化表单时,需要传递用户,例如

form = phoneForm(user, request.POST)

如果这不起作用,请解释原因并展示您的Sim型号。

请注意其他一些变化:

  • 无需使用values()
  • 如果Sim.user是外键,那么您可以将过滤器简化为filter(user=request.user)
  • 用户已添加到表单的__init__方法。