在django中保存模型表单实例

时间:2014-01-29 16:52:45

标签: django models

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

感觉我不需要“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))    

2 个答案:

答案 0 :(得分:0)

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

但是,如果您想要更简洁的代码,可以使用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']

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

答案 1 :(得分:0)

是的,您可以通过检查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))

因此,使用上面的代码,如果你获得/the_url/?article_id=12345,它将显示该文章。如果您将该表单提交回同一个网址,则会保存更改。不要在action=标记中使用任何<form>,它会在应有的位置提交。

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

我要补充的另一件事是,URL的'Django风格'更像是

/myapp/article/&lt; - view(GET)文章列表。

/myapp/article/12345/&lt; - 查看(获取)/保存(POST)文章#12345

/myapp/article/add/&lt; - 显示空白文章(GET)/保存新文章(POST)

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

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