Reputation: 125
I have problem when form is not valid (in POST method).
didn't return an HttpResponse object. It returned None instead.
I could paste this line to last line of Post method
return render(request, self.template_name, context)
But context variable is initialized in Get method. How can I pass context to post method?
class EventPage(View):
template_name = 'event.html'
def get(self, request, event_id):
event = Event.objects.get(id = event_id)
participants = Participant.objects.filter(event_id = event.id)
register_to_event_form = RegisterToEvent()
context = {
'register_to_event_form': register_to_event_form,
'title': event.title,
'description': event.description,
}
return render(request, self.template_name, context)
def post(self, request, event_id):
event = Event.objects.get(id = event_id)
if request.method == "POST":
register_to_event_form = RegisterToEvent(request.POST)
if register_to_event_form.is_valid():
participant = register_to_event_form.save(commit=False)
participant.event = event
participant.save()
return HttpResponseRedirect('/event-%s' %event_id)
Upvotes: 1
Views: 59
Reputation: 599520
You should not be doing things this way at all. The whole point of the class-based views is that they provide a series of methods for you to override which are called by the default implementations of get
and post
; you should not really be overriding get and post yourself.
In your case you should be using a CreateView, not a plain view. And you should be returning the events and participants in a get_context_data
method. Setting the event
property of the saved object should happen in the form_valid
method.
Upvotes: 1
Reputation: 5475
you are not returning anything if your form is invalid, so you can do like:
def post(self, request, event_id):
event = Event.objects.get(id = event_id)
register_to_event_form = RegisterToEvent(request.POST)
if register_to_event_form.is_valid():
. . .
return HttpResponseRedirect('/event-%s' %event_id)
else:
context = {'register_to_event_form': register_to_event_form}
return render(request, self.template_name, context)
and you dont need if request.method == "POST":
in your post method
Upvotes: 0
Reputation: 5390
I think you need an else statement in case of non valid form which return an HttpResponseRedirect
Upvotes: 0