0

This is my first time here, and I'm trying to develop an app for a personal project (journal app) using Django and Postgres. When I use the Shell method, I am able to create a new entry into a table defined in my Postgres DB. However, when using the browser method, it keeps retrieving the last entry in the DB instead of creating a new one.

I tried calling the entry_id in my views.py file and made sure to call the save() method to save a new entry. But instead, it keeps fetching the latest entry from the DB.

Any help and/or direction is highly appreciated by someone who's just learning.

Misael

VIEWS.PY


from django.shortcuts import render, redirect
from .models import Entry
from .forms import EntryForm
from django.urls import reverse

def entry_form(request):
    latest_entry = Entry.objects.latest('id')
    latest_entry_id = latest_entry.id if latest_entry else None

    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save()  # Save the form data to the database
            return redirect(reverse('journal:entry_success', kwargs={'latest_entry_id': entry.id}))  # Pass the latest_entry_id as a parameter
        else:
            print('Form errors:', form.errors)
    else:
        form = EntryForm()
    
    return render(request, 'journal/entry_form.html', {'form': form, 'latest_entry_id': latest_entry_id})

def entry_list(request):
    entries = Entry.objects.all()
    return render(request, 'journal/entry_list.html', {'entries': entries})

def entry_success(request, latest_entry_id):
    print('Entry success view called')
    try:
        latest_entry = Entry.objects.get(id=latest_entry_id)
        print('Latest Entry ID:', latest_entry.id)
    except Entry.DoesNotExist:
        print('Entry does not exist')
        latest_entry = None
    return render(request, 'journal/entry_success.html', {'entry': latest_entry})

MODELS


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

class Entry(models.Model):
    auth_user_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column='auth_user_id', default=1)
    mood = models.CharField(max_length=100)
    sleep_quality = models.IntegerField()
    heart_rate_min = models.IntegerField()
    heart_rate_max = models.IntegerField()
    exercise_duration = models.IntegerField()
    screen_time_hours = models.IntegerField()
    screen_time_minutes = models.IntegerField()
    sleep_duration = models.DecimalField(max_digits=5, decimal_places=2)
    energy = models.IntegerField()
    notes = models.TextField()

    def save(self, *args, **kwargs):
        self.screen_time = self.screen_time_hours + self.screen_time_minutes / 60.0
        super().save(*args, **kwargs)

    class Meta:
        managed = True
        db_table = 'journal_entry'

HTML entry form

<!DOCTYPE html>
<html>
<head>
    <title>Journal Entry Form</title>
    <style>
        .form-group {
            margin-bottom: 10px;
        }

        .form-group label {
            display: block;
        }

        .form-group .field-wrapper {
            display: flex;
            align-items: center;
        }

        .form-group .help-text {
            margin-left: 10px;
            font-size: 12px;
            color: #999;
        }
    </style>
</head>
<body>
    <h1>Journal Entry Form</h1>
    <form method="post" action="{% url 'journal:entry_success' latest_entry_id=latest_entry_id %}">
        {% csrf_token %}
        <div class="form-group">
            <label for="{{ form.mood.id_for_label }}">{{ form.mood.label }}</label>
            {{ form.mood }}
            <span class="help-text">{{ form.mood.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.sleep_duration.id_for_label }}">{{ form.sleep_duration.label }}</label>
            {{ form.sleep_duration }}
            <span class="help-text">{{ form.sleep_duration.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.sleep_quality.id_for_label }}">{{ form.sleep_quality.label }}</label>
            {{ form.sleep_quality }}
            <span class="help-text">{{ form.sleep_quality.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.heart_rate_min.id_for_label }}">{{ form.heart_rate_min.label }}</label>
            {{ form.heart_rate_min }}
            <span class="help-text">{{ form.heart_rate_min.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.heart_rate_max.id_for_label }}">{{ form.heart_rate_max.label }}</label>
            {{ form.heart_rate_max }}
            <span class="help-text">{{ form.heart_rate_max.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.exercise_duration.id_for_label }}">{{ form.exercise_duration.label }}</label>
            {{ form.exercise_duration }}
            <span class="help-text">{{ form.exercise_duration.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.screen_time_hours.id_for_label }}">{{ form.screen_time_hours.label }}</label>
            {{ form.screen_time_hours }}
        </div>
        <div class="form-group">
            <label for="{{ form.screen_time_minutes.id_for_label }}">{{ form.screen_time_minutes.label }}</label>
            {{ form.screen_time_minutes }}
        </div>
        <div class="form-group">
            <label for="{{ form.energy.id_for_label }}">{{ form.energy.label }}</label>
            {{ form.energy }}
            <span class="help-text">{{ form.energy.help_text }}</span>
        </div>
        <div class="form-group">
            <label for="{{ form.notes.id_for_label }}">{{ form.notes.label }}</label>
            {{ form.notes }}
            <span class="help-text">{{ form.notes.help_text }}</span>
        </div>
        <input type="hidden" name="latest_entry_id" value="{{ latest_entry_id }}">
        <button type="submit">Submit</button>
    </form>    
</body>
</html>

1 Answers1

0

Hi Misael: the option in Django ORM is .last() .

So you should do:

latest_entry_id = Entry.objects.last().id

EDIT: You should pick it up just after the save, in the POST. Id is automatically generated upon database commit, and not instantiated in any manner when the form is loaded. Hence, if you query the "last id" before the commit and load it in a variable, is not going to be the last after the commit, but the variable will remain with the previously loaded value:

def entry_form(request):
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save()  # Save the form data to the database
            latest_entry_id = Entry.objects.last().id
            return redirect(reverse('journal:entry_success', id=Latetst_entry_id))  # Pass the latest_entry_id as a parameter
        else:
            print('Form errors:', form.errors)
    else:
        form = EntryForm()

Else, there is no need to use kwargs, since only the id integer is going to be loaded in the Latest_entry_id variable.

Hope it helps!

  • Thank you Paulo. I did modify it as such: from django.shortcuts import render, redirect from .forms import EntryForm from .models import Entry def entry_form(request): latest_entry_id = Entry.objects.last().id if Entry.objects.last() else None print('Latest Entry ID:', latest_entry_id) # Debug print I still get the ID fetch of the entry that already exists in the database. I am trying to add debugging print messages, but still don't get too far with it. – Misael Lopez Jul 08 '23 at 00:09
  • Yes, now I see it. I´ll edit my answer, since there It will be easier to read the code. – Paulo Mielnichuk Jul 08 '23 at 01:19