Skip to content
Advertisement

How to resolve user into the field?

I’m creating a simple To Do app using Django 3.2, and I have stuck in a error which is: FieldError: Cannot resolve keyword 'user' into field. Choices are: content, created, email, id, name, user1, user1_id

This is models.py:

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

# Create your models here.


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

    user1 = models.ForeignKey(User, on_delete=CASCADE)
    
    def __str__(self):
        return self.content

forms.py

from django import forms
from django.forms import ModelForm, fields
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']

views.py

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

from demo.forms import CreateUserForm

from .models import *
from .models import __str__

# Create your views here.

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

    context = {'all_items': all_items}
    return render(request, 'html/home.html', context)

@login_required(login_url='/login')
def add_content(request):
    current_date = timezone.now()
    newItem = User(content=request.POST.get('content'))
    newItem.save()
    return redirect('/')

@login_required(login_url='/login')
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)

        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'))

            if user is not None:
                login(request, user)
                return redirect('/')
    
    context = {'form':form}

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

home.html

<div>
  <form class="felx" action="add_content/" method="POST">
    {% csrf_token %}
    <input class="form-control me-2" type="text" name="content" placeholder="Hey">
    <button id="add-btn" class="button" type="submit">Add</button>
  </form>

  <table>
    <thead>
      {% for all_item in all_items %}
        <tr>
          <td>{{ all_item.content }}</td>
        </tr>
      {% endfor %}
    </thead>
  </table>
  <a href="{% url 'demo:login' %}">Logout</a>

  {% if request.user.is_authenticated %}
    <p>Hello {{request.user}}</p>
  {% endif %}  
</div>

By far, any data that is added can be access by every account, but what i’m trying to do is that each user has his own data or tasks in this case. Would appreciate any idea! Thanks

Advertisement

Answer

i think your problem is here

@login_required(login_url='/login')
def home(request):
    user = request.user.pk
    
    all_items = User.objects.filter(user1_id=user).order_by("created") #new

    context = {'all_items': all_items}
    return render(request, 'html/home.html', context)

@login_required(login_url='/login')
def add_content(request):
    current_date = timezone.now()
    newItem = User(content=request.POST.get('content'),user1_id=request.user.pk)
    newItem.save()
    return redirect('/')

Advice:Please try to change the User in models.py to an other name because Django has by default a model called User.

Advertisement