I create program stock management system by using Django. Page of Update_items that create for saving and updating. Program can running but when I will update new data it can't save and update data. It will redirect with same data. I'm not sure whatit's wrong. I am very new so please introduce me.
This is from views.py
from email import header
from multiprocessing import context
from urllib import request
from django.shortcuts import render,redirect
import stockmgmt
from .models import Stock
from .forms import StocksearchForm,StockCreateForm,StockUpdateForm
def home(request):
title = 'ยินดีต้อนรับเข้าสู่ระบบสต็อคสินค้าเซียงกง'
form = 'Welcome: This is the Home Page'
context = {
"title": title,
"test": form,
}
return render(request, "home.html",context)
def list_items(request):
title = 'รายการสินค้า'
form = StocksearchForm(request.POST or None)
queryset = Stock.objects.all()
context = {
"title": title,
"queryset": queryset,
"form":form
}
if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),item_name__icontains=form['item_name'].value(),id_product__icontains=form['id_product'].value(),shop_name__icontains=form['shop_name'].value())
context ={
"form":form,
"header": header,
"queryset": queryset,
}
return render(request, "list_items.html",context)
def add_items(request):
form=StockCreateForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/list_items')
context={
"form":form,
"title":"Add Item",
}
return render(request,"add_items.html",context)
def update_items(request, pk):
queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == ' POST':
form = StockUpdateForm (request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')
context = {
'form':form
}
return render(request, 'add_items.html', context)
This is list_items.html
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>รายการสินค้า</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/navbar-top-fixed/">
<!-- Bootstrap core CSS -->
<link href ="../../dist/css/bootstrap.min.css" rel ="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="navbar-top-fixed.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">สต็อคสินค้าร้านเซียงกง</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">หน้าแรก <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/list_items">รายการสินค้า</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/add_items">เพิ่มรายการสินค้า</a>
</li>
</ul>
<form class="form-inline mt-2 mt-md-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<main role="main" class="container">
<div class="jumbotron">
<h1>รายการสินค้า</h1>
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>
<table class='table'>
<thead>
<tr>
<th>รายการสินค้า</th>
<th>ประเภทสินค้า</th>
<th>ชื่อสินค้า</th>
<th>รหัสสินค้า</th>
<th>ชื่อร้าน</th>
<th>ราคา/หน่วย</th>
<th>จำนวนที่มีอยู่ในร้าน</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{instance.category}}</td>
<td>{{instance.item_name}}</td>
<td>{{instance.id_product}}</td>
<td>{{instance.shop_name}}</td>
<td>{{instance.price}}</td>
<td>{{instance.quantity}}</td>
</tr>
{% endfor %}
</table>
</div>
</main>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
This is url.py
"""djangoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from stockmgmt import views
urlpatterns = [
path('', views.home, name='home'),
path('list_items/', views.list_items, name='list_items'),
path('add_items/', views.add_items, name='add_items'),
path('update_items/<str:pk>/', views.update_items, name="update_items"),
path('admin/', admin.site.urls)
]
This is my error in command promopt
In forms.py
from django import forms
from .models import Stock
# Create your forms here
class StockForm(forms.Form):
class Meta:
model = Stock
# incase you want all fields
fields = '__all__'
In views.py
from .forms import StockForm
from .models import Stock
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib import messages
def update_entry(request, pk):
try:
queryset = Stock.objects.get(id=pk)
except Stock.DoesNotExist:
messages.error(request, "The request entry does not exist.")
# Redirect back some page incase of invalid pk
return HttpResponseRedirect(reverse("app2:listing"))
# Populate the form with old data
form = StockForm(instance=qs)
context = {"form": form}
# When method is post
if request.method == "POST":
# Populate the form with newly posted data
form = StockForm(request.POST, instance=qs)
# Checking data validity in form
if form.is_valid():
form.save()
# Always use HttpResponseRedirect after successfull post request
return HttpResponseRedirect(reverse("some-url-name"))
# When form is not valid re-render page
else:
messages.error(request, "Invalid form received.")
# Update form in context dictionary
context["form"] = form
return render(request, "update-stock.html", context)
# When method is not post
else:
return render(request, "update-stock.html", context)
In update-stock.html
<div class="container-fluid">
<!-- Loop over messages rendered from views -->
{% for message in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ message }}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
<form method="post" action="" class="row g-1">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary">
</form>
</div>
Related
I am having this error constantly - The view location_form.views.Insertrecord didn't return an HttpResponse object. It returned None instead.
I have tried indenting it in all ways possible. And i have a created another view in similar manner and that worked. Can someone tell where am i going wrong?
I want to store the data of this form in my database which is phpmyadmin (mysql)
views.py
from django.shortcuts import render
from .models import Location
from django.contrib import messages
# Create your views here.
def Insertrecord(request):
if request.method=='POST':
if request.POST.get('id') and request.POST.get('parent_id') and request.POST.get('name') and request.POST.get('status') and request.POST.get('added_by') and request.POST.get('updated_by') and request.POST.get('created_on') and request.POST.get('updated_on') :
saverecord=Location()
saverecord.id=request.POST.get('id')
saverecord.parent_id=request.POST.get('parent_id')
saverecord.name=request.POST.get('name')
saverecord.status=request.POST.get('status')
saverecord.added_by=request.POST.get('added_by')
saverecord.updated_by=request.POST.get('updated_by')
saverecord.created_on=request.POST.get('created_on')
saverecord.updated_on=request.POST.get('updated_on')
saverecord.save()
messages.success(request,"Record Saved Successfully..!")
return render(request, 'location.html')
else:
return render(request,'location.html')
location.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Location Registration Form</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<nav class="navbar bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">
<img src="https://img.freepik.com/premium-vector/customer-service-icon-vector-full-customer-care-service-hand-with-persons-vector-illustration_399089-2810.jpg?w=2000" alt="" width="30" height="24" class="d-inline-block align-text-top">
Location Registration Portal
</a>
</div>
</nav>
</head>
<body background="https://img.freepik.com/free-vector/hand-painted-watercolor-pastel-sky-background_23-2148902771.jpg?w=2000">
<br>
<h1 align="center">Location Registration Portal</h1>
<hr>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<div class="container-sm">
<form method = "POST">
{% csrf_token %}
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">Country</label>
<div class="col-sm-10">
<input type="text" name="name" class="form-control" id="inputEmail3"/>
</div>
</div>
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">Status</label>
<div class="col-sm-10">
<select class="form-select" aria-label="Default select example">
<option selected>--Select Status--</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
<br><br>
{% if messages %}
{% for message in messages %}
<h2 style="color: green;">{{message}}</h2>
{% endfor %}
{% endif %}
<div class="d-grid gap-2 col-6 mx-auto">
<input style="color: black;" type="submit" value="Submit"/>
</div>
<br>
</form></div>
</body>
</html>
urls. py
from django.contrib import admin
from django.urls import path
from customer_form import views as cview
from location_form import views as lview
urlpatterns = [
path('admin/', admin.site.urls),
# path('', admin.site.login, name='login'),
path('', cview.Insertrecord),
path('location/', lview.Insertrecord),
]
It is giving none because you are rendering template inside if statement.
def Insertrecord(request):
if request.method=='POST':
if request.POST.get('id') and request.POST.get('parent_id') and request.POST.get('name') and request.POST.get('status') and request.POST.get('added_by') and request.POST.get('updated_by') and request.POST.get('created_on') and request.POST.get('updated_on') :
saverecord=Location()
saverecord.id=request.POST.get('id')
saverecord.parent_id=request.POST.get('parent_id')
saverecord.name=request.POST.get('name')
saverecord.status=request.POST.get('status')
saverecord.added_by=request.POST.get('added_by')
saverecord.updated_by=request.POST.get('updated_by')
saverecord.created_on=request.POST.get('created_on')
saverecord.updated_on=request.POST.get('updated_on')
saverecord.save()
messages.success(request,"Record Saved Successfully..!")
return redirect('/home') #Add your route name here
return render(request, 'location.html')
I am trying to setup user login in the header, that way, the user can login/logout at any point in the web. However I must have missunderstood the Django tutorials. I am kind of a newbie with Django and I am not entirely sure of how to accomplish this, so any help is welcome.
I would like to clarify also, that I do not wish to redirect to another template. If possible, just reload the current page with the user already authenticated.
I tried 2 things:
add action="{% url 'sign_in' %}" in the header form
add action="{% url 'accounts_login' %}" in the header form
And neither seems to work.
My app name is 'web'
My project name is 'core'
# core/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', include('django.contrib.auth.urls')),
path('rest/', include('rest_framework.urls')),
path('', include('web.urls'))
]
# web/urls.py
from django.contrib.auth.views import LoginView
from django.urls import path
from . import views
urlpatterns = [
path('', views.base),
path('sign_in', views.sign_in, name='sign_in'),
path('accounts/login/', LoginView.as_view(template_name='base.html'), name='accounts_login')
]
# wev/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.contrib.auth import authenticate, login, logout
import requests
def base(request):
context = {
'user': request.user
}
return render(request, 'base.html', context)
def sign_in(request):
if request.POST:
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None and user.is_active:
print(user)
login(request, user)
return base(request)
return base(request)
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<header>
{% include 'header.html' %}
</header>
<main>
{% block main %}
Main content
{% endblock %}
</main>
<footer>
{% include 'footer.html' %}
</footer>
</body>
</html>
<!-- header.html -->
<!-- I am using bootstrap so i removed all extra divs an classes for readibility -->
<nav>
<ul>
<li>Home</li>
<li>Link</li>
</ul>
<div>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
<button>Sign out</button>
{% else %}
<button>Sign up</button>
<button>Sign in</button>
{% endif %}
</div>
</nav>
<div id="bootstrapModal">
<form method="POST" action="{% url 'accounts_login' %}">
{% csrf_token %}
{{ form.as_p }}
<div>
<h5>Sign in</h5>
<button type="button" aria-label="Close"></button>
</div>
<div>
<div>
<label>Email address</label>
<input name="email" type="email" placeholder="Email address">
</div>
<div >
<label>Password</label>
<input name="password type="password" placeholder="Password" ">
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
I am trying to create a simple to-do list app using Django. But face this error will running the server ValueError: Field 'id' expected a number but got 'index.html'.
models.py
from django.db import models
class List(models.Model):
item = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.item + '|' + str(self.completed)
urls.py
from . import views
urlpatterns = [
path("index",views.index, name="home"),
path("delete/<list_id>/", views.delete , name="delete"),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
# Create your views here.
def index(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request,('Items has been Added to List !!'))
return render(request,'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request,'index.html',{'all_items': all_items})
def delete(request, list_id):
item = List.objects.get(pk=list_id)
item.delete()
messages.success(request,('Item has been deleted'))
return redirect('index')
index.html
{% extends 'home.html' %}
{% block content %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if all_items %}
<table class="table table-bordered">
{% for things in all_items %}
<tr>
<td>{{ things.item }}</td>
<td><center>{{ things.completed }}</center></td>
<td><center>Delete</center></td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock content %}
home.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Home</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'home' %}">To-Do Lists</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Add Items" aria-label="Search" name="item">
<button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add To List</button>
</form>
</div>
</nav>
<br/>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
migration file 0001_intial.py
# Generated by Django 3.1.1 on 2020-09-27 05:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='List',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item', models.CharField(max_length=200)),
('completed', models.BooleanField(default=False)),
],
),
]
here is my note app page
Error that I getting
can anybody tell me where I made the mistake?
thanks in advance
Try replacing "{% url 'delete' things.id %}" with "{% url '<appname>:delete' things.id %}" the appname should be replaced by your app name. The same format works for me in Django 2.x.
I am brand new to AJAX requests and I am still learning Django, but I have a project where the user enters an Elasticsearch query and then we generate a downloadable document (report) for the user.
I have an AJAX request to continuously check on the existence of a file in my form.html file and it doesn't seem to be getting picked up at all. I can tell this because it isn't giving me any alerts and it's just automatically timing out on big requests after ~30 seconds.
I tried to write a temporary fix in my views.py that is basically attempting to do what the javascript in form.html is doing, but A) I feel like this isn't the best method to use in production, B) it doesn't feel like a good use of time to essentially re-invent the wheel, and C) I want the user to get some sort of alert or indication on their end that the report is in progress, and then when it's ready to download.
How can I modify my code to actually perform the AJAX request? Or why does it appear that the AJAX request isn't working?
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('form/', include('audit_tool.urls')),
path('report/', include('audit_tool.urls')),
path('check_progress/', views.check_progress, name='check_progress'),
# path('return_doc/', views.return_doc, name='return_doc'),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
audit_tool/urls.py
urlpatterns = [
path('', views.get_query, name='form'),
] + static(settings.STATIC_URL, document_root=settings.STAT)
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from docx import Document
import os
import threading
from .forms import QueryForm
from .models import *
#login_required
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.is_valid():
query = form.cleaned_data["query"]
fn = str(time.time()).replace(".", "_") + ".docx"
t = threading.Thread(target=generate_doc, args=(query, fn))
t.start()
return HttpResponseRedirect('/check_progress/')
else:
return HttpResponse("Your query does not appear to be valid. Please enter a valid query and try again.")
else:
form = QueryForm()
return render(request, 'icm_audit_tool/form_template.html', {'form': form})
#login_required
def check_progress(request):
"""
Returns whether document generation is complete or in progress
"""
fn = request["filename"]
file = "/app/created_files/" + fn
while not os.path.exists(file):
time.sleep(10)
if os.path.exists(file):
doc = Document(file)
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename={}'.format(fn)
doc.save(response)
return response
form.html
{% block javascript %}
<script>
var checkInterval = setInterval(isFileComplete, 10000); //10000 is 10 seconds
function isFileComplete() {
$.ajax({
url: '/check_progress/',
type: 'GET',
dataType: 'json',
success: function (data) {
if (data.file_created) {
alert("Your file is ready to download!");
clearInterval(checkInterval);
} else {
alert("Your report is still being created, please hold.");
checkInterval;
}
}
});
}
</script>
{% endblock %}
base_login.html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
<link rel="shortcut icon" href="link/to/company/iconicon.ico" type="image/vnd.microsoft.icon" />
<title>Audit Report Tool</title>
</head>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Dept</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="../">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../admin">Admin</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<hr class="mt-0 mb-4">
<img src="{% static "logo.png" %}" alt="Company Logo" align="left"></img>
<img src="{% static "logo.png" %}" alt="Dept Logo" align="right" width="140" height="140"></img>
<h1 align="center"><font size="6"> Audit Report Tool</font></h1>
</div>
</div>
</div>
<body>
<main>
{% block content %}
{% endblock %}
</main>
{% block javascript %}{% endblock %}
</body>
</html>
I've gotten the NoReverse Match error before and I got it to work with a blind guess. and page not found I've always been able to fix so I'm really not sure what is going on.
As far as I can tell everything should be working correctly, and I even compared this code to a previous project and it looks fine (I have been tinkering with it so it may not be exactly what I originally typed in).
base.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<title>Evverest</title>
<meta name"viewport" content="width=device-width, initial-scale=1">
<meta charset="uft-8">
<link rel="shortcut icon" href="/images/favicon.ico">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<nav>
<div class="container">
<a class="brand" href="{% url 'index' %}">Evverest</a>
<div class="navbar">
<a class="nav-link btn" href="{% url 'index' %}">Home</a>
{% if user.is_authenticated %}
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
<a class="nav-link" href="{% url 'users:user_logout' %}">Logout</a>
{% else %}
<a class="nav-link" href="{% url 'users:user_login' %}">Login</a>
<a class="nav-link" href="{% url 'users:register' %}">Register</a>
{% endif %}
</div>
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
app views.py
from django.shortcuts import render
from users.forms import UserForm,UserProfileForm
from users.models import UserProfileInfo
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('index'))
else:
return HttpResponse("Account now active")
else:
print("Login Unsuccessful")
return HttpResponse("Username and/or password are not correct")
else:
return render(request,'login.html',{})
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
print(user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,'register.html',{
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))
class HomeView(ListView):
model = UserProfileInfo
ordering = ['-join_date']
class UserProfileView(DetailView):
model = UserProfileInfo
class UserEditProfileView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = '/users_detail.html'
form_class = UserProfileForm
model = UserProfileInfo
Project urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from users import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.HomeView.as_view(),name='index'),
url(r'^users/',include('users.urls',namespace='users')),
]
app urls.py
from django.conf.urls import url
from users import views
app_name = 'users'
urlpatterns = [
url(r'^login/$',views.user_login,name='user_login'),
url(r'^logout/$',views.user_logout,name='user_logout',kwargs={'next_page':'/'}),
url(r'^register/$',views.register,name='register'),
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile'),
url(r'(?P<username>\d+)/edit$',views.UserEditProfileView.as_view(),name='user-profile-edit'),
]
file structure:
EDIT
Here is the traceback:
As you see in your urls.py:
url(r'(?P<username>\d+)/$',views.UserProfileView.as_view(),name='user-profile')
Your user-profile url takes one parameter, which is username. But in your template you do not pass it:
<a class="nav-link" href="{% url 'users:user-profile' %}">New Color Set</a>
So Django does not know which username to pass and this causes NoReverseMatch.
You just need to to pass the username to the url:
<a class="nav-link" href="{% url 'users:user-profile' username=user.username %}">New Color Set</a>
Figured it out: The problem come up because in another template (which I didn't post because I didn't realize it had any effect on this) I didn't put in the namespace users
Here is that other template:
{% extends "base.html" %}
{% block content %}
<div class="form-base">
<h2>Login</h2>
<form action="{% url 'users:user_login' %}" method="POST">
{% csrf_token %}
<label for="username">Username: </label>
<input type="text" class="login-input" name="username" placeholder="Enter Username" />
<label for="password">Password: </label>
<input type="password" class="login-input" name="password" />
<input type="submit" name="" value="Login" />
</form>
</div>
{% endblock %}
Thank you for the help everyone.