Django模型 – 参考用户ID

huangapple go评论54阅读模式
英文:

Django Model - Reference User ID

问题

新手使用Django。

我正在创建一个单词卡应用程序,其中我有两个模型 - 单词卡和单词卡套。

我希望我的数据库中的每个单词卡套都与创建它们的用户关联,使用外键链接到用户ID。

在如何实现这一点方面遇到了困难。

到目前为止的代码:

User = settings.AUTH_USER_MODEL

class CardSet(models.Model):
    name = models.TextField() 
    description = models.TextField()
    date_created = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

根据我所了解,Django中外键的第一个参数应该是一个模型,但在我的数据库中创建一个Card Set实例会将author_id返回为NULL。在这种情况下,我希望它返回当前登录的用户的ID。

有关如何解决这个问题的想法?

谢谢。

英文:

New to Django.

I'm creating a flashcard app where I have two models - Cards and Cards Set.

I want each card set in my database to be linked to the user who created them with a foreign key to the user id.

Having trouble understanding how to implement this.

Code so far

User = settings.AUTH_USER_MODEL


class CardSet(models.Model):
    name = models.TextField() 
    description = models.TextField()
    date_created = models.DateTimeField(default = timezone.now)
    author = models.ForeignKey(User, blank = True, null = True, on_delete=models.SET_NULL)

From what I understand, the first parameter of a Foreign Key in Django should be a model, but creating an instance Card Set in my database returns author_id as NULL. In this case, I want it to return the id of the user currently logged in.

Thoughts on how to solve this?

Thanks,

答案1

得分: 1

那必须在视图中完成或者在创建模型实例的其他代码中完成

模型通常被设计为与请求分开因此它们没有当前用户的概念

另一方面视图始终将`request`作为参数

```python
def create_cardset(request):
    if request.method == "POST":
        form = CardsetCreateForm(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect("somewhere")
    # 其余部分由您填写

在管理员界面中,可以通过覆盖ModelAdmin类的保存相关方法之一来完成相同的操作。


<details>
<summary>英文:</summary>

That has to be done in the view, or other code that creates the model instance.

Models are typically designed to be separate from request so they don&#39;t have a concept of &quot;current&quot; user.

Views on the other hand always have `request` as argument:

```python
def create_cardset(request):
    if request.method == &quot;POST&quot;:
        form = CardsetCreateForm(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            form.save()
            return redirect(&quot;somewhere&quot;)
    # fill the rest yourself

Same can be done in admin overriding one of save-related methods of ModelAdmin class.

huangapple
  • 本文由 发表于 2023年7月18日 05:55:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定