Yunter
Yunter

Reputation: 284

Django mapping user to model

On Django 1.9, I can create users through a user form view. When the user submits the form to create a profile, the submission can be seen in the admin under Users and is logged in fine. I want the user to only be able to view the models they have uploaded. As such, I need to map them together. However, the user model is not defined in models.py.

I have tried to link them in models.py in my model with:

user = models.ForeignKey(User)

However, this error is thrown:

NameError: name 'User' is not defined

Is this due to not having the user as a model in my models.py?

Request that creates user:

def post (self, request):
    form = self.form_class(request.POST)

    if form.is_valid():
        #creates an object from the form
        #being stored locally as of now
        user = form.save(commit=False)

        #cleaned data
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user.set_password(password)
        #Saved to the DB after it's shown in the correct format
        user.save()

models.py:

class Clean(models.Model):
    name = models.CharField(max_length=100, blank = False)
    #User doesn't see when creating model
    cv = models.TextField(max_length=10000, blank = True, null = True)
    cvfile = models.FileField(validators=[validate_file_extension])
    #User doesn't se when creating model
    cvscore = models.IntegerField()
    spellerrors = models.CharField(max_length=100, blank = False)

    *** user = models.ForeignKey(User) ***

Any resolution would be appreciated. I am using Python 3.6.4.

Upvotes: 1

Views: 2326

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477684

You are probably lacking an import statement, but nevertheless, referencing to User directly is typically not a good idea, since later, you might change the model you use for users.

Like the documentation says, you should use the AUTH_USER_MODEL settings:

from django.conf import settings
from django.db import models

class SomeModel(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL)

Upvotes: 5

Lemayzeur
Lemayzeur

Reputation: 8525

If you want to use the auth.User, you should import it from django

from django.contrib.auth.models import User

class Clean(models.Model):
    user = models.ForeignKey(User)

or, use it like a string from the Django app auth

user = models.ForeignKey('auth.User')

Upvotes: 2

Related Questions