form_obj前端页面(添加,编辑)和后端代码(rbac的角色表)

forms

# 角色的form
class RoleForm(forms.ModelForm):
    class Meta:
        model = models.Role
        fields = '__all__'
        exclude = ['permissions']
        widgets = {
            'name':forms.TextInput(attrs={'class':'form-control'}),
        }

  

 

后端

# 角色添加/编辑
def role_change(request, edit_id=None):
obj = models.Role.objects.filter(pk=edit_id).first()

form_obj = RoleForm(instance=obj)

title = '添加角色信息' if not obj else '编辑角色信息'

if request.method == 'POST':
form_obj = RoleForm(request.POST, instance=obj)
if form_obj.is_valid():
form_obj.save()

return redirect(reverse('role_list'))

return render(request, 'rbac/forms.html', {'form_obj': form_obj, 'title': title})

  

 

前端页面

{% extends 'layout.html' %}

{% block content %}


    <div class="panel panel-info">
          <div class="panel-heading">
              <h3 class="panel-title">{{ title }}</h3>
          </div>
          <div class="panel-body">
              <div class="col-lg-5 col-lg-offset-3 " style="margin-top: 80px">
                <form class="form-horizontal" novalidate method="post">
                    {% csrf_token %}
                    {% for field in form_obj %}

                        <div class="form-group {% if field.errors %}has-error{% endif %}">
                            <label for="{{ field.id_for_label }}"
                                class="col-sm-2 control-label">{{ field.label }}</label>
                            <div class="col-sm-10">
                                {{ field }}
                                <span class="help-block">{{ field.errors.0 }}</span>
                            </div>
                        </div>
                    {% endfor %}

                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-default">保存</button>
                        </div>
                    </div>
                </form>
            </div>
          </div>
        </div>

{% endblock %}

  

posted on 2019-06-18 09:49  哎呀!土豆  阅读(482)  评论(0编辑  收藏  举报

导航