在其他表单模型中添加外部模型 - Django 1.8

时间:2015-12-06 22:54:18

标签: python django

当我尝试以AgregarActividad形式添加外来对象'linea'时,我在django中出错

views.py

someMethod()

forms.py

@login_required(login_url='/')
def agregar_actividad(request, pk):
    linea =  Linea.objects.filter(pk=pk)

    if request.method == "POST":
        form = AgregarActividad(request.POST, linea = linea)
        if form.is_valid():
            actividad = form.save(commit=False)
            actividad.save()
            return redirect('/lineas/lista')
    else:
        form = AgregarLinea()
    return render(request, 'lineas/editar_actividad.html', {'form': form})

models.py

class AgregarActividad(forms.ModelForm):

    class Meta:
        model = Actividad
        fields = '__all__'
        exclude = ['updated']

    def __init__(self, *args, **kwargs):
        linea = kwargs.pop('linea')
        print linea
        super(AgregarActividad, self).__init__(*args,**kwargs)
        self.fields['descripcion'].required = True
        self.fields['linea'] = linea

agregar_actividad.html

class Actividad(models.Model):
    class meta:
        verbose_name_plural = "Actividades"

    descripcion =  models.CharField(max_length=75, unique=True)
    linea = models.ForeignKey('Linea')
    updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)

    def __str__(self):
        return self.descripcion

引发我的错误

{% extends 'base/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <div class="col-sm-6 col-sm-offset-3">
        <h1>Nueva Actividad</h1>
        <form method = "POST" class="post-form">
            {% csrf_token %}
            {{ form|crispy }}
          <input class="btn btn-default" type="submit" value="Submit">   <!-- Boton para subir POSTEAR LOS DATOS -->
        </form>
    </div>
{% endblock %}

回溯

AttributeError at /linea/19/actividad/agregar/
'QuerySet' object has no attribute 'widget'
Request Method: POST
Request URL:    http://localhost:8000/linea/19/actividad/agregar/
Django Version: 1.8.5
Exception Type: AttributeError
Exception Value:    
'QuerySet' object has no attribute 'widget'

1 个答案:

答案 0 :(得分:1)

问题在于表格中的这一行

self.fields['linea'] = linea

用这样的查询集或对象替换字段是没有意义的。

相反,请从表单中排除字段

class AgregarActividad(forms.ModelForm):

    class Meta:
        model = Actividad
        fields = '__all__'
        exclude = ['updated', 'linea']

在视图中,在保存之前指定对象。请注意,您应该使用get()而不是filter()来获取单个对象。

linea =  Linea.objects.get(pk=pk)

if request.method == "POST":
    form = AgregarActividad(request.POST, linea = linea)
    if form.is_valid():
        actividad = form.save(commit=False)
        actividad.linea = linea
        actividad.save()
        return redirect('/lineas/lista')