无法保存在数据库中使用Djangp

时间:2015-07-10 07:10:53

标签: python django django-models

我想创建数据但无法保存在数据库中。

view.py

def roster_add(request):
    if request.method == "POST":
        form = RosterSetup(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('roster_add.html', pk=post.pk)
    else:
        form = RosterSetup()
    user    = User.objects.all().prefetch_related('groups').filter(groups__name='Operator')
    op      = Operator.objects.all().prefetch_related('person')
    result  = list(chain(user,op))
    fleet   = Fleet.objects.all()
    return render(
        request,
        'roster_add.html',
        {'form': form, 'result':result, 'fleet':fleet},
        context_instance= RequestContext(request)
    )

roster_add.html

<div class="form-group">
    <label>Person Operator</label>
    <select class="form-control">
    {% for results in result %}
        <option name="id_person" value="{{ results.person_id }}">{{ results.tag_id }}</option>
    {% endfor %}
    </select>
</div>

<div class="form-group">
    <label>Fleet</label>
    <select class="form-control">
        {% for fleets in fleet %}
            <option name="id_fleet" value="{{ fleets.id }}">{{ fleets.id_fleet }}</option>
        {% endfor %}                                               
    </select>
</div>

我在我的模板中使用<select><option但是数据无法保存在数据库中但是当我使用“输入”数据更改保存在数据库中

我这样改变:

<div class="form-group">
    <label>Person Operator</label><br>
    {{form.id_person}}
</div>

<div class="form-group">
    <label>Person Operator</label><br>
    {{form.id_fleet}}
</div>

但引导它不起作用。

forms.py

class RosterSetup(forms.ModelForm):
    class Meta:
        model  = Roster 
        fields  = ['name_roster','id_person','id_fleet','longitude']
你可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

尝试将下一个代码添加到roster_add.html

{% if form.errors %}
    <div class="alert alert-danger">
        <ul class="errors">
            {% for field in form %}
                {% if field.errors %}
                    <li>{{ field.label|safe }}<ul>
                        {% for error in field.errors %}
                            <li>{{ error|safe }}</li>
                        {% endfor %}
                    </ul></li>
                {% endif %}
            {% endfor %}
            {% for error in form.non_field_errors %}
                <li>{{ error|safe }}</li>
            {% endfor %}
        </ul>
    </div>
{% endif %}

答案 1 :(得分:0)

尝试将选择器的所有逻辑传递给表单

  

models.py

class Roster(models.Model):

    person = models.ForeignKey(Person, ...)
    fleet = models.ForeignKey(Fleet, ...)

    name_roster = models.CharField()
    longitude = models.CharField()

    class Meta:
        verbose_name = _('Roster')
        verbose_name_plural = _('Rosters')

    def __str__(self):
        return name_roster
  

form.py

from .models import *    

class RosterSetup(forms.ModelForm):

    name_roster = forms.CharField(
        label=_('Name Roster'),
        max_length=255,
        required=False,
        widget=forms.TextInput(
            attrs={'name': 'name_roster'}
        )
    )

    person = forms.ChoiceField(
        label=_('Person Operator'),
        required=True,
        widget=forms.Select()
    )

    fleet = forms.ChoiceField(
        label=_('Fleet'),
        required=True,
        widget=forms.Select()
    )

    longitude = forms.CharField(
        label=_('Longitude'),
        max_length=255,
        required=False,
        widget=forms.TextInput(
            attrs={'name': 'longitude'}
        )
    )

    def __init__(self, *args, **kwargs):

        super(RosterSetup, self).__init__(*args, **kwargs)

        user = User.objects.all().prefetch_related('groups').filter(groups__name='Operator')
        op = Operator.objects.all().prefetch_related('person')
        result = list(chain(user, op))

        fleet = Fleet.objects.all()

        # choices are required to validate the form (form.is_valid())
        self.fields['person'].choices = [(x.person_id, x.tag_id) for x in result]
        self.fields['fleet'].choices = [(x.pk, x.id_fleet) for x in fleet]

        self.fields['person'].queryset = result
        self.fields['fleet'].queryset = fleet

    class Meta:
        model = Roster
        fields = ['name_roster', 'person', 'fleet', 'longitude', ]
  

views.py

def roster_add(request):
    """

    :param request:
    :return:
    """
    form = RosterSetup()

    if request.method == "POST":

        form = RosterSetup(request.POST, request.FILES)

        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return redirect('roster_add.html', pk=instance.pk)

    return render(request, 'roster_add.html', {
        'form': form,
    })
  

roster_add.html

<div class="form-group {% if form.name_roster.errors %} has-error {% endif %}">
  <label>{{ form.name_roster.label }}</label>
  {{ form.name_roster }}
  {% if form.name_roster.help_text %}
    <span class="help-block">{{ form.name_roster.help_text }}</span>
  {% endif %}
  {% for error in form.name_roster.errors %}
    <span class="help-block">{{ error }}</span>
  {% endfor %}
</div>

<div class="form-group {% if form.person.errors %} has-error {% endif %}">
  <label>{{ form.person.label }}</label>
  {{ form.person }}
  {% if form.person.help_text %}
    <span class="help-block">{{ form.person.help_text }}</span>
  {% endif %}
  {% for error in form.person.errors %}
    <span class="help-block">{{ error }}</span>
  {% endfor %}
</div>

<div class="form-group {% if form.fleet.errors %} has-error {% endif %}">
  <label>{{ form.fleet.label }}</label>
  {{ form.fleet }}
  {% if form.fleet.help_text %}
    <span class="help-block">{{ form.fleet.help_text }}</span>
  {% endif %}
  {% for error in form.fleet.errors %}
    <span class="help-block">{{ error }}</span>
  {% endfor %}
</div>

<div class="form-group {% if form.longitude.errors %} has-error {% endif %}">
  <label>{{ form.longitude.label }}</label>
  {{ form.longitude }}
  {% if form.longitude.help_text %}
    <span class="help-block">{{ form.longitude.help_text }}</span>
  {% endif %}
  {% for error in form.longitude.errors %}
    <span class="help-block">{{ error }}</span>
  {% endfor %}
</div>