在保存Django之前过滤已登录的Users组



注册新用户时,所有组都列出供用户从下拉列表中选择。我正试图将此过滤为仅登录用户所属的组。

views.py

from .forms import UserRegisterForm
@login_required(login_url='login')      
def addUser(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save()
group = form.cleaned_data['group']        
group.user_set.add(user)
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'base/adduser.html', {'form':form})

forms.py

from django.contrib.auth.forms import UserCreationForm    
class UserRegisterForm(UserCreationForm):
group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True)



class Meta:
model = User
fields = ['username', 'password1', 'password2', 'group'] 

adduser.html

> {% extends 'main.html' %}
> 
> {% block content %} 
<style>
>     .home-container{ display:grid; grid-template-columns: 1fr 4fr;
> 
>     } </style> <div class="home-container">
>     
>         
>         
>     <div>
>         
>     </div>
>         <div>
>             {% include 'settingmenu.html' %}
>         
>     </div>
>     <div></div>
>     <div>
>         <form method="POST" action="">
>             {% csrf_token %}
>     
>             {{form.as_p}}
>     
>             <input type="submit" value="Add User" />
>         </form>
> 
> 
> 
>     </div> </div>   {% endblock %}

你可以试试这个

forms.py

class UserRegisterForm(UserCreationForm):
group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True)
def __init__(self,*args,**kwargs):
# you can pass user id or 
#what ever you need to filter groups
user = kwargs.pop('user',None) 
super(UserCreationForm).__init__(*args,**kwargs)
self.fields["group"].choices = # use user to query groups he belongs to


class Meta:
model = User
fields = ['username', 'password1', 'password2', 'group'] 

,在视图中使用

form = UserRegisterForm(request.POST,user=your_user)

不是

form = UserRegisterForm(request.POST)

相关内容

  • 没有找到相关文章

最新更新