1👍
✅
Yes, that’s the way to go (you don’t need a else statement though). Django and other frameworks do this – the assumed default is GET, then you add a if statement for the POST method.
Don’t forget to return a redirect response in case you don’t want the form to be reposted. Also, if the form processing is long – you can use a separate method / service. Something like:
def my_view(request):
form = SomeForm(data=request.POST or None)
if request.method == 'POST':
if form.is_valid():
do_something(form) # form processing that could save a couple of objects, send notifications, etc.
messages.success(request, "Some message.")
return HttpResponseRedirect(request.path)
return render(request, ".../template.html", locals())
This way, you keep the business logic separated and you can easily unit test it (in this example, you would unit test do_something(…)).
1👍
Yes, this is ok. This is what Django does normally. Note that the generic FormView has got get
andpost
methods.
(To understand how they’re called, read the dispatch
method.)
- [Answered ]-Make All hashtags clickable in Template with Templatetags
- [Answered ]-Modifying User instances in Django already in database
- [Answered ]-How can I write my own OrderedDict class in Python?
- [Answered ]-UpdateView form pre-populate error
- [Answered ]-Rendering/Raising A Validation Error on an HTML Template in Django
Source:stackexchange.com