Django - 类别下拉列表

时间:2014-02-07 17:12:10

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

我正在尝试创建一个表单来添加新的“服务”(或编辑现有的服务)并显示类别的下拉列表,以便用户可以选择服务所属的类别。 我知道这一定是一个新手问题,但我已经调查好几天了,而且变得令人沮丧:(

出于某种原因,我看到了表单和类别列表,但是当我保存它时,我收到了这个错误:

无法分配“”:“Service.category”必须是“类别”实例。

这就是我现在所拥有的:

这是我的models.py

from django.db import models

class Category(models.Model):
        name = models.CharField('Nombre de Categoria', max_length=250)

        class Meta:
                verbose_name_plural = "categories"

        def __unicode__(self):
                return self.name

class Service(models.Model):
        category = models.ForeignKey(Category)
        name = models.CharField('Nombre del Servicio', max_length=250)
        duration = models.IntegerField('Duracion', default=0)
        price = models.FloatField('Precio', default=0.0)

        def __unicode__(self):
                return self.name

和我的forms.py

from django.forms import ModelForm, Select, ModelChoiceField
from services.models import Service, Category
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Fieldset, Button, Submit, Div, Row, HTML
from crispy_forms.bootstrap import AppendedText

class ServiceForm(ModelForm):
        helper = FormHelper()
        helper.form_tag = False
        helper.disable_csrf = True
        helper.layout = Layout (
                Div(
                        Div('name', css_class='col-sm-3'),
                        Div(AppendedText('duration', 'minutos'), css_class='col-sm-3'),
                        Div(AppendedText('price', '€'), css_class='col-sm-2'),
                        css_class='row'
                ),
        )
        class Meta:
                model = Service

class CategoryForm(ModelForm):
        name = ModelChoiceField(queryset=Category.objects.all())

        helper = FormHelper()
        helper.form_tag = False
        helper.disable_csrf = True
        helper.layout = Layout (
                Div(
                        Div('name', css_class='col-sm-6'),
                        css_class='row'
                ),
        )
        class Meta:
                model = Category
                widgets = { 'name': Select() }

这是views.py文件:

def manage_service(request, service_id=None):
        # Verifico si el request viene con un service_id
        if service_id:
                service = get_object_or_404(Service, pk=service_id)
                extra_value = 0
        else:
                service = Service()
                extra_value = 1

        CategoryInlineFormSet = inlineformset_factory(Category, Service, form=CategoryForm, extra=extra_value)

        if request.method == "POST":
                form = ServiceForm(request.POST, instance=service)
                category_formset = CategoryInlineFormSet(request.POST, instance=service)
                if form.is_valid():
                        service = form.save(commit=False)
                        if category_formset.is_valid():
                                service.save()
                                category_formset.save()
                                messages.add_message(request,
                                        messages.SUCCESS,
                                        mark_safe('Servicio <strong>%s</strong> guardado correctamente' % service.name))
                                return HttpResponseRedirect(reverse('services:index'))
        else:
                form = ServiceForm(instance=service)
                category_formset = CategoryInlineFormSet(instance=service)

        return render(request, 'services/service_form.html', {
                'form': form,
                'category_formset': category_formset,
        })

service_form.html

#...
<form enctype="multipart/form-data" class="" role="form" method='post' action=''>
        {% csrf_token %}

        {% crispy form %}
        {% crispy category_formset category_formset.form.helper %}

        <p>
                <button type="submit" value="Guardar" class="btn btn-primary">Guardar Servicio</button>
                <button type="submit" value="Borrar" class="btn btn-danger">Borrar Servicio</button>
        </p>
</form>
#...
你能不能让我知道我做错了什么? :(

提前致谢!!

0 个答案:

没有答案