0

我想编辑文章详细信息页面,

如果请求方法是get,用数据预先制定表单

def edit_article(request, pk):
    article = Article.objects.get(pk=pk)
    if request.method == "GET":
        form = CommentForm(instance=article)
    context = {'form':form,}
    return render(request, "article/article_detail_edit.html", context)

模板

  <div class="form-group">
    <label for="title" class="col-sm-1 control-label">Title</label>
    <div class="col-sm-11">
      <input type="text" class="form-control" id="title" name="title"   value="{{ form.title.value }}">
    </div>
  </div>
  <div class="form-group">
    <label for="content" class="col-sm-1 control-label" >Content</label>
    <div class="col-sm-11">
      <textarea class="form-control" id="content" name="content" rows="10" cols="30">{{ form.content.value }}</textarea>
    </div>
  </div>

不幸的是,单击编辑链接后,表单为空白:

在此处输入图像描述

我用

if request.method == "GET":
    form = CommentForm(instance=article)
    print(vars(form.instance))

它打印所有数据

{'_state': <django.db.models.base.ModelState object at 0x10c977438>, 'id': 1, 'owner_id': 1, 'block_id': 1, 'title': 'Time and Tide', 'content':....}

我将表单传递给上下文

context = {'form': form}
return render(request, "article/article_detail_edit.html", context)

文章型号

class Article(models.Model):
    STATUS = (
        (1,  'normal'),
        (0, 'deleted'),
    )
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    block = models.ForeignKey(Block, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField() # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ("id",)

    def __str__(self):
        return self.title

表格.py

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['title', 'content']
        widgets = {'content': forms.Textarea}


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body',)
        widgets = {'body': forms.Textarea}

我要显示的代码有什么问题form.field.value

4

2 回答 2

1

您不会将上下文中的表单传递给模板。

尝试:

def edit_article(request, pk):
    article = Article.objects.get(pk=pk)
    if request.method == "GET":
        form = CommentForm(instance=article)
        context['form'] = form
    return render(request, "article/article_detail_edit.html", context)

我希望这个能帮上忙

于 2018-07-09T15:03:25.060 回答
1

看起来您正在将 Article 实例传递给 CommentForm。尝试:

if request.method == "GET":
    form = ArticleForm(instance=article)

由于 CommmentForm 没有标题或内容值。

于 2018-07-09T15:34:21.153 回答