Django - 提交表单时将多个字段插入数据库

时间:2013-11-28 02:20:54

标签: python django django-models django-forms django-views

很抱歉有一些新手问题,但是我希望对它进行排序,如果它适用于我当前的实现并进行一些小的调整,那将是理想的。我想要做的是让form具有多个名称相同的字段,但可以根据选择而有所不同。我希望表单将这些选项插入到DB中。现在它只抓取表格中的最后一个值(最后解析),提交,然后扔掉其余的。

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(模板

            <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>

感谢任何帮助。希望这个问题有道理。这是漫长的一天,我并没有真正想得太清楚。

*编辑* 我解决了我的问题。我本来想要实现一个Django formset,但却不知道正确的词。 :)

在这里找到一个非常有用的网站,如何设置一个:http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/

干杯

1 个答案:

答案 0 :(得分:1)

我解决了我的问题。我正在寻求实现一个Django formset,但只是不知道正确的单词。 :)

在这里找到一个非常有用的网站,如何设置一个:http://stellarchariot.com/blog/2011/02/dynamically-add-form-to-formset-using-javascript-and-django/

干杯