Django-Social-Auth错误(Django-Social-Auth Errors)
更新我尝试使用以下内容替换自定义管理器中的所有内容:
def create_user(self, username, email): return self.model._default_manager.create(username=username)
这会引发错误。 然后我尝试从我的自定义用户管理器返回用户,我得到“无法分配”“:”UserSocialAuth.user“必须是”Barbuser“实例。 从associate_user抛出。 它来自django.db.models.fields.related.py的内容。 基本上,我知道如何从我的自定义模型mgr正确创建用户。 我直接从文档引导我复制django内置的ModelManager中的所有内容。 帮帮我? 更新
我在配置django-social-auth时遇到了问题。 我已经待了3-4天了,我已经准备好了。 我安装了一个现有的用户注册应用程序,然后我安装并跟随django-social-auth github网站上的文档。 我在settings.py中添加了以下内容
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', 'barbuser', 'social_auth', ) AUTHENTICATION_BACKENDS = ( 'social_auth.backends.facebook.FacebookBackend', 'django.contrib.auth.backends.ModelBackend', ) FACEBOOK_APP_ID = os.environ.get('FACEBOOK_APP_ID') FACEBOOK_API_SECRET = os.environ.get('FACEBOOK_SECRET') TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'social_auth.context_processors.social_auth_by_type_backends', ) #SOCIAL_AUTH_ENABLED_BACKENDS = ('facebook',) SOCIAL_AUTH_DEFAULT_USERNAME = 'new_social_auth_user' LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/profile/' LOGIN_ERROR_URL = '/login-error/' SOCIAL_AUTH_USER_MODEL = 'barbuser.Barbuser'
我的models.py看起来像:
from datetime import date from django.db import models from django.contrib.auth.models import User from django.db.models import BooleanField from django.db.models.fields import DateTimeField from django.utils import timezone from django.utils.crypto import get_random_string class BarbuserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the address by converting the domain part of the email address to lowercase. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) return email def create_user(self, username, email=None, password=None): """ Creates and saves a User with the given username, email and password. """ email = 'you@email.com' if email.strip() == '' else email now = timezone.now() if not username: raise ValueError('The given username must be set') email = BarbuserManager.normalize_email(email) user = User(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now) user.set_password(password) user.save() barbuser = Barbuser(user=user, birthday=date.today(), last_login=user.last_login, name=username) barbuser.save() return barbuser def create_superuser(self, username, email, password): u = self.create_user(username, email, password) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789'): """ Generates a random password with the given length and given allowed_chars. Note that the default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(length, allowed_chars) def get_by_natural_key(self, username): return self.get(username=username) class Barbuser(models.Model): user = models.OneToOneField(User) username = models.CharField(max_length=200) last_login = DateTimeField(blank=True) is_active = BooleanField(default=True) birthday = models.DateField() name = models.CharField(max_length=200) objects = BarbuserManager() def __init__(self, *args, **kwargs): me = super(Barbuser, self).__init__(*args, **kwargs) barbuser = me return me def __unicode__(self): return self.name def is_authenticated(self): return self.user.is_authenticated()
我已将我的urls.py更新为包含'social_auth.urls',并且在身份验证后,用户将从我的views.py重定向到ViewProfile视图:
# Create your views here. from barbuser.forms import RegistrationForm, LoginForm from barbuser.models import Barbuser from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template.context import RequestContext def create_Barbuser(form): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password']) user.save() barbuser = Barbuser(user=user, name=form.cleaned_data['name'], birthday=form.cleaned_data['birthday']) barbuser.save() def process_form(form, request_context): if form.is_valid(): create_Barbuser(form) return HttpResponseRedirect('/profile/') else: return render_to_response('register.html', {'form': form}, context_instance=request_context) def render_blank_registration_form(request): '''When the user is not submitting the form, show them the blank registration form.''' form = RegistrationForm() context = {'form': form} return render_to_response('register.html', context, context_instance=RequestContext(request)) def BarbuserRegistration(request): """ Handles the registration of new Barbwire users. """ if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == "POST": return process_form(RegistrationForm(request.POST), RequestContext(request)) else: return render_blank_registration_form(request) def LoginRequest(request): ''' Handles Login requests. ''' if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] barbuser = authenticate(username=username, password=password) if barbuser is not None: login(request, barbuser) return HttpResponseRedirect('/profile/') else: return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) else: return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) else: form = LoginForm() return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) def LoginError(request): return render_to_response('login.html', {'form' : LoginForm()}, context_instance=RequestContext(request)) def LogoutRequest(request): logout(request) return HttpResponseRedirect('/') def ViewProfile(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/') else: return render_to_response('profile.html',{'barbuser' : request.user.barbuser }, context_instance=RequestContext(request))
我的问题是2倍。 当我在models.py中添加这些额外的东西时:
def facebook_extra_values(sender, user, response, details, **kwargs): return False from social_auth.signals import pre_update from social_auth.backends.facebook import FacebookBackend pre_update.connect(facebook_extra_values, sender=FacebookBackend)
我在服务器启动时遇到错误:assert isinstance(to,basestring),“%s(%r)无效.OignanKey的第一个参数必须是模型,模型名称或字符串%r”%(self。 类 ._ name _,to,RECURSIVE_RELATIONSHIP_CONSTANT)AssertionError:ForeignKey(None)无效。 ForeignKey的第一个参数必须是模型,模型名称或字符串'self'
当我删除它时,我可以通过Facebook流程登录,但我得到:/ Error / at / facebook /'NoneType'对象没有属性'extra_data'
我不确定我错过了什么或我哪里出错了。 有人可以帮我解释我哪里错了吗?
更新我在调试中跟踪了问题,显然我在associate_user函数中的social_auth.backends.pipeline.social.py中遇到IntegrityError,当它尝试“UserSocialAuth.objects.create”时。 然后它回退到一个调用social_auth_user()的Except块,这个函数为social_user返回None。 我得到的IntegrityError是:
insert or update on table "social_auth_usersocialauth" violates foreign key constraint "social_auth_usersocialauth_user_id_fkey" DETAIL: Key (user_id)=(17) is not present in table "auth_user".
我不熟悉知道如何,在何处或为何将social_user与我在models.py中的CustomUserManager中创建的用户相关联。 此外,我从models.py的底部删除了facebook_extra_values,额外的导入和preupdate.connect,因为我真的不明白它的作用或它的用途。 我只是从示例应用程序复制的东西试图修复我的第一个问题与缺少的关联。 帮帮我? 更新
Update I tried replacing everything in my custom manager with the following:
def create_user(self, username, email): return self.model._default_manager.create(username=username)
And that throws an error. I then tried returning the User from my custom user manager and I get 'Cannot assign "": "UserSocialAuth.user" must be a "Barbuser" instance.' thrown from associate_user. It comes from the bowels of django.db.models.fields.related.py. Basically, I'm stuck with knowing how to correctly create users from my custom model mgr. I was going directly off of the docs which lead me to copying everything from django's built in ModelManager. Help? Update
I'm having trouble configuring django-social-auth. I've been at this for 3-4 days and I'm getting ready to throw in the towel. I have a working existing user registration app installed and I then installed and followed along with the docs on django-social-auth github site. I added the following to my settings.py
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', 'barbuser', 'social_auth', ) AUTHENTICATION_BACKENDS = ( 'social_auth.backends.facebook.FacebookBackend', 'django.contrib.auth.backends.ModelBackend', ) FACEBOOK_APP_ID = os.environ.get('FACEBOOK_APP_ID') FACEBOOK_API_SECRET = os.environ.get('FACEBOOK_SECRET') TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'social_auth.context_processors.social_auth_by_type_backends', ) #SOCIAL_AUTH_ENABLED_BACKENDS = ('facebook',) SOCIAL_AUTH_DEFAULT_USERNAME = 'new_social_auth_user' LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/profile/' LOGIN_ERROR_URL = '/login-error/' SOCIAL_AUTH_USER_MODEL = 'barbuser.Barbuser'
My models.py looks like:
from datetime import date from django.db import models from django.contrib.auth.models import User from django.db.models import BooleanField from django.db.models.fields import DateTimeField from django.utils import timezone from django.utils.crypto import get_random_string class BarbuserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the address by converting the domain part of the email address to lowercase. """ email = email or '' try: email_name, domain_part = email.strip().rsplit('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) return email def create_user(self, username, email=None, password=None): """ Creates and saves a User with the given username, email and password. """ email = 'you@email.com' if email.strip() == '' else email now = timezone.now() if not username: raise ValueError('The given username must be set') email = BarbuserManager.normalize_email(email) user = User(username=username, email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now) user.set_password(password) user.save() barbuser = Barbuser(user=user, birthday=date.today(), last_login=user.last_login, name=username) barbuser.save() return barbuser def create_superuser(self, username, email, password): u = self.create_user(username, email, password) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyz' 'ABCDEFGHJKLMNPQRSTUVWXYZ' '23456789'): """ Generates a random password with the given length and given allowed_chars. Note that the default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ return get_random_string(length, allowed_chars) def get_by_natural_key(self, username): return self.get(username=username) class Barbuser(models.Model): user = models.OneToOneField(User) username = models.CharField(max_length=200) last_login = DateTimeField(blank=True) is_active = BooleanField(default=True) birthday = models.DateField() name = models.CharField(max_length=200) objects = BarbuserManager() def __init__(self, *args, **kwargs): me = super(Barbuser, self).__init__(*args, **kwargs) barbuser = me return me def __unicode__(self): return self.name def is_authenticated(self): return self.user.is_authenticated()
I've updated my urls.py to include 'social_auth.urls' and after authentication the user is redirected to ViewProfile view from my views.py:
# Create your views here. from barbuser.forms import RegistrationForm, LoginForm from barbuser.models import Barbuser from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template.context import RequestContext def create_Barbuser(form): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password']) user.save() barbuser = Barbuser(user=user, name=form.cleaned_data['name'], birthday=form.cleaned_data['birthday']) barbuser.save() def process_form(form, request_context): if form.is_valid(): create_Barbuser(form) return HttpResponseRedirect('/profile/') else: return render_to_response('register.html', {'form': form}, context_instance=request_context) def render_blank_registration_form(request): '''When the user is not submitting the form, show them the blank registration form.''' form = RegistrationForm() context = {'form': form} return render_to_response('register.html', context, context_instance=RequestContext(request)) def BarbuserRegistration(request): """ Handles the registration of new Barbwire users. """ if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == "POST": return process_form(RegistrationForm(request.POST), RequestContext(request)) else: return render_blank_registration_form(request) def LoginRequest(request): ''' Handles Login requests. ''' if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] barbuser = authenticate(username=username, password=password) if barbuser is not None: login(request, barbuser) return HttpResponseRedirect('/profile/') else: return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) else: return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) else: form = LoginForm() return render_to_response('login.html', {'form' : form}, context_instance=RequestContext(request)) def LoginError(request): return render_to_response('login.html', {'form' : LoginForm()}, context_instance=RequestContext(request)) def LogoutRequest(request): logout(request) return HttpResponseRedirect('/') def ViewProfile(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/') else: return render_to_response('profile.html',{'barbuser' : request.user.barbuser }, context_instance=RequestContext(request))
My problem is 2-fold. When I add this extra stuff in my models.py:
def facebook_extra_values(sender, user, response, details, **kwargs): return False from social_auth.signals import pre_update from social_auth.backends.facebook import FacebookBackend pre_update.connect(facebook_extra_values, sender=FacebookBackend)
I get errors on server startup: assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.class._name_, to, RECURSIVE_RELATIONSHIP_CONSTANT) AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
When I remove it I can go thru the login with facebook flow but I get: AttributeError at /complete/facebook/ 'NoneType' object has no attribute 'extra_data'
I'm not sure what I'm missing or where I've gone wrong. could somebody help explain where I'm going wrong?
Update I've traced the problem in debug and apparently I'm getting an IntegrityError in social_auth.backends.pipeline.social.py in the associate_user function when it tries "UserSocialAuth.objects.create". It then falls back into an Except block that calls social_auth_user() and this function returns None for the social_user. The IntegrityError I'm getting is:
insert or update on table "social_auth_usersocialauth" violates foreign key constraint "social_auth_usersocialauth_user_id_fkey" DETAIL: Key (user_id)=(17) is not present in table "auth_user".
I'm not familiar enough to know how, where or why to associate a social_user with the user created in my CustomUserManager in my models.py. Also I've removed the facebook_extra_values, extra imports, and the preupdate.connect stuff from the bottom of my models.py since I really don't understand what it does or what it's for. I was merely copying things from the example app trying to fix my first problem with the missing association. Help? Update
原文:https://stackoverflow.com/questions/11488958
最满意答案
关闭包装器流会自动关闭内部流。
因此,在您的情况下,您只需要关闭
ObjectOutputStream
。 关闭一个流两次不会抛出异常因此你已经做过的事情(尽管不必要)也可以。以下是实例化
ObjectOutputStream
时发生的情况public ObjectOutputStream(OutputStream out) throws IOException { bout = new BlockDataOutputStream(out); // inner stream being wrapped ... }
这是
ObjectOutputStream.close()
的实现public void close() throws IOException { flush(); clear(); bout.close(); // inner stream being closed }
Closing the wrapper stream automatically closes the inner stream.
So, in your case you only need to close
ObjectOutputStream
. Closing a stream twice does not throw an exception hence what you've already been doing (although unnecessary) works as well.Here's what happens when you instantiate an
ObjectOutputStream
public ObjectOutputStream(OutputStream out) throws IOException { bout = new BlockDataOutputStream(out); // inner stream being wrapped ... }
Here's the implementation of
ObjectOutputStream.close()
public void close() throws IOException { flush(); clear(); bout.close(); // inner stream being closed }
相关问答
更多-
也许用2个组合框? 也就是说,你在第一个中选择一个值,然后在第二个中显示单位: import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class ComboBoxTwo extends JPanel implements ActionListener { private JComboBox
mainComboBox; private JComb ... -
FANN(Fast Artifical Neural Network Library,快速人工神经网络库)是用C语言编写的一个很好的通用神经网络库,但它可以绑定任何你想要的语言(C ++,.NET,Python,Mathematica等)。 更好的是,它是开放源代码的,并根据LGPL授权,所以我想这对你来说可以。 如果您使用.NET(也是开放源代码), Neuron.NET是另一个不错的选择,虽然它在GPL下获得许可。 希望有所帮助。 FANN (Fast Artifical Neural Network ...
-
我会在业务层级别上进行日志记录,然后重新抛出错误。 如果这个图层将来在另一个项目中使用,它已经在进行日志记录。 重新生成异常允许该层的消费者将错误转换为友好的消息。 编辑:我认为这取决于记录的种类:如果你记录到独立于UI的中央数据库,将日志记录放入业务逻辑层。 如果日志记录特定于用户界面,例如将日志文件写入应用程序的目录,请将其放入UI中。 I'd put the logging at the business layer level and then rethrow the error. If this ...
-
我成功地解决了这个问题。 首先,我有不正确的点群中心,因此这些点在2D空间中变得完全不可分割。 中学,我不得不重写训练过程,从集合中挑选随机点。 第三个,我发现将int转换为int并不是最好的想法(数据丢失率非常高)。 链接到最终版本的代码: CLICK I successfully resolved the problem. First of all, I had incorrect centers of groups of points, so this points became completely ...
-
将您的学习率更改为0.01甚至更小的值。 它有帮助,但在我的情况下,准确性仍然比两层感知器更差 Change your learning rate to 0.01 or even smaller value. It helps but in my case accuracy is still worse than with two layers perceptron
-
关闭包装器流会自动关闭内部流。 因此,在您的情况下,您只需要关闭ObjectOutputStream 。 关闭一个流两次不会抛出异常因此你已经做过的事情(尽管不必要)也可以。 以下是实例化ObjectOutputStream时发生的情况 public ObjectOutputStream(OutputStream out) throws IOException { bout = new BlockDataOutputStream(out); // inner stream being wrapped ...
-
您可以在您的Vehicle类的构造函数上使用@JsonCreator注释 : @JsonCreator public Vehicle(Map
map) { String color = map.get("car.color"); String make = map.get("car.engine.make"); Integer power = Integer.valueOf(map.get("car.engine.power")); Engin ... -
如此处所示(使用连接模型创建范围): 问题:activerecord(rails3),使用includes链接范围 在这里(使用多列排序): Ruby on Rails:如何使用ActiveRecord对两列进行排序? 最后在这里(按关联模型排序): Rails 3.按关联模型排序 你可以这样做: scope :complex_sorting, lambda { joins(:questions) .order('questions_count DESC, question.answers_ ...
-
至于您正在寻找Stream-Wrapper类的示例代码,请参阅示例类注册为流包装器 。 由于您没有太多关于要在流数据上应用的修补程序的性质,因此很难提供更多信息。 也许流过滤器不那么复杂,也可以为您完成工作。 根据您的评论,这看起来更合适,因为您不想关心提供流但是使用它。 请参阅stream_filter_register()的手册页,其中包含有关如何即时过滤流的示例。 由于你没有分享实际上已经被破坏的东西,并且因为XML是一种文件格式,需要完全加载到内存中才能正确处理它(严格说来),我不能说流过滤器是否真 ...
-
您正在寻找的是绝对可能的。 我相信您应该寻找的搜索术语是diagramming libraries或graph drawing和flow-charting编程库。 那里有很多图书馆,包括商业图书馆和开源图书馆。 有关许多选项,请参阅此相关的SO问题 。 从您的描述中,我相信HTML图表库的yFiles应该是一个很好的匹配。 在线提供了两个演示,显示的场景似乎与您的描述相符: 实时演示Hierarchic Grouping 现场演示Collapsible Tree 由于这是一个具有巨大API的库,因此您可以轻 ...