django-CreateView-如何使用ForeignKey字段插入默认值

时间:2020-07-22 09:06:53

标签: python django django-models django-views

当我进入CreateView时,我试图使用外键使模型具有默认动态值。让我解释一下:

使用以下型号:

class EquipmentType(models.Model):
    type        = models.CharField(max_length=100, unique=True)
    description = models.CharField(max_length=250, default='')
    date_posted = models.DateTimeField(auto_now_add=True)
    image       =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_type')
    active      =models.BooleanField(default=True)

    objects=EquipmentTypeManager()

    def __str__(self):
        return self.type

    def get_absolute_url(self):
        return reverse('equipmentType-home')
      

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)


######################################


class EquipmentItem(models.Model):
    type                        =models.ForeignKey(EquipmentType, on_delete=models.SET_NULL, null=True)
    brand                       =models.CharField(max_length=100, help_text='bho some help text')
    model_type                  =models.CharField(max_length=100)
    matricola                   =models.CharField(max_length=100)
    image                       =models.ImageField(default='default.jpeg', upload_to='equipment/equipment_item')
    libretto_uso_e_manutenzione = models.FileField(null= True, default= '', blank=True, upload_to='equipment/equipment_item/libretti_uso_e_man')
    elimina                      =models.BooleanField(default=False)

    def __str__(self):
        return str(self.id) + '. '+  self.type.type + ' - '+ self.brand + ' - ' +self.model_type

    def get_absolute_url(self):
        return reverse('equipmentItem-list', kwargs={'type': self.type.type})

首先,在前端,我列出所有不同的类型(锯,焊工等),然后通过单击特定类型,进入Item-list-view:

class EquipmentItem_ListView(LoginRequiredMixin, ListView):
    model = EquipmentItem
    template_name = 'equipment/equipmentItem_list.html'
    context_object_name = 'obj_list'
    ordering = ['brand'] 

    def get_queryset(self):
        type = get_object_or_404(EquipmentType, type=self.kwargs.get('type'))
        return EquipmentItem.objects.filter(type = type, elimina=False).order_by('brand')

然后使用以下创建视图:

class EquipmentItem_CreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    model = EquipmentItem
    template_name='equipment/equipmentItem_form.html'
    fields = ['type', 'brand', 'model_type', 'matricola', 'image', 'libretto_uso_e_manutenzione']

我希望视图使用以下模板创建新项目:

{% extends 'equipment/0_base.html'%}
{% load crispy_forms_tags %}
{% block content%}
<a class='btn btn-outline-dark mb-2' href="{{object.get_absolute_url}}">&#x2190; Indietro</a>
    <div class="content-section" >
      <form method="POST" enctype='multipart/form-data'>
        {%csrf_token%}
        <fieldset class='form-group'>
          <legend class='border-bottom mb-4'> Nuovo/modifica {{object.type.type}}</legend>

          {{ form | crispy }}
        </fieldset>
        <div class="form-group">
          <button type="submit" class='btn btn-outline-info' name="button"> Salva </button>
          <!-- <a href="  url 'equipmentType-home' %}" class='btn btn-outline-secondary ml-4'>Cancella</a> -->
        </div>
      </form>
    <a class='btn btn-outline-dark mt-2' href="{{object.get_absolute_url}}">&#x2190; Indietro</a>

    </div>
{% endblock %}

问题是,我希望表单默认插入类型。假设我单击了电锯,然后单击添加一个新电锯,我希望EquipmentItem模型的类型已经是电锯。

为此,在寻找可能的答案之后,我试图在EquipmentItem_CreateView中定义一个新方法:

def get_initial(self, *args, **kwargs):
        type = get_object_or_404(EquipmentType, type=self.kwargs.get('type'))
        initial = super(EquipmentItem_CreateView, self).get_initial(**kwargs)
        initial['type'] = 'CHAINSAW'
        return initial

2个主要问题:1浏览器向我返回404错误,再加上CHAINSAW是硬编码的。虽然我希望它是动态的。

希望解释很清楚。

如果您有任何建议,请告诉我。

非常感谢您。

卡洛

0 个答案:

没有答案
相关问题