无法将关键字“用户”解析为Django字段

时间:2020-04-05 20:13:51

标签: django

我是Django的新手。我已经阅读了文档,并且在这里查找了所有内容,但是数量不多。我基本上是想让个人资料显示在我已经创建的页面上。我正在使用自定义用户模型。

问题是,建议我只在“ user = request.user”中取出“ user”,但是问题是如果这样做,我将无法获得“ Profile”。

description = Profile.objects.get(user=request.user).description行出现错误:

FieldError at /mingle/
Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote
Request Method: GET
Request URL:    http://localhost:8000/mingle/
Django Version: 2.2.3
Exception Type: FieldError
Exception Value:    
Cannot resolve keyword 'user' into field. Choices are: date_joined, description, email, given_vote, id, is_active, is_admin, is_staff, is_superuser, last_login, logentry, matches, password, photo, username, uservote
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1420
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
Python Version: 3.7.3
Python Path:    
['/Users/papichulo/Documents/DatingAppCustom',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/Users/papichulo/Library/Python/3.7/lib/python/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Server time:    Sun, 5 Apr 2020 19:20:01 +0000

mingle.html

{% extends "dating_app/base.html" %}
{% load bootstrap4 %}


{% block content %}
<div class="container">
    {% if user %}
        <div class="container content is-child box column is-4 is-offset-4">
            <img src="{{ profile.photo.url  }}">
            <p style="font-size: 25px">{{profile}}</p>

            <b>Bio:</b>
            <p>{{profile.description}}</p>

        </div>
    {% else %}
        <p>Wait for more people to join!</p>
        <p>Help us get more user. Share this link to your friends! <a href="http://localhost:8000/">http://localhost:8000/</a></p>
  {% endif %}
{% endblock %}

views.py

def mingle(request):




    try:
        user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0])
    except IndexError:
        user = None
        print(Profile.username)
    try:

        description = Profile.objects.get(user=request.user).description
    except Profile.DoesNotExist:
        create = Profile.objects.get_or_create(user = request.user)
        return redirect('profile')

    match = models.Profile.objects.get(user=request.user).matches.all()
    context = dict(user = user, match = match)  
    return render(request, 'dating_app/mingle.html', context)

models.py

class ProfileManager(BaseUserManager):



    def create_user(self, username, email,description,photo, password=None):
        if not email:
            raise ValueError("You must creat an email")
        if not username:
            raise ValueError("You must create a username!")
        if not description:
            raise ValueError("You must write a description")
        if not photo:
            raise ValueError("You must upload a photo")

        user = self.model(
                email=self.normalize_email(email),
                username = username, 
                description= description,
                photo= photo,

            )

        user.set_password(password)
        user.save(using=self._db)
        return user 


    def create_superuser(self, username, email,description,photo, password):
        user = self.create_user(
                email=self.normalize_email(email),
                password=password,
                username=username,
                description=description,
                photo=photo,

            )

        user.is_admin=True
        user.is_staff=True
        user.is_superuser=True
        user.save(using=self._db)
        return user




class Profile(AbstractBaseUser):

    class Meta:
        swappable = 'AUTH_USER_MODEL'


    email                       = models.EmailField(verbose_name="email")
    username                    = models.CharField(max_length=30, unique=True)
    date_joined                 = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login                  = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                    = models.BooleanField(default=False)
    is_active                   = models.BooleanField(default=True)
    is_staff                    = models.BooleanField(default=False)
    is_superuser                = models.BooleanField(default=False)
    #what I added
    description                 = models.TextField()
    photo                       = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
    matches                     = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)



    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['description','photo','email']


    objects = ProfileManager()


    def __str__(self):
        return self.username


    def has_perm(self, perm, obj=None):
        return self.is_admin


    def has_module_perms(self,app_label):
        return True



class UserVote(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
    vote = models.BooleanField(default=False)

    class Meta:
        unique_together = (('user', 'voter'))

1 个答案:

答案 0 :(得分:0)

您是否在settings.py中设置了AUTH_USER_MODEL来指向您的自定义Profile模型?如果是这样,request.user将已经是您要过滤的用户。

您可以更改:

description = Profile.objects.get(user=request.user).description

收件人:

description = request.user.description