Created
September 12, 2012 07:17
-
-
Save bmispelon/3704905 to your computer and use it in GitHub Desktop.
View examples
This file contains hidden or 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
| def create(request): # django.views.generic.CreateView | |
| """Create a new model object and save it to the database.""" | |
| if request.method == 'post': | |
| form = ModelFormClass(request.POST) | |
| if form.isvalid(): | |
| form.save() | |
| return redirect(...) | |
| else: | |
| form = ModelFormClass() | |
| return render('your_template.html', {'form': form}) | |
| def update(request, object_id): # django.views.generic.UpdateView | |
| """Update an existing model object and save it to the database.""" | |
| object = get_object_or_404(YourModel, pk=object_id) | |
| if request.method == 'post': | |
| form = ModelFormClass(request.POST, instance=object) | |
| if form.isvalid(): | |
| form.save() | |
| return redirect(...) | |
| else: | |
| form = ModelFormClass(instance=object) | |
| return render('your_template.html', {'object': object, 'form': form}) | |
| def delete(request, object_id): # django.views.generic.DeleteView | |
| """Delete an existing object from the database, asking for a confirmation before.""" | |
| object = get_object_or_404(YourModel, pk=object_id) | |
| if request.method == 'post': | |
| object.delete() | |
| return redirect(...) | |
| return render('confirmation.html', {'object': object}) | |
| def create_with_linked_object(request, linked_object_id): | |
| """Create a new model that's linked to an existing instance.""" | |
| linked_object = get_object_or_404(YourLinkedModel, pk=linked_object_id) | |
| if request.method == 'post': | |
| form = LinkedModelForm(request.POST) | |
| if form.is_valid(): | |
| # creates a new instance without saving it to the db | |
| new_object = form.save(commit=False) | |
| new_object.linked_field = linked_object | |
| new_object.save() | |
| return redirect() | |
| else: | |
| form = LinkedModelForm() | |
| return render('your_template.html', {'form': form, 'linked_object': linked_object}) |
This file contains hidden or 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
| class LinkedModelForm(forms.ModelForm): | |
| class Meta: | |
| model = YourModel | |
| fields = ['foo', 'bar', 'baz'] # everything except the FK field | |
| # You could also use exclude = ['quux'] but i wouldnt recommend it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment