bside_12
bside_12

Reputation: 11

CSV import to model with many-to-many field

I'm trying to create a simple CSV import form that imports into my model GroupMembers. The GroupMembers model has a many-to-many field that links to my Groups model. The idea is you can upload a CSV membership file for a specific group; you select a group from a dropdown on the same page as the CSV upload. A member can be a member of multiple groups so if the member already exists, it should just add the new group relationship.

My code is partially working - it adds groupmembers - but I'm having problems with the many-to-many link to Groups. Here is my code so far

models.py (group)

class Group (models.Model):
    initials = models.CharField(max_length = 20)
    initials_lower = models.CharField(max_length = 20)
    full_name = models.CharField('Full name', max_length = 100)

models.py (groupmember) - this is where the csv adds to

from django.db import models
from datetime import datetime

class GroupMember (models.Model):
    name = models.CharField('Name', max_length = 30, unique = True)
    pub_date = models.DateTimeField('Date published', auto_now_add = True)
    groups = models.ManyToManyField('groups.Group', blank = True)

    def __unicode__(self):
        return self.name 

forms.py

from django import forms
import csv
from myproject.groupmembers.models import GroupMember
from myproject.groups.models import Group


class GroupImportForm (forms.Form):

    csv_file = forms.FileField()
    group_name = forms.ModelChoiceField(queryset=Group.objects.all())

    def save(self):
        records = csv.reader(self.cleaned_data["csv_file"])
        for line in records:
            input_data = GroupMember()
            input_data.handle = line[0]
            input_data.groups.create(initials=self.cleaned_data["group_name"]) <-- this is where the problem is
            input_data.save()

views.py (partial)

def batch_add (request):
    if request.method == 'POST':
        form = GroupImportForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
    else:
        form = GroupImportForm()

    return render_to_response(
        'members/batch_add.html',
        {
        'form': form,
        },
    context_instance=RequestContext(request)
    )

The error I'm now getting when uploading is that 'initials_lower' does not exist, which implies that it's trying to create a new Group record, which I don't want it to do. I simply want it to use the pre-existing group chosen from the select and add that to it's groups many-to-many field.

Hope that makes sense, any help appreciated

Upvotes: 1

Views: 1355

Answers (1)

Mariusz Jamro
Mariusz Jamro

Reputation: 31643

Use get_or_create which creates an object only if it doesn't exist yet:

input_data.groups.get_or_create(initials=self.cleaned_data["group_name"]) 

Upvotes: 1

Related Questions