Searchbar in Django not working: like query is not executed - django

I am developing an app in Django.
I have contents of a database displayed on my template glossario.html ad I want to implement a search bar to query the database and display only the query results.
So I have set up the toolbar in glossario.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav">
<a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a>
<div id="blocco_ricerca_semplice" class="search-container">
<form method="GET" action="{% url 'glossario' %}">
<input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}">
<button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button>
<button id="search_button" type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
In views.py have prepared a function to show only the query results:
def vista_ricerca_semplice(request):
template = "glossario.html"
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
context = {'selected_entries':selected_entries}
return render(request, template, context)
Note: Lemma_it is the field of my model I want to search and glossary_entry is the name of my model
To tell the truth I am looking for a command to do the query on all the model fields without typing
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query) | Q(field2__icontains=query) | Q(field3__icontains=query) ...)
In app/urls.py I have mapped the url of the search results:
from django.urls import path
from . import views
from .views import vista_ricerca_semplice
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
path('glossario', views.vista_ricerca_semplice, name="vista_ricerca_semplice"),
]
But it simply does not work.
If for example I type "attempt1", the console returns
[19/Sep/2019 18:08:00] "GET /glossario?q=attempt1 HTTP/1.1" 200 126941
And it updates the page but there is no query. The view does not change.
What's the error here?

I have been working on a similar project like yours but mine is a school management system.
I have implemented a search bar and it is working perfectly.
in views.py
def search_student(request):
student_list = DataStudent.objects.all()
student_filter = StudentFilter(request.GET, queryset=student_list)
return render(request, 'accounts/Students/Search/student_list.html', {'filter': student_filter})
and in urls.py
from django.conf.urls import url, include
from . import views
urlpatterns=[
url(r'^search_student', views.search_student, name="search_student")
]
in student_list.html
{% extends 'base.html' %}
{% block body %}
<div class="container" style="margin-left: 200px;font-size: 20px; padding: 0px 10px;">
{% load crispy_forms_tags %}
<form method="get">
<nav class="container nav navbar-expand navbar" >
<div style="color:black; font-size:160%">
<ul class="navbar-nav mr-auto" >
<li class="nav-item">
{{ filter.form.name|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.Class|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.stream|as_crispy_field }}
</li>
<li style="margin-left:5%"> <button type="submit" style="margin-top:60%;" class="btn btn-primary">Search </button>
</li>
</ul>
</div>
</nav>
</form>
<ul>
<div class="container" style="margin-left:2px; font-size:15px; padding:3px">
<table class="table table-hover" border="2">
<thead class="table-success">
<tr>
<td>Reg Number</td>
<td>Photo</td>
<td>Name</td>
<td>Class</td>
<td>Stream</td>
<td>Admision No</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{% for student in filter.qs %}
<tr>
<td>{{ student.admission_no}}</td>
<td>{% if student.Student_Photo %}<img src="{{ student.Student_Photo.url}}" width="50">{% endif %}</td>
<td>{{ student.name}}</td>
<td>{{ student.Class}}</td>
<td>{{ student.stream}}</td>
<td>{{ student.admission_no}}</td>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<td><a class="btn btn-primary a-btn-slide-text" href="{% url 'singlestudentdetails' pk=student.id %}"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
<span><strong>View</strong></span></a>
<a class="btn btn-danger a-btn-slide-text" href="{% url 'deletestudent' pk=student.id %}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span> </a>
</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
I hope this helps you fellow dev, happy coding

SOLVED
As pointed by ,the problem was that I had two views functions pointing at the same path (template).
This cannot be. One template/path cannot be pointed by more than one view function.
So I eliminated all the code related to my previous view function vista_ricerca_semplice
I solved my problem by changing code in urls.py and views.py like this:
In views.py:
def glossario(request):
query = request.GET.get('q')
template = "glossario.html"
# query executed
if query:
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
return render(request, template, {'all_entries':selected_entries})
# no query
else:
all_entries = glossary_entry.objects.all
return render(request, template, {'all_entries':all_entries})
In Urls.py
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
]

Related

Why am I getting a No Reverse Match error?

I'm trying to add delete functionality to my Django project, and I seem to be stuck in a loop whenever I try to access my health_hub_history page.
I keep getting the below error, which I know is to do with my urls.py setup, but I have commented it out- so I really don't know why I'm still getting the error!
Error message:
NoReverseMatch at /MyHealth/history
Reverse for 'delete_entry' not found. 'delete_entry' is not a valid view function or pattern name.
Views.py:
from django.shortcuts import render, get_object_or_404, redirect
from django.views import View, generic
from .models import HealthStats
from .forms import StatUpdateForm
def home(request):
return render(request, 'home.html')
def health_hub(request):
latest = HealthStats.objects.filter(user=request.user).latest('date')
context = {
"user": latest.user,
"weight": latest.weight,
"date": latest.date,
"run_distance": latest.run_distance,
"run_time": latest.run_time,
}
return render(request, 'health_hub.html', context)
def health_history(request):
serialized_stats = []
for stats in HealthStats.objects.filter(user=request.user):
serialized_stats.append({
"user": stats.user,
"weight": stats.weight,
"date": stats.date,
"run_distance": stats.run_distance,
"run_time": stats.run_time,
})
context = {
"stats": serialized_stats
}
return render(request, 'health_hub_history.html', context)
class UpdateHealth(View):
def get(self, request, *args, **kwargs):
stats = HealthStats
update_form = StatUpdateForm
context = {
'stats': stats,
'update_form': update_form,
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
}
return render(request, 'health_hub_update.html', context)
def post(self, request, *args, **kwargs):
stats = HealthStats
update_form = StatUpdateForm(data=request.POST)
context = {
'stats': stats,
'update_form': update_form,
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
'run time': stats.run_time,
'run distance': stats.run_distance
}
if update_form.is_valid():
update_form.save()
return render(request, 'health_hub_update.html', context)
# def delete_entry(request, entry_id):
# entry = get_object_or_404(HealthStats, id=entry_id)
# entry.delete()
# return redirect("health_hub_history")
urls.py:
from django.urls import path
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from . import views
app_name = 'HealthHub'
urlpatterns = [
path('', views.home, name='home'),
path('MyHealth/', views.health_hub, name='health_hub'),
path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
path('MyHealth/history', views.health_history, name='health_hub_history'),
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
# path('MyHealth/delete_entry/<id>', views.delete_entry, name='delete_entry'),
]
health_hub.html (button from which the error occurs):
<a href="{% url 'HealthHub:health_hub_history' %}"><button class="btn btn-primary btn-lg">View my Health
History</button></a>
health_hub_history.html:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>My Health History</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<table class="table table-striped table-hover table-bordered">
<tr>
<td>User:</td>
<td>Weight (lbs):</td>
<td>Date:</td>
<td>Run Distance (km):</td>
<td>Run Time (HH:MM:SS):</td>
<td>Action</td>
</tr>
{% for stat in stats %}
<tr>
<td>{{ stat.user }}</td>
<td>{{ stat.weight }} </td>
<td>{{ stat.date }}</td>
<td>{{ stat.run_distance }}</td>
<td>{{ stat.run_time }}</td>
<!-- Button trigger modal -->
<td>
<button type="button" class="btn btn-danger" data-bs-toggle="modal"
data-bs-target="#staticBackdrop">
Delete
</button>
</td>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Are you sure you want to delete
this entry?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
If you just need to amend something, try the edit button.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Cancel</button>
<!-- <a href="{% url 'delete_entry' entry_id %}"><button class="btn btn-danger">I'm -->
sure</button></a>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock content %}
I don't understand how it can all be commented out, but it's still trying to access the 'delete_entry' view?
Django does not ignore HTML comments, you need to use a special tag :
{% comment "Optional note" %}
<a href="{% url 'delete_entry' entry_id %}"><button class="btn btn-danger">
{% endcomment %}
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#comment

Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

Typeerror at/10 my_view() got an unexpected keyword argument 'pk'

I am getting a typeerror my_view() got an unexpected keyword argument 'pk'
views.py:
def my_view(request):
prod = get_object_or_404(Products, pk=1)
context = {
'prod': prod,
}
return render(request, 'title.html', context)
urls.py:
urlpatterns = [
path('search/', views.search, name='search'),
path('<int:pk>', views.my_view, name='my_view'),
path('', views.index),
]
My template when I make a search:
{% if results.products %}
{% for product in results.products %}
<div class="col-sm-{% column_width results.products %} pb-5">
<div class="card">
<div class="card-header bg-default" align="center">
<b>{{product.title}}</b>
</div>
<div class="card-body">
<a href="{% url 'my_view' product.id %}">{{
product.Author }}</a>
<p>{{ product.description|striptags }}</p>
<h6 class="btn btn-primary btn-large">
{{product.price}}</h6>
</div>
</div>
</div>
{% endfor %}
{% endif %}
My template to render when making a click on one of the search:
<div class="row">
<div class="col-md-12">
<div class="jumbotron">
<h2>{{ prod.title }}</h2>
<p>{{ prod.description }}</p>
<h6 class="btn btn-primary btn-large">{{judi.price}}</h6>
<h6 style="float: right;">{{judi.modified_date}}</h6>
</div>
</div>
</div>
You need to tell your
view that, a parameter named pk will come alongside the request.
You need to change:
def my_view(request):
with
def my_view(request, pk)
Furthermore, in your urls.py you need to give a path to your view, your current path lacks a path string. You need to replace:
path('<int:pk>', views.my_view, name='my_view') with:
path('my_view/<int:pk>', views.my_view, name='my_view')
Also in your template replace:
<a href="{% url 'my_view' product.id %}"> with
<a href="{% url 'my_view' pk=product.id %}">

Django Check boxes and progress bar

I'm new to Django a few week or two in to learning.
Django Ver 1.11
Python Ver 2.7
I'm making a Todo app in Django and I'm done with the application, but I want to add some extra features to it.
1. Sub tasks Checkbox that update the progress bar on the main page
2. and after the progress bar has reached 100% the status changes to done of the task.
I've made the login, registration, logout, adding new tasks and deleting the ones that are complete to my app so far.
here is the code
Models.
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class To_DO_Fun(models.Model):
Task_Name = models.CharField(max_length=20, default='')
Task_Text = models.TextField(max_length=45, default='')
Task_Done = models.BooleanField(default=False)
owner = models.ForeignKey(User)
def __str__(self):
return self.Task_Name + ' is ' + str(self.Task_Done) + ' by ' + str(self.owner)
forms
from .models import To_DO_Fun
from django import forms
class Form_todo(forms.ModelForm):
class Meta:
model = To_DO_Fun
fields = ['Task_Name','Task_Done']
class Form_Task(forms.ModelForm):
class Meta:
model = To_DO_Fun
exclude = ['Task_Name','Task_Done', 'owner']
fields = ['Task_Text']
views
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .models import To_DO_Fun #Class Name
from .forms import Form_todo, Form_Task #Form Name
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import JsonResponse
def HomeFun(request): #To view contents of the home page
return render(request, "ToDo_Files/HomePage.html")
#login_required(login_url='Login-Page')
def Display_Page(request):
if request.user.is_superuser:
all_items = To_DO_Fun.objects.all()
else:
all_items = To_DO_Fun.objects.filter(owner = request.user)
context = {'all_items':all_items}
if request.method == "POST":
obj_todo = To_DO_Fun()
obj_todo.Task_Name = request.POST.get('Task_Name')
obj_todo.owner_id = request.POST.get('owner_id')
obj_todo.save()
context = {'all_items': all_items}
messages.success(request, ("Good Luck."))
return render(request,'ToDo_Files/Display_Page.html',context )
else:
return render(request , 'ToDo_Files/Display_Page.html', context)
return render(request,'ToDo_Files/Display_Page.html',context )
#login_required(login_url='Login-Page')
def remove(request, To_DO_Fun_id):
if request.user.is_superuser:
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.delete()
messages.success(request, ('Task Deleted.'))
return redirect('Display-Page')
else:
return redirect('Logout-Page')
#login_required(login_url='Login-Page')
def data(request, To_DO_Fun_id):
if request.method == "POST":
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
form = Form_Task(request.POST, instance= item_all)
if form.is_valid():
form.save()
messages.success(request, ("Task Updated."))
return redirect('Display-Page')
else:
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
return render(request, 'ToDo_Files/details.html', {'item_all' : item_all})
return redirect('Display-Page')
#login_required(login_url='Login-Page')
def Done_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = True
item.save()
messages.success(request, ("Congratulations."))
return redirect('Display-Page')
#login_required
def Pen_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = False
item.save()
return redirect('Display-Page')
# def change_status(request, To_DO_Fun_id):
# Task_Done = request.GET.get('active', False)
# To_DO_Fun_id = request.GET.get('To_DO_Fun_id', False)
# # first you get your Job model
# task = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
# try:
# task.Task_Done = Task_Done
# task.save()
# return JsonResponse({"Success": True})
# except Exception as e:
# return JsonResponse({"success": False})
# return JsonResponse('Display-Page')
def Reg_Fun(request):
if request.method == "POST":
UserReg_Form = UserCreationForm(request.POST)
if UserReg_Form.is_valid():
UserReg_Form.save()
return redirect('Login-Page')
else:
messages.error(request, ('USERNAME TAKEN'))
return redirect('Reg-Page')
else:
UserReg_Form = UserCreationForm(request.POST)
return render(request, "ToDo_Files/reg.html", {'UserReg_Form':UserReg_Form})
return redirect('Login-Page')
html for main page
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task</title>
{% if messages %}
<br>
{% for msg in messages%}
<div class="alert alert-info alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<h4>☀</h4>
</button>
{{ msg }}
</div>
{% endfor %}
{% endif %}
<br>
<center><h5>WORK HARD <br> <i>{{ user.username }}</i></h5>
{% if all_items %}
<div>
<br>
{% if request.user.is_superuser %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Author </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
</table>
{% else %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endif %}
{% endblock %}
Base.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">
</head>
<style>
body {
background-color:#fffff7;
}
</style>
<body >
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href='{% url 'Display-Page' %}'>Django</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='{% url 'Home-Page' %}'>Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href='{% url 'Logout-Page' %}'>Logout<span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input type="hidden" name="owner_id" value="{{request.user.id}}">
<input class="form-control mr-sm-2" type="search"placeholder="Add TO-DO" aria-label="Search" name="Task_Name">
<button class="btn btn-success my-2 my-sm-0" type="submit" >Add TODO</button>
</form>
</div>
</nav>
<div class="container">
{% block asd %}
{% endblock %}
</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>
html for the subtask
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task Details</title>
{% if item_all %}
<form class="form-inline my-2 my-lg-0" method="POST" action="">
{% csrf_token %}
<br> <br>
<input class="form-control mr-sm-2" placeholder='Subtask' aria-label="Search" name="subTask">
<br>
<button class="btn btn-success my-2 my-sm-2" type="submit" >Add</button>
</form>
<br><br><br>
{% endif %}
{% endblock %}
urls
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^(?i)Home/', views.HomeFun, name='Home-Page'),
url(r'^(?i)Display/', views.Display_Page, name='Display-Page'),
url(r'^(?i)delete/(?P<To_DO_Fun_id>\d+)/$', views.remove, name='Del-Page'),
url(r'^(?i)details/(?P<To_DO_Fun_id>\d+)/$', views.data, name='Task-Data'),
url(r'^(?i)registraion/', views.Reg_Fun, name='Reg-Page'),
url(r'^(?i)login/', auth_views.LoginView.as_view(template_name='ToDo_Files/login.html'), name='Login-Page'),
url(r'^(?i)logout/', auth_views.LogoutView.as_view(template_name='ToDo_Files/logout.html'), name='Logout-Page'),
url(r'^(?i)Done/(?P<To_DO_Fun_id>\d+)/$', views.Done_status, name='Task-Done'),
url(r'^(?i)Pending/(?P<To_DO_Fun_id>\d+)/$', views.Pen_status, name='Task-Pen'),
]
I want to see a progress bar on the main page that shows how much % the task is done after comparing or getting input from the sub task checkbox.
also that I am able to add and remove new sub tasks in the sub tasks page where I can check the and uncheck any sub task.
Thank you in advance

How to setup the url redirect correctly after user registration and login in django?

So, I have setup django-registration's simple backend where the user registers and is immediately logged in to the display to my other django app fileuploader. Here is the urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
So after the user registers at accounts/register he/she is taken directly to the url upload/users/username
Here is the mysite.fileuplaod.urls that contains the url patterns for upload/:
from django.conf.urls import patterns, include, url
from mysite.fileupload.views import PictureCreateView, PictureDeleteView
from mysite.registration.backends.simple.views import RegistrationView
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from mysite.registration import signals
from mysite.registration.views import RegistrationView as BaseRegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
(r'$'+get_absolute_url(),PictureCreateView.as_view(), {}, 'upload-new'),
(r'^new/$', PictureCreateView.as_view(), {}, 'upload-new'),
(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
)
I want to setup the exact same view as upload/new for upload/users/username. r'$'+get_absolute_url() doesn't look like the right way to do it. I would really appreciate if someone could show me the right way to do this.
Also I would like to display the user name on the fileupload view page as something like "Welcome
{% extends "base.html" %}
{% load upload_tags %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Wordseer File Uploader</h1>
</div>
<form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-primary fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="file" multiple>
</span>
<button type="submit" class="btn btn-success start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete files</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5 fileupload-progress fade">
<div class="progress progress-success progres-striped active">
<div class="bar" style="width:0%"></div>
</div>
<div class="progress-extended"> </div>
</div>
</div>
<div class="fileupload-loading"></div>
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
<div class="fileupload-content">
<table class="files"></table>
<div class="fileupload-progressbar"></div>
</div>
<div>
{% if pictures %}
<h2>Already uploaded</h2>
<table class="table table-striped">
{% for picture in pictures %}
<tr>
<td class="preview">
<img src="{{ picture.file.url }}">
</td>
<td class="name">{{ picture.slug }}</td>
<td class="delete">
<a class="btn btn-danger" href="{% url 'upload-delete' picture.id %}">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
</td>
</tr>
{% endfor %}
</table>
<p>(Removing from this list is left as an exercise to the reader)</p>
{% endif %}
</div>
</div>
<!-- modal-gallery is the modal dialog used for the image gallery -->
<div id="modal-gallery" class="modal modal-gallery hide fade" data-filter=":odd">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"><div class="modal-image"></div></div>
<div class="modal-footer">
<a class="btn modal-download" target="_blank">
<i class="icon-download"></i>
<span>Download</span>
</a>
<a class="btn btn-success modal-play modal-slideshow" data-slideshow="5000">
<i class="icon-play icon-white"></i>
<span>Slideshow</span>
</a>
<a class="btn btn-info modal-prev">
<i class="icon-arrow-left icon-white"></i>
<span>Previous</span>
</a>
<a class="btn btn-primary modal-next">
<span>Next</span>
<i class="icon-arrow-right icon-white"></i>
</a>
</div>
</div>
{% upload_js %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.ui.widget.js"></script>
<script src="{{ STATIC_URL }}js/tmpl.min.js"></script>
<script src="{{ STATIC_URL }}js/load-image.min.js"></script>
<script src="{{ STATIC_URL }}js/canvas-to-blob.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap-image-gallery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.iframe-transport.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-fp.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-ui.js"></script>
<script src="{{ STATIC_URL }}js/locale.js"></script>
<script src="{{ STATIC_URL }}js/main.js"></script>
<script src="{{ STATIC_URL }}js/csrf.js"></script>
{% endblock %}
Thanks in advance.
To set url use something like:
url(r"^(?P<username>\w+)/$", PictureCreateView.as_view(), {}, 'upload-new')
and move it after 'new/' url.
To display user name in template use:
{{ request.user.username }} or {{ request.user.get_full_name }}