简体   繁体   中英

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. This Blog model is itself linked to the custom user model that I created.

How exactly do I do that? Below are the

  1. models.py file (custom user model is here)
  2. models.py file (Blog model created here - in another Django app)
  3. views.py file where I try to save to the Blog model. How do I reference the user here?

Please excuse the noob-ness of this question. I'm just starting out:)

Inside models.py, I have a custom user 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:

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:

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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