私のビュー login_user では、ldap サーバーを使用して認証を行っています。それは正常に動作します。私が作成したUzytkownikクラスのオブジェクトを最初にログインしようとすると、それも機能します(毎回ではなく、最初のログイン時のみ)。指定したグループにユーザーを追加するコードを追加すると、最初のログイン後にのみ機能します。2回目のログイン試行の後、djangoがそのグループからユーザーを削除するように動作します。
login_user ビューからのいくつかのコード:
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
prof=user.get_profile()
prof.stanowisko=user.stanowisko
prof.tytul_Naukowy=user.tytul
prof.save()
try:
uzytkownik=Uzytkownik.objects.get(username=user)
except Exception as e:
g = Group.objects.get(name= settings.DEFAULT_GROUP_NAME) #this 3 lines don't work as I expect
g.user_set.add(user)
g.save()
uzytkownik=Uzytkownik(username=user, tytul_Naukowy=user.tytul, stanowisko=user.stanowisko, imie=user.first_name, nazwisko=user.last_name)
uzytkownik.save()
login(request, user)
return HttpResponseRedirect("/")
設定.py:
DEFAULT_GROUP_NAME = 'common'
グループをユーザーに追加する2番目の方法を試しましたが、効果はありません(最初のログイン後にのみ機能します):
g=Groups.objects.get(name='common')
u=User.objects.get(username=user)
u.groups.add(g)
ログインして、ログインしているユーザーをこのグループに追加してページを更新すると、そのグループにいることがわかりますが、ログアウトしてログインした後は、どのグループにも属していません。ユーザー プロファイルにいくつかの変更を加えましたが、それが原因でしょうか?
設定.py:
AUTH_PROFILE_MODULE = 'user.UserProfile'
そして私のモジュール:
class UserProfile(models.Model):
class Meta:
verbose_name_plural = 'Profile'
user = models.OneToOneField(User, unique=True)
stanowisko=models.CharField(max_length=50)
tytul_Naukowy=models.CharField(max_length=30)
def __unicode__(self):
return self.user.username
def create_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.\
objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)