Created
April 25, 2013 03:33
-
-
Save briandant/5457321 to your computer and use it in GitHub Desktop.
Some simple views for updating Django models
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
# views.py | |
from models import Recipe | |
# create a new recipe | |
def create_recipe(request, template='successful_recipe_add.html"): | |
recipe_title = request.POST['title'] # request.POST is a dict that comes from your form; the keys of request.POST will come from the name attribute of your HTML <input> element | |
recipe_description = request.POST['description'] | |
recipe_content = reqeust.POST['content'] | |
# etc, etc | |
new_recipe = Recipe(title=recipe_title, description=recipe_description, content=recipe_content) | |
new_recipe.save() # https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects | |
return render(request, template) | |
# deleting a recipe | |
def delete_recipe(request, template="successful_recipe_delete.html"): | |
this_recipe = Recipe.objects.get(id=request.POST['recipe_id']) # https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-objects | |
this_recipe.delete() # https://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects | |
return render(request, template) | |
# updating a recipe | |
def update_recipe(request, template="successful_update.html"): | |
this_recipe = Recipe.objects.get(name=request.POST['recipe_name'] # https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-a-single-object-with-get | |
this_recipe.content = request.POST['content'] | |
this_recipe.save() | |
return render(request, template) | |
# display recipes that match some keyword | https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters | |
# this is probably similar to 'show' in Rails | |
def get_similar_recipes(request, template="similar_recipes.html"): | |
similar_recipes = Recipe.objects.filter(title__startwith=request.POST['title_search_criteria'] | |
return render(request, template, {'similar_recipes': similar_recipes}) | |
#### for more options about how you can interact with your models, check out the Queryset API reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment