Benedict K.
Benedict K.

Reputation: 37

Django no such column ForeignKey

I'm doing a Django project (kind of social network) and want to have a page where I can see all my posts, which I did.

I allways get the error: no such column: uploaded_by

in models.py

from django.db import models
from django.contrib.auth.models import User

class ContentItem(models.Model):
    upload_date = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=100, default='no title')
    description = models.CharField(max_length=400, default='no description')
    image = models.ImageField(upload_to='image_board/posts/', default='null')
    uploaded_by = models.ForeignKey(User, default='0')

    def __str__(self):
        return self.title

in views.py

def view_my_favorites(request):
    all_posts = ContentItem.objects.raw('SELECT * FROM image_board_ContentItem WHERE uploaded_by = request.user.username')
    template = loader.get_template('favorites.html')
    context = {
        'all_posts': all_posts,
    }
    return HttpResponse(template.render(context, request))

I want to get the user name of the user who is loged in, how can i whrite this in the sql query?

Thaks guys :)

Upvotes: 0

Views: 2341

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

Your actual issue is probably caused by neglecting to make and run migrations after adding the uploaded_by field.

But there are a huge number of other things wrong here.

Firstly, you are comparing the uploaded_by column with a non-existent column, request.user.username. You need to use the actual value of that variable.

Secondly, you are comparing a foreign key - uploaded_by - with a string, username. These will never match.

Thirdly, you are using a raw query. There is absolutely no need to do that here.

Your query is trivial to express in the Django query syntax. You should do:

all_posts = ContentItem.filter(uploaded_by=request.user)

or even simpler:

all_posts = request.user.contentitem_set.all()

Upvotes: 2

Related Questions