为checkboxSelectMultiple提供值

时间:2012-04-22 13:13:06

标签: python django

问题是我无法使用已在视图中通过实例选择和转发的选项值填充checkboxSelectMultiple小部件。

这些是相关的课程:

查看:

if sid and request.method != "POST":
    try:
        obj = Service.objects.get(pk=int(sid), user=request.user.pk)
        form = addNewService(instance=obj)
    except:
        return HttpResponseRedirect("/")

形式:

class addNewService(forms.ModelForm):
    pk = forms.HiddenInput()
    authorities = forms.ModelMultipleChoiceField(queryset=authorities.objects.all(), widget=forms.CheckboxSelectMultiple, required=True)
    error_css_class = 'error'
    required_css_class = 'required'
    #organisation_logo = forms.ImageField()
    class Meta:
        model = Service
        #exclude = ("user",)
        fields = (  'service_name',
                    'category',
                    'service_duration',
                    'price',
                    'bursarie',
                    'vat_included',
                    'travelExpensesIncluded',
                    'authorities',
                    'type_of_delivery',
                    'description',
                    'active',
                    )

型号:

class Service(models.Model):
    user = models.ForeignKey(User)
    service_name = models.CharField(max_length=30)
    description = models.TextField()
    category = models.ForeignKey(Category)
    authorities = models.ManyToManyField(authorities)
    active = models.BooleanField()

    def removeServiceURL(self):
        return "/Services/Remove/%s"%self.pk

    def __unicode__(self):
        return "%s @ %s"%(self.service_name, self.user.username)

复选框会相应显示,但是当我从实例打开表单时,除了复选框之外,所有内容都会正确填充,这些复选框都是未选中的。

我做错了什么?

谢谢你的回答。

1 个答案:

答案 0 :(得分:0)

尝试:

def your_view(request, sid=None):
    if sid and request.method == "GET":
        try:
            obj = Service.objects.get(pk=sid, user=request.user)
            form = addNewService(instance=obj)
        except Service.DoesNotExist:
            return HttpResponseRedirect("/")

#rest of view

您不想吞下try / except中的所有异常。检查您正在处理的特定例外情况;它使调试变得更容易。此外,在您的查询集中,您尝试匹配主键上的用户,但将其与对象:user进行比较。如果你想在pk上匹配,请执行:user__id=request.user.id但是,如果用户是匿名的,这将失败。