Home > other >  Why it doesn't show any data after I add it?
Why it doesn't show any data after I add it?

Time:11-22

Wokring on a simple To Do application using Django 3.2. In the moment I'm working on one to one relationship which every specific user has his own data(which are the tasks to do in this case) I did that by create a field at models.py user = models.ForeignKey(User, on_delete=CASCADE, null=True) The problem is that when I add a task in the home template it doesn't show up.

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 user_active(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)
    user = models.ForeignKey(User, on_delete=CASCADE, null=True)

    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 .models import user_active

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

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 'demo1:login' %}">Logout</a>

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

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 demo1.forms import CeateUserForm1

from .models import *
from .models import __str__

from .forms import CreateUserForm


def home(request):
    user = request.user
    
    all_items = user_active.objects.filter(user=user).order_by("created")
 
    context = {'all_items': all_items}

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

def add_content(request):
    user = request.user
    current_date = timezone.now()
    newItem = user_active(content=request.POST.get('content'))
    print('New item:', newItem)
    newItem.save()
    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)

        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)

Also to tested it, I print the newItem to see if it any data is added, and yes, it shows to terminal the new item, but not in the template. Not sure why is this error. Would appreciate any response or suggestions Thank you1

CodePudding user response:

In your add_content view you're not assigning the user to the user_active object, when you create a newItem.

def add_content(request):
    user = request.user
    current_date = timezone.now()

    #here you need to assign the user
    newItem = user_active(user=user, content=request.POST.get('content'))

    print('New item:', newItem)
    newItem.save()
    return redirect('/')
  • Related