Django ModelForm ManyToManyField,html删除ManyToManyField

时间:2018-07-31 12:00:18

标签: django

我想制作一个通用页面 但是我想要一个通用方法,因为我不知道其他模型将具有哪些领域。 还有其他方法可以删除ManyToManyField或ForeignKey? 但我不希望权限字段 我知道用

from django import forms
from models import Role
class PostForm(forms.ModelForm):
    class Meta:
        model=Role
        exclude=['permission']

models.py

class Role(models.Model):
    """
    权限角色表
    """
    name = models.CharField(max_length=20, verbose_name='角色名')
    description = models.CharField(max_length=255, verbose_name='描述', null=True, blank=True)
    permissions = models.ManyToManyField(verbose_name='拥有权限', to='Permission',null=True, blank=True)

    class Meta:
        db_table = 'roles'
        verbose_name = "权限角色表"
        verbose_name_plural = "权限角色表"

    def __str__(self):
    return self.name

views.py

class ModelAdmin():
    def get_modelform_class(self):
        ModelFormDemo = self.page_model_form
        if not self.page_model_form:
            from django.forms import ModelForm
            class ModelFormDemo(ModelForm):
                class Meta:
                    model = self.model
                    fields = "__all__"
            # 等同于
            # _meta = type('Meta', (object,), {'model': self.model_class, "fields": "__all__"})
            # model_form_cls = type('DynamicModelForm', (ModelForm,), {'Meta': _meta})
        return ModelFormDemo

    def add_view(self, request):
        ModelFormDemo = self.get_modelform_class()
        form = ModelFormDemo()
        if request.method == "POST":
            print(request.POST)
            form = ModelFormDemo(request.POST)
            if form.is_valid():
                obj = form.save()
                return redirect(self.changelist_view)
        return render(request, "xadmin/add_view.html", locals())

form.html

{% csrf_token %}
{% for field in form %}
<div class="layui-form-item">
    <label for="name" class="layui-form-label">
        <span class="x-red"></span>{{ field.label }}
    </label>
    <div class="layui-input-inline">
        <input type="text" id="name" name="{{ field.name }}"
               {% if field.field.required %}required="" lay-verify="required"{% endif %}
               autocomplete="off" class="layui-input" value="{{ field.is_hidden  }}" >

    </div>
    <style>
        .layui-word-aux ul li {
            color: red;
        }
    </style>

{%endfor%}

例如 enter image description here 角色名==名称描述== description拥有权限==权限

0 个答案:

没有答案