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 %}
Related
I am trying to perform update operation in Django. Actually what I need when I click the update button of an existing entry it should load in an another form with the data and once I change the details need to save it. I have referred a video with same requirement but that code is not working for me. Please help me I am really stuck.
These are my files and code details.
forms.py
from .models import Building
from django.forms import ModelForm
class BuildingForm(ModelForm):
class Meta:
model = Building
fields = '__all__'
models.py
from django.db import models
# Create your models here.
class BuildingType(models.Model):
building_type = models.CharField(max_length=100)
def __str__(self):
return self.building_type
class Building(models.Model):
building_name = models.CharField(max_length=50)
name_of_owner = models.CharField(max_length=50)
building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE)
number_of_rooms = models.IntegerField()
mobile_number = models.IntegerField()
current_lease_period = models.DateField()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='home'),
path('buildings', views.Buildings, name='buildings'),
path('rooms', views.Rooms, name='rooms'),
path('customers', views.Customers, name='customers'),
path('receipts', views.Receipts, name='receipts'),
path('new_building', views.NewBuilding, name='new_building'),
path('update/<int:bldg_id>', views.UpdateBuilding, name='update_building'),
path('delete_building/<int:bldg_id>', views.DeleteBuilding, name='delete_building'),
path('new_room', views.NewRoom, name='new_room'),
path('new_customer', views.NewCustomer, name='new_customer'),
path('new_receipt', views.NewReceipt, name='new_receipt'),
path('login', views.Login, name='login'),
path('signup', views.Signup, name='signup'),
]
views.py
from django.shortcuts import render, redirect
from .forms import BuildingForm
from webapp.models import Building, BuildingType
# Create your views here.
def Home(request):
return render(request, 'index.html', {'context':'null'})
def Buildings(request):
building_list = Building.objects.all()
return render(request, 'buildings.html', {'context': 'Buildings', 'building_list': building_list})
def Rooms(request):
return render(request, 'rooms.html', {'context':'Rooms'})
def Customers(request):
return render(request, 'customers.html', {'context':'Customers'})
def Receipts(request):
return render(request, 'receipts.html', {'context':'Receipts'})
# New Building
def NewBuilding(request):
bldg_type = BuildingType.objects.all()
form = BuildingForm()
if request.method == "POST":
form = BuildingForm(request.POST)
if form.is_valid():
form.save()
return redirect('buildings')
else:
form = BuildingForm()
return render(request, 'new_building.html', {'context':'NewBuilding', 'bldg_type':bldg_type, 'form':form})
**
# Update Building
def UpdateBuilding(request, bldg_id):
bldg_type = BuildingType.objects.all()
Update_building = Building.objects.get(id=bldg_id)
form = BuildingForm(instance=Update_building)
return render(request, 'update_building.html', {'context':'UpdateBuilding', 'bldg_type':bldg_type, 'form':form})**
# Delete Building
def DeleteBuilding(request, bldg_id):
building_list = Building.objects.all()
if request.method == "POST":
bldg=Building.objects.get(id=bldg_id)
bldg.delete()
return redirect('buildings')
return render(request, 'buildings.html', {'building_list':building_list})
def NewRoom(request):
return render(request, 'new_room.html', {'context':'NewRoom'})
def NewCustomer(request):
return render(request, 'new_customer.html', {'context':'NewCustomer'})
def NewReceipt(request):
return render(request, 'new_receipt.html', {'context':'NewReceipt'})
def Login(request):
return render(request, 'login.html')
def Signup(request):
return render(request, 'signup.html')
buildings.html
{% extends 'base.html' %}
{% load static %}
{% block title %} Buildings {% endblock %}
{% block content %}
<!-- Buildings -->
<div class="container-fluid">
<div class="sub-box">
<div class="row">
<div class="col-sm-12 mt-3">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 search-col">
<form action="" class="d-flex gap-3">
<input type="text" class="form-control form-control-lg" id="search" >
<button type="submit" class="btn btn-lg search">Search</button>
</form>
</div>
</div>
</div>
<div class="col-sm-12 mt-3 table-responsive">
<table class="table table-hover table-bordered text-center ">
<thead>
<tr>
<th scope="col" class="align-middle">Building Name</th>
<th scope="col" class="align-middle">Building Type</th>
<th scope="col" class="align-middle">Rooms</th>
<th scope="col" class="align-middle">Owner Name</th>
<th scope="col" class="align-middle">Mobile Number</th>
<th scope="col" class="align-middle">Lease Period</th>
<th scope="col" class="align-middle">Actions</th>
</tr>
</thead>
<tbody>
{% for list in building_list %}
<tr>
<td class="align-middle">{{list.building_name}}</td>
<td class="align-middle">{{list.building_type}}</td>
<td class="align-middle">{{list.number_of_rooms}}</td>
<td class="align-middle">{{list.name_of_owner}}</td>
<td class="align-middle">{{list.mobile_number}}</td>
<td class="align-middle">{{list.current_lease_period}}</td>
<td class="d-flex justify-content-between gap-3">
Update
<form action="{% url 'delete_building' list.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete" class="btn delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
update_building.html
{% extends 'base.html' %}
{% load static %}
{% block title %} UpdateBuilding {% endblock %}
{% block content %}
<!-- Update Building -->
<div class="container-fluid">
<div class="main-box">
<div class="row d-flex align-items-center justify-content-center">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex align-items-start flex-column">
<h1 class="mb-4 mt-2">Update Building</h1>
<form method="post" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="building_name" class="form-label">building name</label>
<input type="text" class="form-control form-control-lg" id="building_name" name="building_name" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="name_of_owner" class="form-label">name of owner</label>
<input type="text" class="form-control form-control-lg" id="name_of_owner" name="name_of_owner" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<label for="building_type" class="form-label">building type</label>
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="building_type" name="building_type">
<option selected>select</option>
{% for type in bldg_type %}
<option value="{{type.id}}">{{type.building_type}}</option>
{% endfor%}
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="mobile_number" class="form-label">mobile number</label>
<input type="number" class="form-control form-control-lg" id="mobile_number" name="mobile_number">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="number_of_rooms" class="form-label">number of rooms</label>
<input type="number" class="form-control form-control-lg" id="number_of_rooms" name="number_of_rooms">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-5">
<label for="current_lease_period" class="form-label">current lease period</label>
<input type="date" class="form-control form-control-lg" id="current_lease_period" name="current_lease_period">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<button type="submit" class="btn btn-lg mb-4">Update</button>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<button type="reset" class="btn btn-lg">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
UPDATE(enter image description here I have added backslash to the url and new error comes out )
My idea is to have Teachers and Students and I want my Teachers to have the ability to edit quizzes for the students for some reason when I try to acces the QuizUpdateView via other ListView it gives me 404 Not Found screenshot
So I want to edit my quiz with this view:
class QuizUpdateView(views.UpdateView):
model = Quiz
fields = ('name', 'subject', )
context_object_name = 'quiz'
template_name = 'classroom/quiz_update.html'
def get_context_data(self, **kwargs):
kwargs['questions'] =
self.get_object().questions.annotate(answers_count=Count('answers'))
return super().get_context_data(**kwargs)
def get_queryset(self):
return self.request.user.quizzes.all()
def get_success_url(self):
return reverse_lazy('quizzes')
I have int:pk in my urls.py
urlpatterns = (
path('register', RegisterView.as_view(), name='register'),
path('register/student', StudentRegisterView.as_view(), name='register student'),
path('register/register', TeacherRegisterView.as_view(), name='register teacher'),
path('login', LoginView.as_view(), name='login'),
path('logout', LogoutView.as_view(), name='logout'),
path('quizzes', QuizListView.as_view(), name='quizzes'),
path('quiz/create', QuizCreateView.as_view(), name='create quiz'),
path('quiz/update/<int:pk>', QuizUpdateView.as_view(), name='update quiz'),
)
I have the quiz.pk in templates as well(I tried with quiz.id, same result)
{% extends 'base.html' %}
{% block page_content %}
{% include 'classroom/student_header.html' with active='new' %}
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Quiz</th>
<th>Subject</th>
<th>Length</th>
<th></th>
</tr>
</thead>
<tbody>
{% for quiz in quizzes %}
<tr>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.subject.get_html_badge }}</td>
<td class="align-middle"> questions</td>
<td class="text-right">
{% if request.user.type == 'Student' %}
Start quiz
{% elif request.user.type == 'Teacher' %}
<a href="{% url 'update quiz' quiz.pk %}" class="btn btn-
warning">Edit quiz</a>
Delete quiz
{% endif %}
</td>
</tr>
{% empty %}
<tr>
<td class="bg-light text-center font-italic" colspan="4">No exam
matching your interests right
now.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Here is the model
class Quiz(models.Model):
owner = models.ForeignKey(UniversityUser, on_delete=models.CASCADE,
related_name='quizzes')
name = models.CharField(max_length=QUIZ_NAME_MAX_LENGTH, unique=True)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE,
related_name='quizzes')
def __str__(self):
return self.name
And here is the template I am using for the UpdateView:
{% extends 'base.html' %}
{% block page_content %}
<h2 class="mb-3">
{{ quiz.name }}
<a href="{% url 'teachers:quiz_results' quiz.pk %}" class="btn btn-primary float-
right">View results</a>
</h2>
<div class="row mb-3">
<div class="col-md-6 col-sm-8 col-12">
<form method="post" action="{% url 'update quiz' quiz.pk %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success">Save changes</button>
<a href="{% url 'quizzes' %}" class="btn btn-outline-secondary"
role="button">Nevermind</a>
Delete
</form>
</div>
</div>
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-10">
<strong>Questions</strong>
</div>
<div class="col-2">
<strong>Answers</strong>
</div>
</div>
</div>
<div class="list-group list-group-flush list-group-formset">
{% for question in questions %}
<div class="list-group-item">
<div class="row">
<div class="col-10">
{{ question.text }}
</div>
<div class="col-2">
{{ question.answers_count }}
</div>
</div>
</div>
{% empty %}
<div class="list-group-item text-center">
<p class="text-muted font-italic mb-0">You haven't created any
questions yet. Go ahead and add the first question.</p>
</div>
{% endfor %}
</div>
<div class="card-footer">
Add question
</div>
</div>
{% endblock %}
If you have any ideas why this is happening please leave a comment thanks! :)
i'm not sure but is that class you inherit from is right?
try to import :
from django.views.generic.edit import UpdatView
class QuizUpdateView(UpdateView):
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys?
views.py
#login_required(login_url="admin-login")
#user_passes_test(check_role_admin)
def colorProductMap_edit(request, id):
instance = ColorProductMapping.objects.get(color_p_map_id=id)
print(instance.color_id)
form = ColorProductMapForm(instance=instance)
if request.method == 'POST':
form = ColorProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/colorProductMap')
else:
form = ColorProductMapForm(instance=instance)
return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance})
I properly partnered and connected with the following in my urls.py.
urls.py
path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"),
forms.py
class ColorProductMapForm(forms.ModelForm):
class Meta:
model = ColorProductMapping
fields = ['color_id', 'prod_id']
models.py
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
colorProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Color Product Map{% endblock %}
{% block main %}
<h1>
<center>Color Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{%if colorProductMap_show%}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Color Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Color Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-color-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit" class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Color Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Color Product Mapping Id</th>
<th>Product ID</th>
<th>Color ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in colorProductMap_show %}
<tr>
<td>{{x.color_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.color_id}}</td>
<td><a href="{% url 'admin-color-product-map-edit' x.color_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-color-product-map-delete' x.color_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if colorProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in colorProductMap_show.paginator.page_range %}
{% if colorProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if colorProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{%endif%}
{% if instance %}
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
What am I doing wrong? I think I have followed every advice I could find, but yeah it still gives me the error. Any help is appreciated. Thank you very much!
You write your form tag as:
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
After observing your template and view it appears that you are using the same template for multiple views and this is causing confusion. As I note in the comment there is no x in the context for this view (In the other one you loop over a variable which doesn't exist in this view to get this). After looking a bit more one notices that by this {% url 'admin-color-product-map-edit' x.color_p_map_id %} you want to point to the current url itself. If a forms action is to the same url the best thing to do is forego the action attribute completely (If there is no action attribute the request would be to the same url as the page user is in):
<form method="POST" enctype="multipart/form-data">
Thanks all to guide me, I have found my mistake.
In the html template, as shown below
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
Here I am using x.color_p_map_id where x is not any iterable object so the error I was getting.
Now I have made a change and used instance instead of x in above url and now its working fine.
<form action="{% url 'admin-color-product-map-edit' instance.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
I have a model 'Manifests' and a form 'CreateManifestForm'. The user enters multiple lines of data in the CreateManifestForm and these are saved to the Manifest model (on a line by line basis, not using ajax or anything).
There are 3 fields of concern in the model and form - 'Cases', 'FOB', 'CNF'. Both FOB and CNF are dollar amounts, so I'll use one as an example. How could I take the user entered FOB price, multiply it by cases and then store that number? Additionally, when the user enters another line, how could I do the same and then add that to the original number so I can get a total value.
MODELS.PY
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
product_name = models.ForeignKey(Products, default=None, blank=True, null=True)
count = models.IntegerField()
CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)
FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)
def __str__(self):
return self.description
VIEWS.PY
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()
form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)})
reference = request.POST.get('reference')
manifests = Manifests.objects.all().filter(reference=reference)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
ADD_MANIFEST.HTML
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.FOB }}
</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 id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</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>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifests.reference }}</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
I would like to see a read-only field or something of that nature (I guess in the template) which shows the total for this particular manifest the user is creating. Any thoughts?
You can annotate the manifest objects with a computed field
from django.db.models import F, ExpressionWrapper
manifests = Manifests.objects.filter(
reference=reference
).annotate(
total=ExpressionWrapper(F('cases') * F('CNF'), output_field=DecimalField())
)
Then in your template you can reference manifest.total.
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 %}