jaredgilmore
jaredgilmore

Reputation: 657

Django - Insert Multiple Fields Into DB When Submitting Form

Sorry for kind of a newbie question, but I am looking to get this sorted and if it works with my current implementation with some minor tweaking, that would be ideal. What I want to do is have a form with multiple fields that are identical in names, but can be different based on the choices. I would like the form to insert these choices into the DB. Right now it's only grabbing the last value in the form (last parsed), submitting that, and throwing out the rest.

models.py

class JobProficiencies(models.Model):

    jobs = models.ManyToManyRel(Jobs)
    job = models.ForeignKey(Jobs)

    # All the Proficiencies a Company is able to flag
    JOB_PROFICIENCIES = {
        ('CC', 'C / C++'),
        ('CH', 'C#'),
        ('CO', 'COBOL'),
        ('CS', 'CSS'),
        ('GI', 'Git'),
        ('HT', 'HTML'),
        ('JA', 'Java'),
        ('JS', 'JavaScript'),
        ('JQ', 'JQuery'),
        ('LI', 'LISP'),
        ('NE', '.NET'),
        ('PE', 'Perl'),
        ('PH', 'PHP'),
        ('PY', 'Python'),
        ('RU', 'Ruby'),
        ('SH', 'Shell'),
        ('SQ', 'SQL'),
        ('AU', 'Automation Writing'),
        ('UT', 'Unit Testing'),
        ('GB', 'Grey Box Testing'),
        ('EC', 'Edge Case Testing'),
        ('PH', 'Adobe Photoshop'),
        ('CA', 'Computer Aided Graphics'),
        ('3D', '3D Modeling'),
        ('GI', 'GIMP'),
        ('GP', 'Graphic Design'),
        ('XS', 'Cross Site Scripting'),
        ('SQ', 'SQL Injection'),
        ('MM', 'Man in the Middle'),
        ('PC', 'PCI'),
        ('SA', 'Security Auditing'),
        ('WI', 'Windows'),
        ('MA', 'Macintosh'),
        ('LI', 'Linux'),
        ('UN', 'Unix'),
        ('IP', 'IPv4 / IPv6'),
        ('CN', 'Computer Networking'),
        ('EN', 'Enterprise Networking'),
        ('DR', 'Disaster Recovery'),
    }

    PROFICIENCY_REQUIRED = {
        ('RE', 'Required'),
        ('RC', 'Recommended'),
        ('OP', 'Optional')
    }

    COMFORT_LEVEL = {
        ('B', 'Beginner'),
        ('N', 'Novice'),
        ('I', 'Intermediate'),
        ('E', 'Expert'),
    }

    job_proficiency = models.CharField(max_length=2, choices=JOB_PROFICIENCIES, null=False, unique=True)
    proficiency_required = models.CharField(max_length=2, choices=PROFICIENCY_REQUIRED, null=False, unique=True)
    comfort_level = models.CharField(max_length=1, choices=COMFORT_LEVEL, null=False)

views.py

# Create a Job (Companies only)
@login_required(login_url='/login/')
@user_passes_test(lambda u: u.groups.filter(name='Company').exists(), login_url='/login/', redirect_field_name='Only Companies can post Jobs!')
def create(request):

    args = {}
    args.update(csrf(request))
    args['job'] = JobCreateForm(request.POST or None)
    args['job_proficiencies'] = JobCreateProficienciesForm(request.POST or None)

    if request.method == 'POST':
        job = args['job']
        job_proficiencies = args['job_proficiencies']

        if job.is_valid() and job_proficiencies.is_valid():
            m_tags = job.cleaned_data['m_tags']
            _job = job.save(commit=False)
            _job.user = request.user
            _job.dateCreated = datetime.now()
            _job.save()
            _job_proficiencies = job_proficiencies.save(commit=False)
            _job_proficiencies.job_id = _job.id
            _job_proficiencies.save()
            # Without this next line the tags won't be saved.
            for m_tag in m_tags:
                _job.tags.add(m_tag)
            messages.success(request, "Job Posted!")
            return HttpResponseRedirect('/job/all/')
        else:
            messages.error(request, "There are form errors!")
            return render_to_response('job/new.html/', args, context_instance=RequestContext(request))
    return render_to_response('job/new.html', args, context_instance=RequestContext(request))

job/create.html (template

            <form action="/job/create/" method="post" class="form-inline">
            {% csrf_token %}
            <div class="row">
                <div class="col-md-6">
                    <div class="row">
                            {{ job.title.errors }}
                            <div class="span6 inline"><label class="control-label">Job Title: </label>{{ job.title|add_class:"form-control"|attr:"placeholder:Example: Need Java Developer" }} </div>
                            {{ job.about.errors }}
                            <div class="span6 inline"><label class="control-label">About Job: </label>{{ job.about|add_class:"form-control resize:none"|attr:"placeholder:Example: 'Need Java Developer for new enterprise application!" }} </div>
                            {{ job.gitHubLink.errors }}
                            <div class="span6 inline"><label class="control-label">GitHub Link: </label>{{ job.gitHubLink|add_class:"form-control"|attr:"placeholder:Example: github.com/johndoe" }} </div>
                            {{ job.wage.errors }}
                            <div class="span6 inline"><label class="control-label">Wage: </label>{{ job.wage|add_class:"form-control"|attr:"placeholder:Example: $25/hour, $500 COD, Free, etc." }} </div>
                            {{ job.m_tags.errors }}
                            <div class="span6 inline"><label class="control-label">Keywords: </label>{{ job.m_tags|add_class:"form-control"|attr:"placeholder:Example: python, django, java, QA, design" }} </div>
                            <button class="btn btn-lg btn-success btn-block" type="submit">Post Job</button>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="row">
                        <label class="control-label">Job Proficiencies: </label>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            {{ job_proficiencies.job_proficiency|add_class:"form-control" }}
                        </div>
                        <div class="col-md-3">
                            {{ job_proficiencies.proficiency_required|add_class:"form-control" }}
                        </div>
                        <div class="col-md-3">
                            {{ job_proficiencies.comfort_level|add_class:"form-control" }}
                        </div>
                        <div class="col-md-6">
                            {{ job_proficiencies.job_proficiency|add_class:"form-control" }}
                        </div>
                        <div class="col-md-3">
                            {{ job_proficiencies.proficiency_required|add_class:"form-control" }}
                        </div>
                        <div class="col-md-3">
                            {{ job_proficiencies.comfort_level|add_class:"form-control" }}
                        </div>
                    </div>
                </div>
            </div>
        </form>

Any assistance is appreciated. Hope this question makes sense. It's been a long day and I'm not really thinking too clearly.

* EDIT * I solved my question. I was looking to implement a Django formset but just didn't know the right word for it. :)

Found a very useful website here as well on how to set one up: http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/

Cheers

Upvotes: 0

Views: 1113

Answers (1)

jaredgilmore
jaredgilmore

Reputation: 657

I solved my question. I was looking to implement a Django formset but just didn't know the right word for it. :)

Found a very useful website here as well on how to set one up: http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/

Cheers

Upvotes: 1

Related Questions