def post_update(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': f = PostForm(request.POST, instance=post) if f.is_valid(): # if author is not selected and user is superuser, then assign the post to the author named staff if request.POST.get('author') == "" and request.user.is_superuser: updated_post = f.save(commit=False) author = Author.objects.get(user__username='******') updated_post.author = author updated_post.save() f.save_m2m() # if author is selected and user is superuser elif request.POST.get('author') and request.user.is_superuser: updated_post = f.save() # if user is not a superuser else: updated_post = f.save(commit=False) updated_post.author = Author.objects.get( user__username=request.user.username) updated_post.save() f.save_m2m() messages.add_message(request, messages.INFO, 'Post updated.') return redirect(reverse('post_update', args=[post.id])) else: f = PostForm(instance=post) return render(request, 'cadmin/post_update.html', { 'form': f, 'post': post })
def post_add(request): if request.method == "POST": f = PostForm(request.POST) if f.is_valid(): # if author is not selected and user is superuser, # then assign the post to the author named staff if request.POST.get('author') == "" and request.user.is_superuser: new_post = f.save(commit=False) author = Author.objects.get(user__username='******') new_post.author = author new_post.save() f.save_m2m() # if author is selected and user is superuser elif request.POST.get('author') and request.user.is_superuser: new_post = f.save() # if user is not a superuser else: new_post = f.save(commit=False) new_post.author = Author.objects.get( user__username=request.user.username) new_post.save() f.save_m2m() messages.add_message(request, messages.INFO, 'Post added.') return redirect('post_add') else: f = PostForm() return render(request, 'cadmin/post_add.html', {'form': f})