简体   繁体   English

保存到 model,它在 Django 中引用自定义用户 model(通过 ForeignKey)

[英]Save to a model which is referencing a custom user model (via ForeignKey) in Django

I am trying to save to a model named Blog from inside Django's views.py file.我正在尝试从 Django 的 views.py 文件中保存到名为 Blog 的 model。 This Blog model is itself linked to the custom user model that I created.此博客 model 本身链接到我创建的自定义用户 model。

How exactly do I do that?我到底该怎么做? Below are the以下是

  1. models.py file (custom user model is here) models.py 文件(自定义用户 model 在这里)
  2. models.py file (Blog model created here - in another Django app) models.py 文件(博客 model 在此处创建 - 在另一个 Django 应用程序中)
  3. views.py file where I try to save to the Blog model. How do I reference the user here?我尝试保存到博客 model 的 views.py 文件。如何在此处引用用户?

Please excuse the noob-ness of this question.请原谅这个问题的菜鸟性。 I'm just starting out:)我才刚刚开始:)

Inside models.py, I have a custom user model:在 models.py 中,我有一个自定义用户 model:

class UserExtended(AbstractUser):
    is_email_verified = models.BooleanField(default=False)
    company = models.CharField(null=True, blank=True, max_length=255)
    position = models.CharField(null=True, blank=True, max_length=255)
    email = models.EmailField(unique=True)

I also created a model for blog articles in models.py:我还在models.py中为博客文章创建了一个model:

class Blog(models.Model):
    title = models.CharField(max_length=200)
    blogSubject = models.CharField(null=True, blank=True, max_length=200)
    keywords = models.CharField(null=True, blank=True, max_length=300)
    audience = models.CharField(null=True, blank=True, max_length=200)
    # connection to custom user model
    profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

In views.py, I am trying to save to the Blog model:在 views.py 中,我试图保存到博客 model:

def saveBlogTopic(request, blogTopic):
    # create a Blog model instance
    blog = Blog.objects.create(
        title = blogTopic
        blogSubject = request.session['blogSubject']
        keywords = request.session['keywords']
        audience = request.session['audience']
        profile = request.user ### ???????? ###
    )

I have no idea how to reference the custom user model when saving to the Blog model, which itself is linked via ForeignKey to the custom user model. See last line of code in views.py.我不知道如何在保存到博客 model 时引用自定义用户 model,它本身通过 ForeignKey 链接到自定义用户 model。请参阅 views.py 中的最后一行代码。

Follow the steps按照步骤

1) Get the user id from the frontend 

2) data = request.data

3) user)id = data.get('user_id') or seeing your views may be request.session['user_id']

4) user_obj = User.objects.get(id=user_id) # pass this user_obj in profile

in code在代码中

blog = Blog.objects.create(
    title = blogTopic
    blogSubject = request.session['blogSubject']
    keywords = request.session['keywords']
    audience = request.session['audience']
    profile = user_obj
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM