Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the current logged in user? Django models

I want to get the current logged in user to this CreateForm form. Below Im giving my current code, here request.user is not giving me error

ValueError at /create-post/
Cannot assign "<SimpleLazyObject: <User: testuser>>": "Post.author" must be a "Author" instance.

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Author(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   rate = models.IntegerField(default=0)
 
class Post(models.Model):
    title = models.CharField(max_length= 50)
    overview = models.TextField()
    body_text = RichTextUploadingField(null = True)
    time_upload = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(Author, related_name='author', on_delete=models.CASCADE)
    thumbnail = models.ImageField(upload_to = 'thumbnails')
    publish = models.BooleanField()
    categories = models.ManyToManyField(Categories)
    read = models.IntegerField(default=0)
    slug = models.SlugField(null= True, blank= True)

Forms.py

class CreateForm(ModelForm):
class Meta:
    model = Post
    fields = [
        'title',
        'overview',
        'body_text',
        'thumbnail',
        'categories',
        'publish',
    ]

Views.py

def create_post(request):
if request.method == 'POST':
    form = CreateForm(request.POST, request.FILES)
    if form.is_valid:
        post = form.save(commit=False)
        post.author= request.user
        post.save()
        return render(request, 'index.html')
else:
    form = CreateForm()
return render(request, 'create_post.html', {'form': form})

>Solution :

As the error says, post.author expects an Author object, not the user. You thus retrieve this with:

from django.contrib.auth.decorators import login_required

@login_required
def create_post(request):
    if request.method == 'POST':
        form = CreateForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author= request.user.author
            form.save()
            return render(request, 'index.html')
    else:
        form = CreateForm()
    return render(request, 'create_post.html', {'form': form})

You should also call the is_valid() method [Django-doc], so form.is_valid().


Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading