コード例 #1
0
def create_post(request):
    page_title = "Create Post"
    form = PostForm(request.POST or None, request.FILES or None)
    if request.method == "POST":
        if form.is_valid():
            myfrom = form.save(commit=False)
            myfrom.author = request.user
            myfrom.save()
            form.save_m2m()  # save many 2 many field must be like that
            return redirect(reverse('blog:posts'))
        else:
            form = PostForm()

    context = {
        'create_or_update_post_form': form,
        'page_title': page_title,
    }
    return render(request, 'post/post_create_or_update.html', context)
コード例 #2
0
def post_update(
    request, slug
):  #the same view and template create_post with minor change "instance=post_details"
    page_title = "Edit Post"
    post_details = Post.objects.get(slug=slug)
    form = PostForm(
        request.POST or None, request.FILES or None, instance=post_details
    )  # use "instance=" to give the form the current data in the form
    if request.method == "POST":
        if form.is_valid():
            myfrom = form.save(commit=False)
            myfrom.save()
            form.save_m2m()  # save many 2 many field must be like that
            return redirect(reverse('blog:post_details',
                                    args=(slug, )))  # the way to redirect slug
        else:
            form = PostForm()

    context = {
        'create_or_update_post_form': form,
        'page_title': page_title,
    }
    return render(request, 'post/post_create_or_update.html',
                  context)  # different urls for the same html page