0

我正在尝试通过表单编辑现有对象,但没有用当前值填充所有内容。这个对象确实有一个值,但是当我去编辑时,所有字段中都没有显示任何内容,只显示空白字段。

这是模型:

class Flow (models.Model):
    title = models.CharField("Title", max_length=200)
    slug = models.SlugField(unique=True)
    description = models.TextField("Description")
    url = models.URLField("URL")
    tags = TaggableManager()
    flow_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    author = models.ForeignKey('auth.User', null=True)

    def __unicode__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        return ('flow.views.details', (), {'slug':self.slug})

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        return super(Flow, self).save(*args, **kwargs)

    class Meta:
        verbose_name = 'Flow'

这是视图

class FlowForm(forms.ModelForm):
    class Meta:
        model = Flow
        exclude = ['flow_date', 'slug']

@login_required
def edit(request, flow_id = None):
    flow = None
    if flow_id is not None:
        flow = get_object_or_404(Flow, pk=flow_id)

    if request.method == 'POST':
        form = FlowForm(request.POST, instance=flow)
        if form.is_valid():
            tags = form.cleaned_data['tags']
            newflow = form.save(commit=False)
            newflow.save()
            for tags in tags:
                newflow.tags.add(tags)
            return HttpResponseRedirect(newflow.get_absolute_url())
    else:
        form = FlowForm(request.POST, instance=flow)
    return render_to_response('flow/flow_edit.html', {'form':form, 'flow':flow,}, context_instance=RequestContext(request))

提前致谢。

更新

谢谢丹尼尔。

现在我想删除包括他们的 django-taggit 对象的对象。它适用于以下定义,但标签仍显示在基于 django-taggit-templatetags 的标签云列表中。

@login_required
def delete(request, flow_id):
    flow = Flow.objects.get(pk=flow_id)
    flow.delete()
    return render_to_response('flow/flow_delete.html', {'flow':flow,}, context_instance=RequestContext(request))

如何从表单/数据库中删除选定的 django-taggit 的对象/计数?

4

1 回答 1

0

当请求不是 POST 时,您将request.POST作为数据参数传递给 else 子句中的表单实例化,因此这是一个空字典。即使它是空的,它仍然会覆盖实例中的所有字段,因为实例值仅用作默认值,并且在将任何内容作为数据传递时不会显示。将该行更改为:

form = FlowForm(instance=flow)
于 2013-01-28T10:55:26.820 回答