Skip to content

Instantly share code, notes, and snippets.

@jdbit
Last active August 12, 2020 08:52
Show Gist options
  • Save jdbit/39106dead1accaaf60fa58f0131dc75e to your computer and use it in GitHub Desktop.
Save jdbit/39106dead1accaaf60fa58f0131dc75e to your computer and use it in GitHub Desktop.
Useful Django functions
# CRUD
@login_required(login_url='home')
def create_page(requrest):
"""
Create form for model
"""
template = "post.html"
form = PostForm()
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('posts')
context = {'form': form}
return render(request, template, context)
def update_page(requrest, pk):
"""
Update form for model
"""
template = 'post.html'
page = models.Page.objects.get(id=pk)
form = PostForm(instance=page)
if request.method == 'POST':
form = PostForm(request.POST, instance=page)
if form.is_valid():
form.save()
return redirect('posts', slug=slug)
context = {'form': form}
return render(request, template, context)
def delete_page(requrest, pk):
"""
Delete form for model
"""
template = 'delete.html'
page = models.Page.objects.get(id=pk)
if request.method == 'POST':
post.delete()
return redirect('posts', slug=slug)
context = {'object': page}
return render(request, template, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment