Python Forum
Issue with Django only some links work?
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issue with Django only some links work?
#1
Hey guys I'm coming along in my project nicely and I'm on to a new issue:

I have all the listings printed on the index page when you log in. You can click on any of these to go to a page about the item. However, only some of these seem to work. About half of them give me this error:

Error:
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/g3 Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] auction [name='auction'] watchlist [name='watchlist'] categories [name='categories'] post/<str:title><str:description><int:price><str:category> [name='post'] The current path, post/g3, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I have no idea why. The others work perfectly and show me all the information about the item. Anyone know why? Below is my code:

views.py (just the relevant code):

def post(request, title, description, price, category):
    title = title
    description = description
    price = price
    category = category
    query = NewPost.objects.filter(title = title).first()
    p = {"title": query.title, "description": query.description, "price": query.price, "category": query.category}
    return render(request, "auctions/post.html", { "p": p})
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", 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:

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
index.html:

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

{% block body %}
    <h2>Active Listings</h2>
<ul>
{% for query in queries %}
            <li><a href="/post/{{query.title}}{{query.price}}">{{ query.title }} - {{ query.description }} - ${{ query.price }} - {{ query.category }}</a></li>
{% endfor %}  
{% endblock %}



</ul>
Reply
#2
no one?
Reply
#3
anyone?
Reply
#4
I was going to grab your code, play with it, and try to help (even though I've never used Django before), but I see references to files that you haven't provided (e.g. auctions/layout.html). Posts should have full instructions for reproducing the issue. I'd even prefer that you give us a Github repo to clone, since it seems like multiple files are necessary to reproduce the issue.

Besides that, 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. Your low rep probably contributes as well, to be blunt; I nearly skipped the post, and I if you have behavior similar to other threads, I'll probably take the same strategy as other readers have.
Reply
#5
Hint: compare the path in the URL for the case that's failing with the corresponding pattern in your urls.py. What do you notice? Really, the penultimate line in your error output should be making the problem quite obvious.
Reply
#6
I tried comparing it and I couldn't find it.
Reply
#7
What did you find when you compared the two? Saying "I couldn't find it" doesn't really give any details. Another hint: which URL pattern do you expect to be matched?

Edit: out of curiosity, what useful information did you glean from the error message?
Reply
#8
"What did you find when you compared the two? "

I found that some didn't work and some did - couldnt' find a link.

"which URL pattern do you expect to be matched?"

I'm not sure. The same as the ones that worked. There's no different code. Why would some work and others not?

"Edit: out of curiosity, what useful information did you glean from the error message?"

Nothing.

I'm now noticing the only ones that work at are the Monkey300 and Jackie546

However, on the page it only posts the first letter of the word. For monkey it just says Item: M - Price: $300, etc.

Before it was saying monkey.

I'm very confused could you just please tell me what the issue is so I can fix it? I've tried a million things for days.

You always assume I'm not putting any effort into it. I think about it a lot before I come to you.

views.py:
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


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):
    return render(request, "auctions/watchlist.html")

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

def post(request, title, description, price, category):
    title = title
    description = description
    price = price
    category = category
    query = NewPost.objects.filter(title = title).first()
    p = {"title": query.title, "description": query.description, "price": query.price, "category": query.category}
    return render(request, "auctions/post.html", { "p": p})
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", 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:

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
index.html:

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

{% block body %}
    <h2>Active Listings</h2>
<ul>
{% for query in queries %}
            <li><a href="/post/{{query.title}}{{query.price}}">{{ query.title }} - {{ query.description }} - ${{ query.price }} - {{ query.category }}</a></li>
{% endfor %}  
{% endblock %}



</ul>

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="{% url 'watchlist' %}">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>
post.html:

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

{% block body %}

    <h2>{{ p.title }} - Category: {{ p.category }}</h2>
    <p>Price = ${{ p.price }}</p> <div>
            {% if user.is_authenticated %}
                <p><a href="bid.html">Bid</p></a>
            {% else %}
                <p><a href="../login">Sign in to bid</p></a>
            {% endif %}
        </div>
    <p>Description: {{p.description}}</p>


    
{% endblock %}
Reply
#9
(Sep-12-2020, 08:07 PM)card51shor Wrote: "What did you find when you compared the two? "

I found that some didn't work and some did - couldnt' find a link.

This suggests that you actually didn't understand the question I asked :(.

Quote:"which URL pattern do you expect to be matched?"

I'm not sure. The same as the ones that worked. There's no different code. Why would some work and others not?

I'm trying to help you work that out, but you aren't helping to help you.

Quote:"Edit: out of curiosity, what useful information did you glean from the error message?"

Nothing.

There's your problem then. There are several pieces of useful information in it.

Quote:However, on the page it only posts the first letter of the word. For monkey it just says Item: M - Price: $300, etc.

I think this is related, so you need to work out why this is happening.

Quote:I've tried a million things for days.

You always assume I'm not putting any effort into it. I think about it a lot before I come to you.

You always say things like how you've tried "everything" or "a million things", yet we don't really get to hear what those things are. Also, maybe you're putting in effort, but perhaps not the right effort - thinking isn't the only thing to do when you encounter problems; you usually need to use your debugging tools to determine the cause.
Reply
#10
Well it would be impossible to list all the things I've done - I just tried a bunch of different methods but can't get it to work.

I can't figure out why only some are working.

The part where I said only the first letter is showing - I figured that out.

But still - more than half of the links don't work.

Some are because it's lowercase but even some of the ones that are have the first letter capitalized don't work.

I don't see why. Do you know? I have seen the error code. I don't see why some would have an error and others wouldn't.

Obviously it's not finding a match in the database when I do the query.

But why not?
Reply


Forum Jump:

User Panel Messages

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