let me quickly explain what am I trying to do.
So I am making a small Django based Conference Management, where there can be multiple conferences, a single conference can have multiple talks and each talk will have a certain number of Speakers and Participants.
I am able to list the conferences and give the option to delete and edit a conference.
Problem:
I want an option where I click on a conference and it shows a list of talks for that conference.
but when I click on the conference it shows the following error.
NoReverseMatch at /Big Data/talks/
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Request Method: GET
Request URL: http://127.0.0.1:8000/Big%20Data/talks/
Django Version: 3.2.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Exception Location: E:\python\PYTHON and GIT\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: E:\python\PYTHON and GIT\python.exe
Python Version: 3.9.1
Python Path:
['D:\\DjangoConferenceManagementSystem\\mysite',
'E:\\python\\PYTHON and GIT\\python39.zip',
'E:\\python\\PYTHON and GIT\\DLLs',
'E:\\python\\PYTHON and GIT\\lib',
'E:\\python\\PYTHON and GIT',
'C:\\Users\\AKS\\AppData\\Roaming\\Python\\Python39\\site-packages',
'E:\\python\\PYTHON and GIT\\lib\\site-packages',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\pip-21.0.1-py3.9.egg',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32\\lib',
'E:\\python\\PYTHON and GIT\\lib\\site-packages\\Pythonwin']
Server time: Sun, 03 Oct 2021 15:47:10 +0000
I have included the following code to support the argument.
MODELS.PY
from django.db import models
from django.db.models.fields import CharField
from django.utils import timezone
# Create your models here.
class ConferenceModel(models.Model):
conference_title = models.TextField(null=False,primary_key=True)
conference_description = models.CharField(max_length=1000,null=False)
conference_start_date = models.DateField(null=False)
conference_end_date = models.DateField(null=False)
class TalkModel(models.Model):
talk_conference_title = models.ForeignKey(ConferenceModel,on_delete=models.CASCADE)
talk_title = models.TextField(null=False,primary_key=True)
talk_description = models.CharField(max_length=100,null=False)
talk_duration = models.DecimalField(max_digits=2,decimal_places=1)
talk_time = models.DateTimeField(null=False)
class SpeakerModal(models.Model):
speaker_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
speaker_username = models.CharField(max_length=25,null=False)
speaker_email = models.EmailField(max_length=100,primary_key=True,null=False)
class ParticipantModel(models.Model):
participant_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
participant_username = models.CharField(max_length=25,null=False)
participant_email = models.EmailField(max_length=100,primary_key=True,null=False)
URLS.PY
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('',views.conferenceView,name='conference'),
path('delete/<str:id>',views.conferencedelete,name='conferencedelete'),
path('<str:id>/edit',views.conferenceedit,name='conferenceedit'),
path('<str:id>/talks/',views.talkView,name='talks'),
path('admin/', admin.site.urls),
]
VIEWS.PY
from django.shortcuts import render
from django import forms
from django.shortcuts import render,HttpResponsePermanentRedirect,HttpResponse
from myapp.forms import ConferenceForm,TalkForm,SpeakerForm,ParticipantForm
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel
# Create your views here.
def conferenceView(request):
if request.method == 'POST':
conferenceform = ConferenceForm(request.POST)
if conferenceform.is_valid():
conferenceform.save()
conferenceform = ConferenceForm()
else:
conferenceform = ConferenceForm()
conference = ConferenceModel.objects.all()
return render(request,'myapp/conference.html',{'conference':conference,'conferenceform':conferenceform})
def conferenceedit(request,id):
if request.method == 'POST':
uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
requestconferencedetails = ConferenceForm(request.POST,instance=uniqueconferencetitle)
if requestconferencedetails.is_valid():
requestconferencedetails.save()
return HttpResponsePermanentRedirect('/')
else:
uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
requestconferencedetails = ConferenceForm(instance=uniqueconferencetitle)
return render(request,'myapp/conferenceedit.html',{'requestconferencedetails':requestconferencedetails})
def conferencedelete(request,id):
if request.method == 'POST':
conferencedelete = ConferenceModel.objects.get(pk=id)
conferencedelete.delete()
return HttpResponsePermanentRedirect('/')
def talkView(request,id):
talk = ConferenceModel.objects.get(pk=id)
conferencetalks = talk.talkmodel_set.all()
return render(request,'myapp/talks.html',{'conferencetalks':conferencetalks})
FORMS.PY
from django import forms
from django.db import models
from django.db.models import fields
from django.forms import widgets
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel
class ConferenceForm(forms.ModelForm):
class Meta:
model = ConferenceModel
fields = ['conference_title','conference_description','conference_start_date','conference_end_date']
widgets = {
'conference_title' : forms.TextInput(attrs={'class':'form-control '}),
'conference_description' : forms.TextInput(attrs={'class':'form-control'}),
'conference_start_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'}),
'conference_end_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'})
}
class TalkForm(forms.ModelForm):
class Meta:
model = TalkModel
fields = ['talk_conference_title','talk_title','talk_description','talk_duration','talk_time']
widgets = {
'talk_conference_title' : forms.HiddenInput,
'talk_title' : forms.TextInput(attrs={'class':'form-control '}),
'talk_description' : forms.TextInput(attrs={'class':'form-control '}),
'talk_duration' : forms.TextInput(attrs={'class':'form-control '}),
'talk_time' : forms.TextInput(attrs={'class':'form-control '}),
}
class SpeakerForm(forms.ModelForm):
class Meta:
model = SpeakerModal
fields = ['speaker_talk_title','speaker_username','speaker_email']
widgets = {
'speaker_talk_title' : forms.HiddenInput,
'speaker_username' : forms.TextInput(attrs={'class':'form-control '}),
'speaker_email' : forms.TextInput(attrs={'class':'form-control '})
}
class ParticipantForm(forms.ModelForm):
class Meta:
model = ParticipantModel
fields = ['participant_talk_title' , 'participant_username' , 'participant_email']
widgets = {
'participant_talk_title' : forms.HiddenInput,
'participant_username' : forms.TextInput(attrs={'class':'form-control '}),
'participant_email' : forms.TextInput(attrs={'class':'form-control '})
}
CONFERENCE.HTML
{% extends 'myapp/base.html' %}
{% block content %}
<div class="col-sm-5 container">
<h4 class="alert alert-info">Add a new conference</h4>
<form class="form-control" method="POST">
{% csrf_token %}
{{ conferenceform }}
<p></p>
<input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of confrences
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Options</th>
</tr>
</th>
{% for conferences in conference %}
<tr>
<th scope="col">{{conferences.conference_title}}</th>
<th scope="col">{{conferences.conference_description}}</th>
<th scope="col">{{conferences.conference_start_date}}</th>
<th scope="col">{{conferences.conference_end_date}}</th>
<td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
TALKS.HTML
{% extends 'myapp/base.html' %}
{% block content %}
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of Talks under this conference
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Talk Title</th>
<th scope="col">Talk Description</th>
<th scope="col">Talk Duration </th>
<th scope="col">Talk Time</th>
<th scope="col">Options</th>
</tr>
</th>
{% for talkss in conferencetalks %}
<tr>
<th scope="col">{{talkss.talk_title}}</th>
<th scope="col">{{talkss.talk_description}}</th>
<th scope="col">{{talkss.talk_duration}}</th>
<th scope="col">{{talkss.talk_time}}</th>
<!-- <td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
You loop through your queryset by naming the item conferences.
So to access the Id, since the URL expects an id. Look this path('<str:id>/edit',views.conferenceedit,name='conferenceedit'),.
You need to do this:
{% url 'conferenceedit' conferences.id %}
Or
{% url 'conferenceedit' conferences.pk %}
PS. Improve your path by updating '<str:id> to '<int:id>, since your model is integer.
urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('',views.conferenceView,name='conference'),
path('delete/<int:id>',views.conferencedelete,name='conferencedelete'),
path('<int:id>/edit',views.conferenceedit,name='conferenceedit'),
path('<int:id>/talks/',views.talkView,name='talks'),
path('admin/', admin.site.urls),
]
talks.html
{% extends 'myapp/base.html' %}
{% block content %}
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of Talks under this conference
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Talk Title</th>
<th scope="col">Talk Description</th>
<th scope="col">Talk Duration </th>
<th scope="col">Talk Time</th>
<th scope="col">Options</th>
</tr>
</th>
{% for talkss in conferencetalks %}
<tr>
<th scope="col">{{talkss.talk_title}}</th>
<th scope="col">{{talkss.talk_description}}</th>
<th scope="col">{{talkss.talk_duration}}</th>
<th scope="col">{{talkss.talk_time}}</th>
<!-- <td>
Edit
<form action="{% url 'conferencedelete' talkss.talk_conference_title_id %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
conference.html
{% extends 'myapp/base.html' %}
{% block content %}
<div class="col-sm-5 container">
<h4 class="alert alert-info">Add a new conference</h4>
<form class="form-control" method="POST">
{% csrf_token %}
{{ conferenceform }}
<p></p>
<input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
<h4 class="alert alert-info text-center">
Here is the list of confrences
</h4>
<table class="table table-hover">
<th class="thead-dark">
<tr>
<th scope="col">Title</th>
<th scope="col">Description</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Options</th>
</tr>
</th>
{% for conferences in conference %}
<tr>
<th scope="col">{{conferences.conference_title}}</th>
<th scope="col">{{conferences.conference_description}}</th>
<th scope="col">{{conferences.conference_start_date}}</th>
<th scope="col">{{conferences.conference_end_date}}</th>
<td>
Edit
<form action="{% url 'conferencedelete' conferences.pk %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock content %}
I got the problem was with my TALKS.HTML , I duplicated this HTML from the CONFERENCE.HTML and missed removing the following code.
<!-- <td>
Edit
<form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
{% csrf_token %}
<input type="submit" value="Delete" class="btn btn-danger btn-sm">
</form>
</td> -->
though I commented it , but it seems it wasn't commented , I removed it and now it works
Related
How do I pass the value from the inside of a for loop ( jinja2 ) to a bootstrap modal to display it in side the modal body?
here is my views.py file:
if request.method == 'GET':
driver = get_network_driver(device.napalm_driver)
with driver(device.IP_address, device.username, device.password) as device_conn:
interfaces = device_conn.get_interfaces()
context = {
'device': device,
'interfaces': interfaces,
}
return render(request, 'network/interface_list.html', context)
Please note that the the device_conn.get_interfaces() method returns a nested dictionary.
Here is the html template:
{% extends 'base/base.html' %}
{% block title %}iNet Interface List{% endblock %}
{% block content %}
<div class="section">
{% include 'network/include/interface_list_header.html' %}
{% if messages %}
{% for message in messages %}
{% if message.tags == 'success' %}<div class="alert alert-success" role="alert">
{{ message }}
</div>{% elif message.tags == 'error' %}<div class="alert alert-danger" role="alert">
{{ message }}
</div>{% endif %}
{% endfor %}
{% endif %}
<div class="card mx-auto shadow rounded">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col" style="text-align:center">Interface Name</th>
<th scope="col" style="text-align:center">Admin status</th>
<th scope="col" style="text-align:center">Protocol</th>
<th scope="col" style="text-align:center">Description</th>
<th scope="col" style="text-align:center">MAC Address</th>
<th scope="col" style="text-align:center">Last Flapped</th>
<th scope="col" style="text-align:center">Turn On/Off Port</th>
<th scope="col" style="text-align:center">Edit Description</th>
</tr>
</thead>
<tbody>
{% for interface_name, interface in interfaces.items %}
<tr>
<form action="{% url 'get_interfaces' device.id %}" method="post" id="{{ interface_name }}">
{% csrf_token %}
<input type="hidden" value="{{ interface_name }}" name="interface_name" />
<input type="hidden" value="{{ interface.is_enabled|yesno:'False,True' }}" name="enable" />
</form>
<td style="text-align:center">{{ interface_name }}</td>
<td style="text-align:center">{% if interface.is_enabled %}<i class="fa-solid fa-check text-success"></i>{% else %}<i class="fa-solid fa-xmark text-danger"></i>{% endif %}</td>
<td style="text-align:center">{% if interface.is_up %}<i class="fa-solid fa-check text-success"></i>{% else %}<i class="fa-solid fa-xmark text-danger"></i>{% endif %}</td>
<td style="text-align:center">{{ interface.description }} </td>
<td style="text-align:center">{{ interface.mac_address }}</td>
<td style="text-align:center">{{ interface.last_flapped }}</td>
<td style="text-align:center"><button class="btn common-button btn-primary" type="submit" form="{{ interface_name }}" value="Submit">{% if interface.is_enabled %}Turn Off{% else %}Turn On{% endif %}</button></td>
<!-- Modal Trigger button -->
<td style="text-align:center"><i class="fa-regular fa-clipboard"></i></td>
<!-- Modal container -->
<div class="modal fade viewModal" id="editDesc{{ interface_name }}" tabindex="-1" role="dialog" aria-labelledby="editDescLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 style="font-size: 20px;" class="modal-title" id="editDescLabel">View Console Output</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<textarea>{{ interface.description }}</textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
I wish to show the {{interface.description}} of the selected interface in the textarea so that I can edit it later. Any help would be appreciated.
My issue is - I am able to fetch {{interface.description}} outside the bootstrap modal, however I am unable to fetch the same thin inside the bootstrap modal. Eventhough both of them are inside the for loop.
I am trying to create a notification system with Django. I have an approval process in my project. A user approves a document according to his/her role. For example manager sent a document to the regional manager and wait for the approval. When the manager sends the document it goes to the regional manager's pending approvals list.
I created these tables. What I want to is When the user's pending approval is found, write it in the notification icon above. How can I do it?
Note: The notification bar in base.html
There is a picture for understanding clearly.
views.py
def approval(request):
current_user = request.user
rank_priority = RankPriority.objects.filter(rank = current_user.rank)
priority = rank_priority[0].priority
pend_list = ApprovalProcess.objects.filter(status = priority )
submit_list = ApprovalProcess.objects.filter(user_id = current_user)
context = {
'pend_list': pend_list,
'submit_list': submit_list
}
return render(request, 'approvals.html', context)
approvals.html
<div class="content">
<div class="page-inner">
<div class="page-header">
<h4 class="page-title">Approvals</h4>
</div>
<div class="row">
<div class="col-md">
<div class="card">
<div class="card-body">
<ul class="nav nav-pills nav-secondary" id="pills-tab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="pills-home-tab" data-toggle="pill" href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Pending Approvals</a>
</li>
<li class="nav-item">
<a class="nav-link" id="pills-profile-tab" data-toggle="pill" href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Submitted Approvals</a>
</li>
</ul>
<div class="tab-content mt-2 mb-3" id="pills-tabContent">
<div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">
<div class="card">
<div class="card-title">Pending Approvals</div>
<div class="card-body">
<table class="table table-head-bg-primary mt-4">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">User</th>
<th scope="col">Document ID</th>
<th scope="col">Beginning Date</th>
<th scope="col">End Date</th>
<th scope="col">Approve</th>
</tr>
</thead>
<tbody>
{% for pend in pend_list %}
<tr>
<td>1</td>
<td>{{ pend.last_approved.username }}</td>
<td>{{ pend.doc_id }}</td>
<td>{{ pend.begin_date }}</td>
<td>{{ pend.end_date }}</td>
<td>Approve</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">
<div class="card">
<div class="card-title">Submitted Approvals</div>
<div class="card-body">
<table class="table table-head-bg-primary mt-4">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">User</th>
<th scope="col">Document ID</th>
<th scope="col">Beginning Date</th>
<th scope="col">End Date</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{% for submit in submit_list %}
<tr>
<td>1</td>
<td>{{ submit.last_approved.username }}</td>
<td>{{ submit.doc_id }}</td>
<td>{{ submit.begin_date }}</td>
<td>{{ submit.end_date }}</td>
{% if submit.status > submit.highest_rank %}
<td>Approved</td>
{% else %}
<td>Waiting</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
The easiest way to do it is to create and register your custom context processor. For each request, your own template context processor will recalculate the state of notifications.
def approval_context_processor(request):
current_user = request.user
rank_priority = RankPriority.objects.filter(rank = current_user.rank)
priority = rank_priority[0].priority
pend_list = ApprovalProcess.objects.filter(status = priority )
submit_list = ApprovalProcess.objects.filter(user_id = current_user)
context = {
'pend_list': pend_list,
'submit_list': submit_list
}
return context
On your settings:
TEMPLATES = [
{
'# ...,
'OPTIONS': {
'context_processors': [
#...,
'approval_context_processor',
],
},
},
]
At this point, pend_list and submit_list will be available on all templates.
I have some data which I am passing from my views to my templates, whenever the else if the statement is true(that is the if the statement is false) the statement appears after my HTML header().
My main issue is that why is the else block not under the HTML heaader where I have put it in the code
templates.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Telephone</th>
<th>Country</th>
<th>Status</th>
<th>Image</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% if supplier %}
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
{% else %}
<h2>No supplier available</h2>
{% endif %}
</tbody>
</table>
You can not write a h2 in <tbody> or at least not directly. Yolu write this wrapped in a <tr> and <td>:
{% if suppliers %}
…
{% else %}
<tr><td colspan="7">No supplier available</td></tr>
{% endif %}
You also made a typo in the if statement: it is suppliers, not supplier.
Note: Django has a {% for … %}…{% empty %} template tag [Django-doc] that
can be used to render a message if the collection you iterate over is empty.
You can use the {% for … %}…{% empty %} django template tag. Example:
HTML
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.country}}</td>
<td class="process">Active</td>
<td>{{supplier.image.url}}</td>
<td>
<div class="table-data-feature">
<button class="item" data-toggle="tooltip" data-placement="top" title="Edit">
<i class="zmdi zmdi-edit"></i>
</button>
<button class="item" data-toggle="tooltip" data-placement="top" title="Delete">
<i class="zmdi zmdi-delete"></i>
</button>
</div>
</td>
</tr>
{% empty %}
<div><h2>No Suppliers Available</h2></div>
{% endfor %}
I am attempting to populate a table with a filtered set of data from my Manifests model using a url parameter.
I believe that the problem I am having is in the Views.py line
manifests = Manifests.objects.all().filter(reference=reference_id)
Models.py
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
description = models.CharField(max_length=1000)
count = models.IntegerField()
def __str__(self):
return self.description
Urls.py
url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'),
Views.py
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
except Orders.DoesNotExist:
pass
instance.reference = order
instance.save()
return redirect('add_manifest', reference_id=reference_id)
form = CreateManifestForm()
#manifests = Manifests.objects.all()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
template (add_manifest.html)
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference">Reference ID: </label><br>
<input type="text" value="{{ reference_id }}">
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description">Description: </label>
<br>
{{ form.description}}
</div>
</div>
<div class="column">
<label for="form.cases">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count">Count: </label>
<br>
{{ form.count }}
<br>
<br>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th></th>
<th style="width:10%;">Ref ID</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
</tr>
</thead>
<tbody>
{% for manifests in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifests.reference }}</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.description}}</td>
<td>{{ manifests.count}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" name="button" align="right">Subit Manifest</button>
</div>
</div>
I want the table to display only lines where the reference in the Manifests model = the reference_id in the URL. Currently it does not work as such, the table is just empty.
Change the for-loop variable name like this:
{% for manifest in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifest.reference }}</td>
<td>{{ manifest.cases }}</td>
<td>{{ manifest.description}}</td>
<td>{{ manifest.count}}</td>
</tr>
{% endfor %}
If there is any Manifest object for reference_id, then it will render them in template.
Update
Its possible that your form is not validating. So its a good idea to render form errors:
# view
def add_manifest(request, reference_id):
form = CreateManifestForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
instance.reference = order
except Orders.DoesNotExist:
pass
instance.save()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
And update template to show the errors in template as well:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I am trying to make a business card manager using django python but I don't why my business card is not being added. When I press the button "Add business Card", it goes to the BusinessCardListView but it is blank. I also want to know how to make the delete and update button work on the Business Card List. I think I have to add a primary key in the model but I don't know how to pass it correctly.
Views
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .models import BusinessInfo
class BusinessCardListView(generic.ListView):
model = BusinessInfo
template_name = 'manager/BusinessCardList.html'
context_object_name = 'all_business_cards'
def get_queryset(self):
return BusinessInfo.objects.all()
class BusinessCardCreate(CreateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardUpdate(UpdateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardDelete(DeleteView):
model = BusinessInfo
success_url = reverse_lazy('manager:index')
Add Business Card form
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:index' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
form_template
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.error }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
urls
from django.conf.urls import url
from . import views
app_name = 'manager'
urlpatterns = [
url(r'^$', views.BusinessCardListView.as_view(), name='index'),
url(r'business_card/add/$', views.BusinessCardCreate.as_view(), name='business_card-add'),
url(r'business_card/(?P<pk>[0-9]+)/edit/$', views.BusinessCardUpdate.as_view(), name='edit'),
url(r'business_card/(?P<pk>[0-9]+)/delete/$', views.BusinessCardDelete.as_view(), name='delete'),
]
models
from django.db import models
from django.core.urlresolvers import reverse
# Business Card Info
class BusinessInfo(models.Model):
card = models.FileField(default='Picture')
company_name = models.CharField(max_length=100000, primary_key=True)
website = models.CharField(max_length=100000)
representative_name = models.CharField(max_length=100000)
branch_address = models.CharField(max_length=100000)
job_title = models.CharField(max_length=10000)
email = models.EmailField()
phone_number = models.CharField(max_length=100000)
fax_number = models.CharField(max_length=100000)
cell_phone_number = models.CharField(max_length=100000)
def get_absolute_url(self):
return reverse('manager:index')
def __str__(self):
return self.company_name + ':' + self.representative_name
Business Card List
{% extends 'manager/Base.html' %}
{% block body %}
<style>
table, th, .Info {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
</style>
<table style="width:100%">
<tr>
<th>Business Card</th>
<th>Company Name</th>
<th>Representative Name</th>
<th>Job Title</th>
<th>Branch Address</th>
<th>Website</th>
<th>Phone Number</th>
<th>Cell Phone Number</th>
<th>Email</th>
<th>Fax Number</th>
</tr>
{% for businessinfo in all_business_cards %}
<tr>
<td class="Info">{{ businessinfo.card }}</td>
<td class="Info">{{ businessinfo.company_name }}</td>
<td class="Info">{{ businessinfo.representative_name }}</td>
<td class="Info">{{ businessinfo.job_title }}</td>
<td class="Info">{{ businessinfo.branch_address }}</td>
<td class="Info">{{ businessinfo.website }}</td>
<td class="Info">{{ contactinfo.phone_number }}</td>
<td class="Info">{{ contactinfo.cell_phone_number }}</td>
<td class="Info">{{ contactinfo.email }}</td>
<td class="Info">{{ contactinfo.fax_number }}</td>
<td>
<form action="{% url 'music:delete' %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="company_name" value="{{ company_name }}"/>
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
The action attribute in your form tag inside the Business Card Create form template is {% url 'manager:index' %} which points to the BuisinessCardListView thats why it is taking you to the list view on submit.
To achieve what you want it should point the CreateView url, like this:
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:business_card-add' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}