Skip to content

Instantly share code, notes, and snippets.

@dnoyes
Created January 25, 2012 04:31
Show Gist options
  • Save dnoyes/1674741 to your computer and use it in GitHub Desktop.
Save dnoyes/1674741 to your computer and use it in GitHub Desktop.
creating a team (django)
# teams/urls.py
urlpatterns = patterns('teams.views',
...
url(r'^create/?$', 'create'),
...
)
# teams/models.py
class Team(models.Model):
...
def save(self, *args, **kwargs):
#TODO: check if slug exists in DB
if not self.slug:
self.slug = slugify(self.name)
return super(Team, self).save(*args, **kwargs)
# teams/forms.py
class CreateTeamForm(forms.ModelForm):
class Meta:
model = Team
exclude = ('creator', 'images', 'attachments', 'links', 'status')
# teams/views.py
@login_required()
def create(request):
if request.method == 'POST':
form = CreateTeamForm(request.POST, request.FILES)
if form.is_valid():
team = form.save(commit=False)
team.status = STATUS.ACTIVE
team.creator = request.user
team.save()
form.save_m2m()
return HttpResponseRedirect('/teams/' + team.slug)
else:
form = CreateTeamForm()
return render(request, 'teams/team_form.html', {'form': form})
# templates/teams/team_form.html
<html>
...
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit">
</form>
...
</html>
@dnoyes
Copy link
Author

dnoyes commented Jan 25, 2012

I know I can probably do this fancier, but it still seems mostly straightforward-ish. I should probably catch an integrity error but, well, I'm not yet. :-)

Thoughts?

@sleekslush
Copy link

Here's another fancy trick you can do with forms https://gist.github.com/1676619

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment