我想编辑文章详细信息页面,
如果请求方法为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
forms.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
的代码有什么问题?
答案 0 :(得分: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)
我希望这会有所帮助
答案 1 :(得分:1)
好像您正在将Article实例传递给CommentForm。试试:
if request.method == "GET":
form = ArticleForm(instance=article)
由于CommmentForm没有标题或内容值。