具有多个ManyToManyField表单的Django

u3r8eeie  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(122)

这是我的第一个Django应用程序,向我自己(和我的公司)证明我们应该采用Django,但到目前为止,它被证明是棘手的。
我正在尝试创建一个应用程序,它可以显示公司的所有员工,以及每个员工的各种技能,这些技能被分类组织起来。

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Skill(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Employee(models.Model):
    login = models.CharField(max_length=16)
    fullname = models.CharField(max_length=64)
    skills = models.ManyToManyField(Skill, through='EmployeeSkill')

    def __str__(self):              # __unicode__ on Python 2
        return self.fullname

class EmployeeSkill(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    skill    = models.ForeignKey(Skill,    on_delete=models.CASCADE)
    LEVELS = (
        ('0', 'None'),
        ('1', 'Very Basic Knowledge (hours)'),
        ('2', 'Basic Knowledge (days)'),
        ('3', 'Good Understanding Knowledge (weeks)'),
        ('4', 'Excellent Knowledge (months)'),
        ('5', 'Expert Knowledge (years)'),
    )
    level = models.CharField(max_length=1, choices=LEVELS)
    desired_level = models.CharField(max_length=1, choices=LEVELS)

    def __str__(self):
        return "{} level of knowledge for {} is {} / desired is {}".format(self.employee.fullname, self.skill.name, self.level, self.desired_level)

我可以创建一个雇员、一个技能和一个雇员技能,甚至可以显示给定雇员的所有雇员技能,但我所纠结的是我应该如何创建一个表单,显示雇员所有可能的雇员技能,并允许该雇员更改与每个雇员技能关联的级别(和desired_level)。
救命啊!

n7taea2i

n7taea2i1#

您可以为ManyToManyField上的选项生成一个select,并在select上呈现每个选项,然后使用 AJAX 添加值。

<select name="material" id="id_material" required>
    <option value="0" disabled selected>Selecciona el material</option>
     {% for material in materiales %}
       <option value="{{material.id}}">{{material.descripcion}} ({{material.id_tipo_material.unidad}}) -  Total = {{material.cantidad}}</option>
     {% endfor %}
</select>

AJAX 请求:

function agrega_material(){

        var url = '{% url "paquetes:agrega_material_paquete" %}';

        var paquete = $('#id_cantidad').data('paquete');

        var material = $('#id_material').val();

        var cantidad = $('#id_cantidad').val();

        $.post(url,
        {
            paquete:paquete,
            material:material,
            cantidad:cantidad
        })
        .done(function( data ) {
            if(data['status'] == 'ko'){
                Materialize.toast('Cantidad es más grande que el material restante.', 4000)
            }else{
                $('#forma_material_paquete').html(data);
                $('select').material_select();
                Materialize.toast('El material ha sido agregado.', 4000)
            }
        });

        return false;
};

您将使用 AJAX 提交表单,将数据传递给django的一个视图,并添加元素或对视图进行修改,然后如果请求状态正常,您可以弹出一个通知。视图示例:

def agrega_material_paquete(request):
if request.method == 'POST':
    #Procesar datos
    id_paquete = int(request.POST.get('paquete')) //Here you receive the data of the AJAX request.
    paquete = get_object_or_404(Paquete, id=id_paquete )
    id_material = int(request.POST.get('material'))
    material = get_object_or_404(Material, id=id_material)
    cantidad_material = int(material.cantidad)
    cantidad = int(request.POST.get('cantidad'))

    if cantidad_material >= cantidad:
        Material_por_paquete.objects.create(paquete=paquete,material=material,cantidad=cantidad)
        #Mostrar vista de nuevo
        form = FormaMateriales()
        materiales = Material.objects.filter(activo=True)
        id_paquete = request.POST.get('paquete')
        materiales_paquete = Material_por_paquete.materiales_paquete(id_paquete)
        html = render_to_string('paquetes/select_materiales.html', {'form': form,'materiales':materiales,'materiales_paquete':materiales_paquete,'paquete':paquete})
        return HttpResponse(html)
    else:
        return JsonResponse({'status':'ko'})
else:
    return JsonResponse({'status':'ko'})

相关问题