1

问题是我无法使用已通过视图中的实例选择和转发的选项值填充我的 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)

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

我究竟做错了什么?

谢谢你的回答。

4

1 回答 1

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 中吞下所有的异常。检查您正在处理的特定异常;它使调试更容易。此外,在您的查询集中,您试图在主键上匹配用户,但将其与对象进行比较:如果您想在 pk 上进行匹配,请执行以下操作:user__id=request.user.id但是,如果用户是匿名的,这将失败。

于 2012-04-23T13:24:34.140 回答