Reputation: 785
from django.contrib.auth.models import User
from django.db import models
class Team(models.Model):
team_name = models.CharField(max_length=255, unique=True) ## they can create a new team here
description = models.TextField()
slug = models.SlugField(unique=True)
user = models.OneToOneField(User, blank=True, null=True) ## I connect my User here, so they can "own" this info...
Users have the option to create a new team (via the 'team_name' field), but I also want to give users the option to join another team (created by a different user), can I just add a new field to my Team model? And preferably, on the form, they could see a list of created teams, check the one they want to join and save the form.
Could I add something like this to my Team class:
team = forms.ModelMultipleChoiceField(queryset=Team.objects.all()).filter('team_name')
or maybe something like:
TEAM_CHOICES = Team.objects.all()).filter('team_name')
team = forms.CharField(widget=forms.Select(choices=TEAM_CHOICES))
And, how would that data be saved correctly?
Upvotes: 0
Views: 799
Reputation: 12859
If you wanted to allow users to join a team, I'd have a team attribute on the user model that was a FK to the Team.
Then in a form, you could define the list of available teams as you've suggested;
team = forms.ModelMultipleChoiceField(queryset=Team.objects.all())
And I'd also suggest looking at Select2 which creates a javascript 'search' type field that will filter the teams when someone starts to type characters.
Furthermore, the user
field in your Team
model would be better named as creator
or owner
so that you don't confuse them with a standard user associated with the team.
Upvotes: 1