Forked from pylemon/using_request_post_or_none.py
Last active
August 29, 2015 14:26
-
-
Save pvieytes/9f8e5a4c13bbbe4c6e7e to your computer and use it in GitHub Desktop.
django: using(request.POST or None) hack in views | advanced forms usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# simple form usage in view | |
def my_view(request, template_name='home.html'): | |
# sticks in a POST or renders an empty form | |
form = MyForm(request.POST or None) | |
if form.is_valid(): | |
do_something() | |
return redirect('/') | |
return render_to_response(template_name, {'form':form}) | |
# form with files | |
def my_view(request, template_name='home.html'): | |
form = MyForm(request.POST or None, request.FILES or None) | |
if form.is_valid(): | |
do_something() | |
return redirect('/') | |
return render_to_response(template_name, {'form':form}) | |
# ModelForm usage | |
def my_model_edit(request, slug=slug, template_name='home.html'): | |
mymodel = get_object_or_404(MyModel, slug=slug) | |
form = MyModelForm(request.POST or None, instance=mymodel) | |
if form.is_valid(): | |
mymodel = form.save() | |
mymodel.edited_today = True | |
mymodel.save() | |
return redirect('/') | |
return render_to_response(template_name, { | |
'form':form, | |
'mymodel':mymodel | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment