Skip to content

Instantly share code, notes, and snippets.

@dnoyes
Created February 22, 2012 04:12
Show Gist options
  • Save dnoyes/1881280 to your computer and use it in GitHub Desktop.
Save dnoyes/1881280 to your computer and use it in GitHub Desktop.
How do I make multi-[blah] fields ?
# 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>
...
@dnoyes
Copy link
Author

dnoyes commented Feb 22, 2012

I also ran across:
http://djangosnippets.org/snippets/1848/

Would that apply in this situation?

@sleekslush
Copy link

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.

@dnoyes
Copy link
Author

dnoyes commented Feb 22, 2012

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