The code below is from a django project for a kickstarter-like funding platform.
This is the view for the individual project page, which shows the project's title, description, and featured image, and asks the user to donate to the project. The page provides four suggested donation amounts, with a fifth option for the user to write in a custom amount. The minimum donation is $5. The max is $1000. The median is $20.
def project_page(request, slug):
project = get_object_or_404(Project.objects.get(slug=slug, published=True))
featured_image = project.featured_image
account = project.account
if 'shared_donation' in request.GET:
# If a user is directed to a project page via another user sharing their donation
# (including amount) on social media, base suggested donation amounts on the
# referring user's donation.
suggestions = [shared_donation - 10,
shared_donation,
shared_donation + 10,
shared_donation + 20]
else:
suggestions = DEFAULT_SUGGESTIONS
return render(
request,
'donations/donate_project.jinja',
{
'title': project.title,
'project': project,
'account': account,
'featured_image': featured_image,
'suggestions': suggestions,
})
Here is the Project
model:
class Project(models.Model, AbstractHTMLMixin):
title = models.CharField(max_length=NAME_LENGTH,
help_text="The title of the project.")
description = models.TextField(help_text="The project's description")
slug = models.SlugField(max_length=NAME_LENGTH,
help_text="Automatically generated, use for the project URL.")
featured_image = models.ForeignKey(
'Media', null=True, blank=True,
help_text="A large landscape image for use on the project page. \
Should be 1100px wide and 454px tall.")
account = models.ForeignKey('Account', unique=True,
help_text="The accounting code for the project.")
published = models.BooleanField(default=False, help_text="If selected, \
the project will be visible to the public.")
-
Walk through the view. What's it doing?
-
How would you improve the suggested donation amounts code?
-
Add a Custom Manager to the Project model to return only published projects (feel free to look it up).
-
Given the way the model is set up, do you have any suggestions to make the query more efficient?