我想在我的模板中获取用户组,但用户组无法显示,
views.py
def Admin_add(request):
if request.method == "POST":
form = AdminSetup(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
user.groups.add(Group.objects.all)
post.save()
return redirect('admin_add.html', pk=post.pk)
else:
form = AdminSetup()
return render(request,'admin_add.html', {'form': form}, context_instance= RequestContext(request))
forms.py
class AdminSetup(forms.ModelForm):
class Meta:
model = Person, Operator, Owner, Contraktor, user.groups
fields = ['username','password','email', 'group.name']
admin_add.html
<div class="form-group">
<label>User Group</label>
<select class="form-control">
{% for group in user.groups.all %}
<option name="{{ group.name }}" value="{{ group.name }}">{{ group.name }}</option>
{% endfor %}
</select>
</div>
你可以帮我解决这个问题吗?
答案 0 :(得分:1)
似乎您想要向用户添加组。 如果那样,您可以尝试以下代码
def Admin_add(request):
if request.method == "POST":
form = AdminSetup(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
group_name = request.POST.get('group_name')
g = Group.objects.get(name=group_name)
g.user_set.add(user)
post.save()
return redirect('admin_add.html', pk=post.pk)
else:
form = AdminSetup()
groups = Group.objects.all()
return render(request,'admin_add.html', {'form': form, 'groups': groups}, context_instance= RequestContext(request))
<div class="form-group">
<label>User Group</label>
<select class="form-control">
{% for group in groups %}
<option name="group_name" value="{{ group.name }}">{{ group.name }}</option>
{% endfor %}
</select>
</div>