我有一个模型(权限),该模型允许用户A在A的议程中向另一个用户B授予一些权限,例如为A创建事件。 每个权限对象都有两个foreignKey Owner(用户A)和authorized_user(用户B),以及与该权限相对应的布尔字段。用户A可以具有链接到他的多个权限。
我的问题: 由于所有者字段和授权用户字段必须不可编辑或只读,因此在尝试修改权限时我会遇到一些困难。
我的html模板列出了所有表单或当前权限。
我的编辑表单仅由布尔权限字段构成。因此,我不知道 他们需要与哪个实例链接,当我需要保存动机...
models.py:
class Permission(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, editable=False)
authorized_user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False)
can_create_event = models.BooleanField(default=False)
can_edit_event = models.BooleanField(default=False)
出于安全原因,所有者和 authorized_user 字段必须不可编辑(或只读)。
对象创建示例:
owner_user = User.obects.get(username = "User01")
authorized_user_1 = User.obects.get(username = "User02")
authorized_user_2 = User.obects.get(username = "User03")
Permission.objects.create(owner = owner_user, authorized_user = authorized_user_1,
can_create_event=True, can_edit_event = False)
<Permission: Permission from owner User01 linked to User02>
Permission.objects.create(owner = owner_user, authorized_user = authorized_user_2,
can_create_event=False, can_edit_event = True)
<Permission: Permission from owner User01 linked to User03>
forms.py:
class Edit_permission_Form(forms.ModelForm):
class Meta:
model = Permission
fields = '__all__'
我有一个视图,允许权限对象的所有者编辑布尔字段。
views.py:
@login_required()
def managepermission(request):
if request.POST:
permission_form = Edit_permission_Form(request.POST)
if permission_form.is_valid():
#I don't know how to link the form to the good instance
permission_form.save()
return redirect('manage')
else:
#Get all the permission object linked to the logged user
actual_permissions = request.user.permission_set.all()
#Get all the username of the authorized users (to display in the template)
authorized_user_username = [permission.user.username for permission in actual_permissions]
#Get all the permission id
#to allow the owner to delete the entry by clinking on the delete link
permission_id = [permission.id for permission in actual_permissions]
#Generate all the forms linked to the permission objects
perm_edit_forms = [Edit_permission_Form(instance=perm) for perm in actual_permissions]
#Store all the data in a dict
data = {}
for i in range(len(actual_permission)):
data[authorized_user_username[i]] = {
"perm_id" : permission_id[i],
"form" : perm_edit_forms[i],
}
return render(request, 'perm/manageperm.html', {'data': data}
manageperm.html:
{% for key, value in data.items %}
{{key}} <a href="/perm/delete_perm/{{value.perm_id}}">Delete</a>
<form method="post" >
{% csrf_token %}
<table>
{{value.form.as_table}}
<tr>
<td><input type="submit" name="submit" value="Modify"/></td>
</tr>
</table>
</form>
{% endfor %}
因此,您对如何在视图收到POST请求时将表单链接到正确的实例有任何想法?
奖金问题:如何更有效地生成数据字典?