Created
February 22, 2012 04:12
-
-
Save dnoyes/1881280 to your computer and use it in GitHub Desktop.
How do I make multi-[blah] fields ?
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
# models (old) | |
class Team(models.Model): | |
# ... | |
attachments = models.ManyToManyField(Attachment, blank=True, | |
related_name="%(app_label)s_%(class)s_attachments") | |
images = models.ManyToManyField(ImageAttachment, blank=True, | |
related_name="%(app_label)s_%(class)s_images") | |
links = models.ManyToManyField(Link, blank=True, | |
related_name="%(app_label)s_%(class)s_links") | |
# models (what I'm moving to) -- How do I make these fields "multi" ? | |
class Team(models.Model): | |
# ... | |
attachments = models.ImageField(upload_to=[blah], ...) | |
images = models.FileField(upload_to=[blah], ...) | |
links = models.URLField(...) | |
# views | |
class TeamUpdateView(UpdateView): | |
model = Team | |
form_class = UpdateTeamForm | |
queryset = Team.objects.filter(status=STATUS.ACTIVE) | |
# ... | |
class TeamCreateView(CreateView): | |
model = Team | |
form_class = CreateTeamForm | |
# ... | |
#forms (pretty bare) | |
class BaseTeamForm(forms.ModelForm): | |
class Meta: | |
model = Team | |
exclude = ('creator', 'images', 'attachments', 'links', 'status') | |
abstract = True | |
class CreateTeamForm(BaseTeamForm): | |
pass | |
class UpdateTeamForm(BaseTeamForm): | |
pass | |
# template (create and edit) | |
... | |
<form enctype="multipart/form-data" method="post"> | |
{% csrf_token %} | |
{{form.as_p}} | |
<input type="submit"> | |
</form> | |
... |
You probably want something more along the following lines:
class TeamImage(models.Model):
team = models.ForeignKey(Team)
images = models.ImageField(upload_to=[blah], ...)
class TeamAttachment(models.Model):
team = models.ForeignKey(Team)
file = models.FileField(upload_to=[blah], ...)
This gives you a one-to-many relationship for images and attachments. Specifically meaning a team can have x attachments or y images. But each image and each attachment belongs to only a single team.
Then you'll want to use an inlineformset_factory to create your form that you'll present in a view.
That explanation definitely makes sense. Thanks for your continued django help! I'll reply to this gist with my success/failure ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also ran across:
http://djangosnippets.org/snippets/1848/
Would that apply in this situation?