我想在这些问题上寻求帮助。我知道它似乎与关于同一问题的其他问题相似,但我确实环顾四周,实际上没有什么可以解决我的问题。顺便说一句,这是我第二次问这里,所以请告诉我这条消息是否太长了。谢谢!
我正在使用AllAuth与Django 1.8和Python 3.5
我想根据AllAuth提供的用户名实现一个简单的个人资料页面。问题是,我没有在我的模型中指定用户名或电子邮件字段,我只是扩展它以添加一些我想要的信息,但似乎Django只识别我扩展的字段我找不到从AllAuth获取信息的正确方法。
这是我的代码(一些自定义字段是葡萄牙语,但所有核心内容都是英文):
简档/ models.py
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.utils.encoding import smart_text
UF_CHOICES = (
('SP', 'SP'),
('RJ', 'RJ')
)
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
uf = models.CharField(
max_length = 2,
blank=False,
default = 'SP',
choices = UF_CHOICES,
verbose_name = 'UF',
)
cidade = models.CharField(max_length=120, null=True, blank=True, default="Rio de Janeiro")
telefone = models.CharField(max_length = 20, blank=True, null=True, verbose_name = 'Telefone para Contato')
def __str__(self):
return smart_text(self.user)
def post_save_user_model_receiver(sender, instance, created, *args, **kwargs):
if created:
try:
Profile.objects.create(user=instance)
except:
pass
post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL)
简档/ forms.py
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"uf",
"cidade",
"telefone",
]
def profile(self, request, user):
user.uf = self.cleaned_data['uf']
user.cidade = self.cleaned_data['cidade']
user.telefone = self.cleaned_data['telefone']
user.save()
简档/ admin.py
from django.contrib import admin
# Register your models here.
from .models import Profile
admin.site.register(Profile)
简档/ views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from .models import Profile
# Create your views here.
@login_required
def profile_detail(request, username=None):
obj = get_object_or_404(Profile, username=username)
context = {
"object": obj,
}
template = 'profile_detail.html'
return render(request, template, context)
个人资料/ adapter.py [请注意此处显示的用户名] ,例如文档指定:http://django-allauth.readthedocs.io/en/latest/advanced.html
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
class MyAccountAdapter(DefaultAccountAdapter):
def get_login_redirect_url(self, request):
path = "/profiles/{username}/"
return path.format(username=request.user.username)
简档/ urls.py
from django.conf.urls import url
from .views import profile_detail
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', profile_detail, name='profile_detail'),
]
最后,错误信息:
Environment:
Request Method: GET
Request URL: http://localhost:8000/profiles/Sofia/
Django Version: 1.8.17
Python Version: 3.5.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'crispy_forms',
'newsletter',
'profiles',
'properties')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/Users/Alex/Desktop/Hunters/src/profiles/views.py" in profile_detail
9. obj = get_object_or_404(Profile, username=username)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/shortcuts.py" in get_object_or_404
155. return queryset.get(*args, **kwargs)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/query.py" in get
325. clone = self.filter(*args, **kwargs)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/query.py" in filter
679. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/query.py" in _filter_or_exclude
697. clone.query.add_q(Q(*args, **kwargs))
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/sql/query.py" in add_q
1310. clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q
1338. allow_joins=allow_joins, split_subq=split_subq,
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/sql/query.py" in build_filter
1150. lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/sql/query.py" in solve_lookup_type
1036. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/Users/Alex/Desktop/Hunters/lib/python3.5/site-packages/django/db/models/sql/query.py" in names_to_path
1397. "Choices are: %s" % (name, ", ".join(available)))
Exception Type: FieldError at /profiles/Sofia/
Exception Value: Cannot resolve keyword 'username' into field. Choices are: cidade, id, telefone, uf, user, user_id
答案 0 :(得分:2)
好的,我发现了这个问题。我花了很长时间,因为我没有以正确的方式看待它。
问题不在于代码本身,更多的是关于哪个模型实际存储了我需要的信息。在这种情况下,我想从数据库中获取用户和配置文件信息,而不会意识到它们是两个独立的模块。我试图从用户存储的个人资料信息中获取。
原作是:
profiles.views.py(旧与错)
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from .models import Profile
# Create your views here.
@login_required
def profile_detail(request, username=None):
obj = get_object_or_404(Profile, username=username)
context = {
"object": obj,
}
template = 'profile_detail.html'
return render(request, template, context)
profiles.views.py(新的和工作的) - 请注意导入如何从Profile更改为User以及我如何从obj.profile创建新用户obj
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, get_object_or_404
# Create your views here.
@login_required
def profile_detail(request, username=None):
obj = get_object_or_404(User, username=username)
user = obj.profile
context = {
"object": obj,
"user": user,
}
template = 'profile_detail.html'
return render(request, template, context)
非常感谢所有的帮助!
答案 1 :(得分:0)
我扩展了AbtractUser类,并将USERNAME_FIELD设置为电子邮件; 我还将用户名字段设置为“无”。 尝试使用错误的凭据以管理员身份登录会引发相同的错误。这是我的CustomUser模型。
(venv)xyz_api$ python manage.py createsuperuser
我所需要的只是使用正确的电子邮件和密码来成功登录。您可以使用以下命令从命令创建超级用户
:{{1}}