I have made a model for a post and have to make a form to accept that post. I am using the below given view for generating a form both for making a new one and editing one, if it exists.
If the post exists then there will be a valid post_id and I will pick the correct post object and display the form with the fields filled, but if there is no post_id then I will generate a new blank form.
However I am getting an error
What am I doing wrong?
def post_form(request,post_id):
context_instance=RequestContext(request)
if post_id:
post = get_object_or_404(Post, pk=post_id)
else:
#if the user is authenticated then pass the user object
if request.user.is_authenticated():
post = Post(creator=request.user)
else:
post = Post()
if request.method == 'POST':
if 'save' in request.POST:
form = PostForm(request.POST, instance = post)
if form.is_valid():
form.save()
return redirect(post)
# Instantiate an empty form with the given user
else:
form = PostForm(instance = post)
return render_to_response('forum/post.html', {'form':form}, context_instance)
looks like you need a default value for post_id
def post_form(request, post_id=None):
...