Home > Mobile >  How to make many to one field reference in Django 3.2?
How to make many to one field reference in Django 3.2?

Time:11-17

I'm working on a simple project in Django which is a To Do applictaion. Lately I have add to this project a login/register form, but despite that every user has their own account with their own credentials they access to the same data. I tried to use the models.ForeignKey(User, on_delete=models.CASACADE) but it shows me this error: django.core.exceptions.FieldError: Unsupported lookup 'user' for CharField or join on the field not permitted. To understand it better will show the full code:

models.py

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

# Create your models here.


class todo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return self.content

class User(models.Model):
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name

views.py

from django.http.response import HttpResponse
from django.shortcuts import render, redirect
from django.utils import timezone
from django.db.models import Count
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required

from django.http import HttpResponse
from django.contrib import messages

from .models import *
from .models import __str__
from .forms import CreateUserForm

# Create your views here.

@login_required(login_url='login/')
def home(request):
    user = request.user
    count_item = todo.objects.count()
    
    all_items = todo.objects.filter(content__user=user).order_by("created")

    context = {'all_items': all_items, 'count_item':count_item}

    return render(request, 'html/home.html', context)

@login_required(login_url='login/')
def add_todo(request):
    current_date = timezone.now()
    new_item= todo(content = request.POST["content"])
    new_item.save()
    return redirect('/')

@login_required(login_url='login/')
def delete_todo(request, todo_id):
    item_to_delete = todo.objects.get(id=todo_id)
    item_to_delete.delete()
    return redirect('/')


def login_user(request):

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(request, username=username, password=password)
        # print('USER:', user)

        if user is not None:
            login(request, user)
            return redirect('/') 
    return render(request, 'html/login.html')


def logoutUser(request):
    logout(request)
    return redirect('login/')

def register_user(request):
    form = CreateUserForm()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.save()

            user = authenticate(request, username=user.username, password=request.POST.get('password1'))

            print("USER:",user)

            if user is not None:
                login(request, user)
                return redirect('/')

    context = {'form':form}
    return render(request, 'html/register.html', context)

Don't know how to solve this and would be great if you can show me a way how to solve it. Thanks!

CodePudding user response:

Change

todo.objects.filter(content__user=user)

to

todo.objects.filter(user=user)
  • Related