【问题标题】:Saving a model form instance in django在 django 中保存模型表单实例
【发布时间】:2014-01-29 16:52:44
【问题描述】:

我正在尝试创建一个网站,用户可以在其中提交博客文章(使用模型表单)。然后我还有一个视图,可以根据文章编号搜索帖子,这会弹出模型表单进行编辑,然后您可以提交更新。我有什么作品,我只是觉得可能有更好的方法来做到这一点。

感觉我不需要“update_results”视图,只需将其与“submit_post”视图结合即可。

这是我所拥有的:

views.py

def submit_post(request):
    if request.method == 'POST':

        form = Information_Form(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/submit')

    else:
        form = Information_Form

    return render_to_response('submit_post.html', {'form': form},  context_instance=RequestContext(request))



def search_results(request):
    if request.method == 'GET':

        query = request.GET['q']
        results = Information.objects.get(article_number=query)

        form = Information_Form(instance=results)


        return render_to_response('search_results.html', {'results': results, 'form': form}, context_instance=RequestContext(request))


def update_results(request):

    if request.method == 'POST':

        article = request.POST['article_number']
        x = Information.objects.get(article_number=article)

        form = Information_Form(request.POST, instance=x)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/update_results')
    else:
        form = Information_Form()
    return render_to_response('submit_post.html', {'form': form},  context_instance=RequestContext(request))    

【问题讨论】:

    标签: django models


    【解决方案1】:

    在我看来,每个操作都有两个不同的视图是可以的:创建和更新。

    但是,如果您想要更简洁的代码,您可以使用Class Based Views,如下所示:

    from django.views.generic.edit import CreateView, UpdateView
    from myapp.models import BlogPost # replace with your own model
    from myapp.forms import BlogPost_Form # Replace with your own form
    
    class BlogPostCreate(CreateView):
        model = BlogPost
        fields = ['title', 'content']   # define fields you want for the form
                                        # or uncomment the line bellow to use your own form class
        # form_class = BlogPost_Form
    
    
    class BlogPostUpdate(UpdateView):
        model = BlogPost
        fields = ['name', 'content']
    

    这样,您不必为每个视图重现表单处理逻辑。

    【讨论】:

      【解决方案2】:

      是的,您可以通过检查 article_number 的存在来相对轻松地结合创建和更新。如果提供了,则在 POST 时更新现有文章,并在 GET 时显示现有文章。如果没有 article_number,则在 GET 时显示一个空白表单并在 POST 时保存一篇新文章。

      def create_or_edit_article(request):
      
          article_number = request.GET.get('article_number' None)
          if article_number:
              instance = Information.objects.get(article_number=article_number)
          else:
              instance = None
      
          # by using 'or None', this will work as if request.POST was not
          # passed when it is a GET.
          form = Information_Form(request.POST or None, instance=instance)
      
          if request.method == 'POST':
              if form.is_valid():
                  # you do not have to use `commit=True` here because that is the default
                  # behavior. Use `commit=` when False is a possibility.
                  form.save()
                  # here you can decide where to redirect on success.  eg:
                  if instance:
                      return HttpResponseRedirect('/after_edit_url')
                   return HttpResponseRedirect('/after_insert_url')
                  # BTW you should really use reverse() to get these urls. 
      
          return render_to_response('article_form.html', {'form': form}, 
              context_instance=RequestContext(request))
      

      因此,使用上面的代码,如果您 GET /the_url/?article_id=12345,它将显示该文章。如果您将该表单提交回相同的 url,它将保存更改。不要在你的<form> 标签中使用任何action=,它会在它应该提交的地方提交。

      在您的搜索结果模板中,生成包含 article_id 的链接,如图所示,然后您可以通过一个视图编辑任何文章。

      我要补充的另一件事是,URL 的“Django 样式”会更像

      /myapp/article/

      /myapp/article/12345/

      /myapp/article/add/

      为此,您需要在 urls.conf 中设置正则表达式以匹配其中的每一个并调度正确的视图函数。如果您在 url 正则表达式中使用名为 article_number 的“命名组”,它将作为 kwarg 传递给您的视图。

      https://docs.djangoproject.com/en/1.8/topics/http/urls/#named-groups

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 2018-03-21
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多