Skip to main content
 首页 » 编程设计

python之无法将关键字 'username' 解析为字段。选项有 : city, id, phone, etc

2024年10月01日2EasonJim

我想就这些问题寻求帮助。我确实知道它看起来与关于同一问题的其他问题相似,但我确实环顾四周,没有什么可以真正解决我的问题。顺便说一句,这是我第二次在这里提问,如果这条消息太长请告诉我。谢谢!

我在 Django 1.8 和 Python 3.5 中使用 AllAuth

我想根据 AllAuth 提供的用户名实现一个简单的个人资料页面。问题是,我没有在我的模型中指定用户名或电子邮件字段,我只是扩展它以添加一些我想要的信息,但似乎 Django 只识别我扩展的字段并且我无法找到从 AllAuth 获取该信息的正确方法。

这是我的代码(一些自定义字段是葡萄牙语,但所有核心内容都是英语):

配置文件/模型.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) 

profiles/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 

请您参考如下方法:

好的,我发现了问题。花了我很长时间,因为我没有以正确的方式看待它。

问题不在于代码本身,而在于哪个模型实际存储了我需要的信息。在这种情况下,我想从数据库中获取用户和配置文件信息,但没有意识到它们是两个独立的模块。我试图从用户存储的配置文件信息中获取。

原文是:

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) 

非常感谢所有的帮助!