Python Forum
RE: Data isn't writing to the Database with Django and SQL Lite
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
RE: Data isn't writing to the Database with Django and SQL Lite
#1
Hey guys I'm working on creating an Auction site and I've got a bunch of it done but I'm running into trouble with the Watchlist model I created.

When the user clicks on Add to Watchlist, it should add that data to the db for them to view when they go to their Watchlist.

However, when I click it, it doesn't do anything. No errors - but it also doesn't add to the database. I verified but doing a search of the table with Watchlist.objects.all(), I get a None value so it's not adding anything to the table. However, like I said - I'm getting no errors.

There must be something wrong with my code - I'm reviewing it but I haven't been able to find it. Anyone here who sees the problem? I'll post my code below. It should have all the relevant info you need.

Thanks!!!

urls.py:

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("auction", views.auction, name="auction"),
    path("watchlist/<str:user>", views.watchlist, name="watchlist"),
    path("categories", views.categories, name="categories"),
    path("post/<str:title><str:description><int:price><str:category>", views.post, name="post")
]
views.py (Watchlist is the relevant part):

from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from .models import User, NewPost, Watchlist


def index(request):
    query = NewPost.objects.all()
    print(NewPost.title)
    return render(request, "auctions/index.html", { "queries": query })


def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, "auctions/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "auctions/login.html")


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))


def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "auctions/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
        except IntegrityError:
            return render(request, "auctions/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("index"))
    else:
        return render(request, "auctions/register.html")

def auction(request):
    if request.method == "POST":
        title = request.POST.get("title").capitalize()
        description = request.POST.get("description").capitalize()
        price = request.POST.get("price")
        category = request.POST.get("category")
        new = NewPost.objects.create(title = title, description = description, price = price, category = category)
        new.save()
        return render(request, "auctions/auction.html")
    else:
        query = NewPost.objects.all()
        return render(request, "auctions/auction.html", { "queries": query })


def watchlist(request, user):
    if request.method == "POST":
        user = User.objects.filter(username = user).first()
        new = Watchlist.objects.create(user = user, title = title, description = description, price = price, category = category)
        new.save()
        return render(request, "auctions/watchlist.html")
    else:
        user = User.objects.filter(username = user).first()
        query = Watchlist.objects.filter(user = user).first()
        print(query)
        if(query != None):
            title = query.title
            description = query.description
            price = query.price
            category = query.category
            p = {"title": title, "description": description, "price": price, "category": category}
            return render(request, "auctions/index.html", { "p": p })
        else:
            return render(request, "auctions/watchlist.html")

def categories(request):
    return render(request, "auctions/categories.html")

def post(request, title, description, price, category):
    query = NewPost.objects.filter(title = title).first()
    if(query):
        title = query.title.capitalize()
        description = query.description.capitalize()
        price = query.price
        category = query.category.capitalize()
        p = {"title": title, "description": description, "price": price, "category": category}
        return render(request, "auctions/post.html", { "p": p })
    else:
        return render(request, "auctions/index.html")
urls.py:

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


class User(AbstractUser):
    pass

class NewPost(models.Model):
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=64)
    price = models.IntegerField()
    category = models.CharField(max_length=64)

class Bid():
    pass

class Comment():
    pass

class Watchlist(models.Model):
    user = models.CharField(max_length=64)
    title = models.CharField(max_length=64)
    description = models.CharField(max_length=64)
    price = models.IntegerField()
    category = models.CharField(max_length=64)
watchlist.html:

{% extends "auctions/layout.html" %}

{% block body %}
    <h2>Watch List</h2>

{% for query in queries %}
            <li><a href="/watchlist/{{query.user}}">{{ query.title }} - {{ query.description }} - ${{ query.price }} - {{ query.category }}</a></li>
{% endfor %}  
{% endblock %}
layout.html:

{% load static %}

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>{% block title %}Auctions{% endblock %}</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link href="{% static 'auctions/styles.css' %}" rel="stylesheet">
    </head>
    <body>
        <h1>Auctions</h1>
        <div>
            {% if user.is_authenticated %}
                Signed in as <strong>{{ user.username }}</strong>.
            {% else %}
                Not signed in.
            {% endif %}
        </div>
        <ul class="nav">
            <li class="nav-item">
                <a class="nav-link" href="{% url 'index' %}">Active Listings</a>
            </li>
            {% if user.is_authenticated %}
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'auction' %}">Create Auction</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/watchlist/{{ user.username }}">Watchlist</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'categories' %}">Search By Category</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'logout' %}">Log Out</a>
                </li>
            {% else %}
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'login' %}">Log In</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{% url 'register' %}">Register</a>
                </li>
            {% endif %}
        </ul>
        <hr>
        {% block body %}
        {% endblock %}
    </body>
</html>
Reply


Messages In This Thread
Data isn't writing to the Database with Django and SQL Lite - by card51shor - Sep-14-2020, 08:35 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sorting Data Returned From Database Timbo03 9 2,011 Feb-19-2023, 02:12 PM
Last Post: Larz60+
  Sentiment Analysis with NLTK Vader - Writing data in one row ulrich48155 1 4,124 May-15-2017, 06:36 AM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020