无法匹配 django 中 get_user_model 的字段

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


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


当用户添加新书时,我使用 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,)

...

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


...

{% 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 %}

...

我也分别带来了用户名和所有者以进行比较。我仍然获得所有书籍的展示详细信息。

https://img1.sycdn.imooc.com/6576c9f50001881205150431.jpg

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



月关宝盒
浏览 55回答 2
2回答

哔哔one

你应该使用:{% if request.user == book.owner %}&nbsp; &nbsp; …{% endif %}但尽管如此,在模板中进行过滤并不是一个好主意。您应该在视图中进行过滤,以便过滤可以在数据库级别进行。例如:from django.views.generic import ListViewfrom django.contrib.auth.mixins import LoginRequiredMixinclass BookListView(LoginRequiredMixin, ListView):&nbsp; &nbsp; model = Book&nbsp; &nbsp; # …&nbsp; &nbsp; def get_queryset(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; return super().get_queryset(*args, **kwargs).filter(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; owner=self.request.user&nbsp; &nbsp; &nbsp; &nbsp; )注意:文档建议使用AUTH_USER_MODEL设置 [Django-doc]而不是 get_user_model()[Django-doc]。这更安全,因为如果身份验证应用程序尚未加载,设置仍然可以指定模型的名称。因此最好这样写:from django.conf import settingsclass Book(models.Model):&nbsp; &nbsp; # …&nbsp; &nbsp; owner = models.ForeignKey(&nbsp; &nbsp; &nbsp; &nbsp; settings.AUTH_USER_MODEL,&nbsp; &nbsp; &nbsp; &nbsp; on_delete=models.CASCADE&nbsp; &nbsp; )

BIG阳

您需要更新模板中的条件{% if user.username == book.owner.username&nbsp; %}....{% endif %}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5