【问题标题】:Not able to match field from get_user_model in django无法匹配来自 django 中 get_user_model 的字段
【发布时间】:2020-07-24 04:07:55
【问题描述】:

我正在开展一个图书库存项目,用户可以在其中添加他们的图书,而其他人可以看到它们。

我试图在主页上显示所有书籍,但只有所有者会看到“编辑”和“删除”选项。其他人将看到“查看详细信息”选项。

当用户添加新书时,我使用了 Django 的 get_user_model() 功能来获取书的所有者:

...
class Book(models.Model):
    title =models.CharField(max_length =255)
    author =models.CharField(max_length =255)
    genre =models.CharField(max_length=255)
    date=models.DateTimeField(auto_now_add =True)
    owner =models.ForeignKey(get_user_model(),on_delete =models.CASCADE,)
...

现在,当我映射用户的用户名和图书所有者时,它不起作用。 这个 id 是 HTML 模板:

...
{% for book in object_list %}
<div class="card">
    <span class="font-weight-bold">{{book.title}}</span> 
    <span class="font-weight-bold">by {{book.author}}</span>
    <span class="text-muted">Genre: {{book.genre}}</span>
    <span class="text-muted">Owner: {{book.owner}}</span>
    <span class="text-muted">User: {{user.username}}</span>
    <div class="card-footer text-center text-muted">
        {% if user.username == book.owner  %}
         <a href ="{% url 'book_edit' book.pk %}">Edit</a> | <a href="{% url 'book_delete' book.pk %}">Delete</a>
         {% else %}
         <a href="#">Show Details</a>
         {% endif %}
        </div>
</div>
<br />
{% endfor %}
...

我也将用户名和所有者分别带上以进行比较。 我仍然在获取所有书籍的展览详情。

对于调试,我还尝试将 'user.username' 和 'book.owner' 等同于 'jitesh2796' 。虽然前者有效,但后者无效。所以我想问题出在 django 领域的某个地方。

【问题讨论】:

    标签: python html django django-models


    【解决方案1】:

    你应该使用:

    {% if request.user == book.owner %}
        …
    {% endif %}

    但是在 模板 中过滤并不是一个好主意。您应该在视图中进行过滤,以便可以在数据库级别进行过滤。例如:

    from django.views.generic import ListView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class BookListView(LoginRequiredMixin, ListView):
        model = Book
        # …
    
        def get_queryset(self, *args, **kwargs):
            return super().get_queryset(*args, **kwargs).filter(
                owner=self.request.user
            )

    注意documentation 建议 使用AUTH_USER_MODEL setting [Django-doc] over get_user_model() [Django-doc]。 这更安全,因为如果尚未加载身份验证应用程序,设置 仍然可以指定模型的名称。因此最好写:

    from django.conf import settings
    
    class Book(models.Model):
        # …
        owner = models.ForeignKey(
            settings.AUTH_USER_MODEL,
            on_delete=models.CASCADE
        )

    【讨论】:

      【解决方案2】:

      您需要更新模板中的条件

      {% if user.username == book.owner.username  %}
      ....
      {% endif %}
      

      【讨论】:

      • 我试过了,它奏效了。仍然想了解它是如何工作的,因为我没有看到所有者的任何用户名属性。
      • 用户模型有很多字段,如名字、姓氏、用户名等......在外键中,您可以访问用户模型的所有字段,如下所示:owner.first_name, owner.last_name, owner.user_name。如果您有特定模型的外键,则可以访问所有字段,例如 USER_MODEL。更多信息请关注docs.djangoproject.com/en/3.0/ref/contrib/auth
      猜你喜欢
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多