更新 ModelForm Django 1.10

Updating ModelForm Django 1.10

总的来说,我对编码还很陌生,所以请原谅我的无知。

我有一个 ModelForm(Django 1.10 - 以防万一)用于社交网站上的 'post':

models.py:

class Post(models.Model):
   user = models.ForeignKey(User)
   text = models.TextField()
   image = models.ImageField(blank=True)
   draft = models.BooleanField(default=False)
   submission_date = models.DateTimeField(auto_now_add=True)

   def __unicode__(self):
       return self.text

forms.py:

class PostForm(forms.ModelForm):
    class Meta:
         model = Post
         fields = ['text', 'image', 'draft']

更新一个post,这是它的功能: views.py:

def edit_post(request, post_id):
  post = get_object_or_404(Post, pk=post_id)

  if not request.user.is_superuser and\
  not request.user == post.user:
    raise PermissionDenied

  if request.method == 'POST':
    form = PostForm(request.POST, instance=post)
    if form.is_valid():
      post = form.save(commit=False)
      post.user = request.user
      post.save()
      context = {'post': post,'form': form}
      return HttpResponse(render(request, 'accounts/view_post.html', context))

   elif request.method == 'GET':
     form = PostForm(request.GET, instance=post)
     context = {'post': post,'form': form}
     return HttpResponse(render(request, 'accounts/edit_post.html', context))

在模板中:

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'accounts/form_template.html' %}
<input class="btn btn-btn-success" type="submit" value="Save Post">
</form>

我的问题是:尝试更新时,为什么原来的字段输入不显示?这些字段变成空的,就好像我正在创建一个新的 post.

回答的越详细,越感激。 提前谢谢你。

如果您想在表单中显示原始输入,您必须在 PostForm:

中添加一些代码
class PostForm(forms.ModelForm):
  class Meta:
    model = Post
    fields = ['text', 'image', 'draft']

  def __init__(self, *args, **kwargs):
    super(PostForm, self).__init__(*args, **kwargs)
    for key in self.fields:
      self.fields[key].required = False

然后你必须将它加载到视图中

def edit_post(request, post_id):
    post = get_object_or_404(Post, pk=post_id)
    if not request.user.is_superuser and\
    not request.user == post.user:
        raise PermissionDenied

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            context = {'post': post,
                       'form': form}
            return HttpResponse(render(request, 'accounts/view_post.html', context))

    elif request.method == 'GET':
        form = PostForm(request.GET, instance=post)

        context = {'post': post,
                   'form': form}
        return HttpResponse(render(request, 'accounts/edit_post.html', context))

原来我需要做的就是删除 'request.GET': 在 views.py:

def edit_post(request, post_id):
     post = get_object_or_404(Post, pk=post_id)
     ...
     ...
    elif request.method == 'GET':
         form = PostForm(instance=post)

         context = {'post': post,
                    'form': form}
         return HttpResponse(render(request, 'accounts/edit_post.html', context))

感谢所有试图提供帮助的人,尤其是@Zagorodniy Olexiy。