Having trouble posting data to SQL Lite DB with Django

All other Source.Python topics and issues.
card51short
Junior Member
Posts: 1
Joined: Mon Sep 14, 2020 10:40 pm

Having trouble posting data to SQL Lite DB with Django

Postby card51short » Mon Sep 14, 2020 10:44 pm

Hey guys I'm having issues with Django using SQL lite. For some reason, my Watchlist model is not writing the data to the db. My User and NewPost models both work so I have done it before - I think I just messed up somewhere and I can't find where.

Can anyone give my code a look and find out why it's not adding the data to the db? I'm sure of it since I did a query for all and it came up with a None type. It doesn't give me an error or anything - it just redirects and doesn't add the data to the db.

Here is my code. let me know if you need any more info.

Thanks!

views.py ( relevant section is Watchlist):

Code: Select all

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:

Code: Select all

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")
]


models.py:

Code: Select all

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:

Code: Select all

{% 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:

Code: Select all

{% 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>

Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 13 guests