Python Forum

Full Version: RE: Data isn't writing to the Database with Django and SQL Lite
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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>
I didn't know you can't make multiple threads. It seems no one in Homework wants to answer my questions anymore.

Can someone please try to help? Thank you.
Quote:I didn't know you can't make multiple threads.
It doesn't sound like you've read the rules. Please do so before posting again, but also use common sense - besides my quote below, I think it's intuitive that people on a board are going to be annoyed if you post the same question again, meaning multiple people might independently trying to help.

Why do you think you're not getting answers?

(Sep-12-2020, 12:27 AM)micseydel Wrote: [ -> ]I suspect you can simplify your code more, and still reproduce the issue you're asking about; you should make it as easy as possible for us to help you, and every extra line you include works against that. When you find yourself bumping, and no one replying, there's usually something about your post making it difficult for us; one thing you can do is try to reproduce the issue with information from the post.
I'm not sure. Is there some information I didn't provide?

[quote='micseydel' pid='125755' dateline='1600125882']
Quote:I didn't know you can't make multiple threads.
It doesn't sound like you've read the rules. Please do so before posting again, but also use common sense - besides my quote below, I think it's intuitive that people on a board are going to be annoyed if you post the same question again, meaning multiple people might independently trying to help.

I posted it in a different section. Since people in Homework don't seem as eager to help.
STOP blaming other people; we provide help for free, and you're not entitled to it. I've repeated myself twice - you've posted too much code. Simplify your question, there should not be a single extra line on top of what you're asking about. Stop being lazy. I highly encourage a Github link, because I don't think I have enough patience with you to create multiple files to reproduce your issue.

This is your final chance before I advocate with other admins to ban you.
So did you want me to post all the code on GitHub...or to post just a little bit of the code?


I don't have it on GitHub.

Hey if you don't want to help - please move on. I never asked you to help.

I don't think your knowledge is that good anyways. You seem clueless.

Seems like you're the one being lazy and want the code presented to you exactly how you demand it.

I know you have the power right now but can u please try to be kind and help someone?

I get it- you have knowledge I don't have. You're a superior being in every way.

Do you want me to retype my question in Latin to you?

Just tell me what you want please I just want help with Python.
(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]So did you want me to post all the code on GitHub...or to post just a little bit of the code?
I wanted you to post exactly as much code is required to reproduce your problem. I don't want to see extra code unrelated to your problem. If it can be reproduced with a single file, that's what you should provide. This is in the rules, but in case you still didn't read them you should also be clear about what steps are required to reproduce your code - e.g. "have these files in this file structure, then run main.py from its containing directory". Provide any links that you think are relevant docs. Try not to assume anything about the knowledge of the person trying to help, if you want to appeal to more answerers.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]I don't have it on GitHub.
If you can reproduce with a single file, there's no need for Github. If it does require multiple files, I recommend you provide a Github link to make it easier for anyone trying to answer your question.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]Hey if you don't want to help - please move on. I never asked you to help.
(Sep-14-2020, 10:44 PM)card51shor, earlier Wrote: [ -> ]It seems no one in Homework wants to answer my questions anymore.

Can someone please try to help? Thank you.
I did want to help. My goal at this point is just to clarify how you can get help from others, and to point out some other issues here.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]I don't think your knowledge is that good anyways. You seem clueless.
I admitted that already.
(Sep-12-2020, 12:27 AM)micseydel, earlier Wrote: [ -> ]I was going to grab your code, play with it, and try to help (even though I've never used Django before)
I am clueless. If I were a Django expert, I would likely be able to answer your question without all this effort. I would just look at it, know the answer, and give it to you. Maybe I would know exactly where to look in the docs. But I'm not a Django expert, and no one else has helped.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]Seems like you're the one being lazy and want the code presented to you exactly how you demand it.
Oh yes I am being lazy. Am I not entitled to it? You seem to think you're entitled to my time, and I am not, which is backwards. I didn't demand anything - you asked for help, I told you what I needed, and you... well you know.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]I know you have the power right now but can u please try to be kind and help someone?
Had you followed my instructions, I wouldn't be writing this, I'd be providing you an answer. As such, this effort I've spent is I think sufficient. I don't feel obligated to provide more help than what has been spending a lot of effort helping you understand how to get help. I also have no reason to think that effort on my part in excess of this post will improve this situation in any way.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]I get it- you have knowledge I don't have. You're a superior being in every way.

Do you want me to retype my question in Latin to you?
This is ridiculous. There's no need for ridicule on a programming forum. If I see you speaking like this to anyone else on the forum, I'll ban you. Arguing with us is fine (though a waste of time), but be civil, there's no reason for us to tolerate mockery when we're trying to help you.

(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]Just tell me what you want please I just want help with Python.
I wanted you to stop being entitled, and put in effort so that those helping you can minimize theirs. I'm not asking anything of you beyond what I have of others, and have actually expected of myself - when I ask questions about code, I simplify the code before asking. I should also say, the process of simplification often helps the person asking the question to figure out the problem themselves. It's an invaluable skill, and one I'm grateful to the forum for instilling in me years ago.

You might find it ironic that I spent this much time replying to a post instead of providing you an answer. There is an irony there. However, I'm going to bookmark my reply for similar situations in the future, since these kinds of inefficient threads to happen occasionally. So it's not a total waste of time.
You never wanted to help. You came in here to scold me. Congratulations, you got your wish.

You can shame me and tell me how much better you are at coding than me.

Can someone else please try to help? Thanks.
(Sep-14-2020, 11:58 PM)card51shor Wrote: [ -> ]Seems like you're the one being lazy and want the code presented to you exactly how you demand it.
We do not get paid for helping people here. Right now i am posting this minutes before i have to leave for work instead of getting ready to go to work. We are all volunteers here.

To expedite the process of answering questions it is the responsibility of the person asking the question to post 1) enough information and 2) present it in a way that is easiest to get an answer. And if it is multiple files, it is universally known to use a Github repo to communicate the code online. Even when i can patch multiple files together when it is a well known 3rd party library for me, i do not because it is prone to errors. Whereas Github it is as you have exactly. Aside from it taking more time for me to answer everyones question when i have to patchwork their code together for them. Instead it is easier to say "make a github repo" to everyone.

I highly suggest reading this. It is a form of every web forum's etiquette rules in understanding how every forum operates and their expectations of people asking questions, etc. After i read this, it changed the way i ask questions on every forum from that point on. It gets me more answers. If you abide by this, you will get along with everyone here nicely, and other forums too. I suggest you do not skim it and take the time to read it all. It is a game changer.
metulburr it's amazing how fast you come in here to scold me.

Just like everyone else.

But none of you attempt to answer any of my questions ever.

But if I ask a question in the wrong way - you're all here with your superheroes capes on to attack me.

You guys don't care about helping anyone.

You want to lord your information over people.

Typical computer people. Acting like total jerks if I don't bow in servitude to you.

I get it - you don't want to help. You just want to attack me.

But maybe someone else out there does want to help.
Pages: 1 2