英文:
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't have a concept of "current" user.
Views on the other hand always have `request` as argument:
```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")
# fill the rest yourself
Same can be done in admin overriding one of save-related methods of ModelAdmin class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论