How to open a template as modal (detail user data) in user_list page (Django 1.11) - django

I have a user list page which works fine, and a user detail page which works fine too that I call from urls.py in seperate window. I want to open user detail in user list page in a modal window.
user_list.html
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr userid="{{user.id}}" class="edit_user">
<td>{{user.first_name}}</td>
<td>{{user.last_name }}</td>
<td>{{user.username }}</td>
<td>
<form class="right user_delete" method="POST" userid="{{user.id}}"
action="{% url 'user_delete' user.id%}">
{% csrf_token %}
<input class="btn btn-danger btn-sm" type="submit" value="DELETE">
</form>
</td>
<td><a type="button" class="btn btn-primary edit_user" href="{% url 'user_details' user.id %}" target="#edit_user"> UPDATE </a></td>
</tr>
{% empty %}
<tr>
<td>No Projects.</td>
</tr>
{% endfor %}
</tbody>
</table>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#registerformmodal"> New user </button>
user_detail.html
<h1>User Details</h1>
<p>{{ user_details.username }}</p>
<p>{{ user_details.first_name }}</p>
views.py
def user_details(request, userid):
user = User.objects.get(id=userid)
template = loader.get_template('vts/user_detail.html')
context = {
'user_details': user,
}
return HttpResponse (template.render(context, request))

The button data-target here,
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#registerformmodal"> New user </button>
looks for #registerformmodal which is neither associated with <form> nor <div>
You can add the id to your form as this
<form id="#registerformmodal" class="right user_delete" method="POST" userid="{{user.id}}">
...
</form>

Related

Django delete record using modal

I'm new in Django and i like to implement a Modal to delete records. The problem is a funny error in the modal form because is expecting a parameter. The modal link has this
but I don't know how add the right parameter.
This is my List in html
<table id="tablaAlmacenes" class="table table-bordered table-striped">
<thead>
<tr>
<th>Almacén</th>
<th>Detalles</th>
<th></th>
</tr>
</thead>
<tbody>
{% for almacen in object_list %}
<tr>
<td>{{ almacen.almacen }}</td>
<td>{{ almacen.descripcion }}</td>
<td>
<div>
Detalles
<a a href="" class="btn btn-link text-primary">Editar</a>
<a class="btn btn-link deleteAlmacen" data-id="{{ almacen.id}}"><span class="fas fa-trash text-danger"></a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Almacén</th>
<th>Detalles</th>
<th></th>
</tr>
</tfoot>
</table>
this is my url.py
urlpatterns = [
path('',include('polls.urls'),name='home'),
path('admin/', admin.site.urls),
# path('contact/',views.contact, name='contacto')
path('almacenes/', AlmacenesListView.as_view(), name='almacenes'),
path('almacenes/nuevo', AlmacenesCreateView.as_view(), name='crear_almacen'),
path('almacenes/<int:id>/remove/', AlmacenesDeleteView.as_view(), name='eliminar_almacen')
]
This is my views.py
class AlmacenesListView(ListView):
model = Almacen
template_name = 'pages/index.html'
success_message = "Bien!!!!"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de Almacenes"
print(reverse_lazy('almacenes'))
return context
class AlmacenesCreateView(SuccessMessageMixin, CreateView):
model = Almacen
form_class = AlmacenesForm
success_url = reverse_lazy('almacenes')
success_message = "Bien!!!!"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class AlmacenesDeleteView(DeleteView):
model = Almacen
success_url = reverse_lazy('almacenes')
and my modal code
<div class="modal fade" aria-modal="false" id="deleteAlmacenModal">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmación</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>¿Desea eliminar el Almacen?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<form action="{% url 'eliminar_almacen' (some parameter here but error) %}" method="POST">
{% csrf_token %}
<input type="hidden" name="id" id="almacen_id"/>
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
scrpt for modal
$(document).on('click','.deleteAlmacen',function(){
var id_almacen=$(this).attr('data-id');
$('#almacen_id').val(id_almacen);
$('#deleteAlmacenModal').modal('show');
});
So, if you are using bootstrap you don't need to trigger the modal with jquery but let bootstrap do the magic.
Your code should be something like that:
html:
<table id="tablaAlmacenes" class="table table-bordered table-striped">
<thead>
<tr>
<th>Almacén</th>
<th>Detalles</th>
<th></th>
</tr>
</thead>
<tbody>
{% for almacen in object_list %}
<tr>
<td>{{ almacen.almacen }}</td>
<td>{{ almacen.descripcion }}</td>
<td>
<div>
Detalles
<a a href="" class="btn btn-link text-primary">Editar</a>
<a class="btn btn-link" data-toggle="modal" data-target="#deleteAlmacenModal{{almacen.id}}""><span class="fas fa-trash text-danger"></a> <!-- data-toggle and data-target work in bootstrap4, in 5 is data-bs-target and data-bs-toggle -->
{% include 'yourtemplatefolder/modals/delete_almacen_modal.html' %} <!-- as best practice create another folder called modals and put there you modal.html files, as in this case and include them in your code -->
</div>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Almacén</th>
<th>Detalles</th>
<th></th>
</tr>
</tfoot>
</table>
Now, being the modal called inside the for loop, you can fix your modal like this:
delete_almacen_modal.html
<div class="modal fade" aria-modal="false" id="deleteAlmacenModal{{almacen.id}}">
<div class="modal-dialog modal-dialog-centered modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Confirmación</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>¿Desea eliminar el Almacen?</p>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<form action="{% url 'eliminar_almacen' pk=almacen.id %}" method="POST">
{% csrf_token %}
<input type="hidden" name="id" id="almacen_id"/>
<button type="submit" class="btn btn-danger">Eliminar</button>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
Now that should work.

how to update django databsae from html?

I want to only update the brand. So I want to see if I can get the post from the input.
print(request.POST.get('brand')) didn't print anything, but I can get print(request.POST.get('url')). Does anyone know why?
Here is my base.html code.
<form action="{% url 'script' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group w-75">
<input type="text" name="url" id="url" class="form-control">
</br>
<button type="submit" class="btn btn-success btn-lg btn-block">submit</button>
</div>
</br>
{% if alldata %}
<table class="table table-striped table-sm" id="">
<thead>
<tr>
<th>Price</th>
<th>Asin</th>
<th>Rank</th>
<th>Brand</th>
<th>CPU</th>
<th>Update</th>
</tr>
</thead>
<tbody>
{% for data in alldata %}
<tr>
<td>{{ data.price }}</td>
<td> {{ data.asin }} </td>
<td>{{ data.rank }}</td>
<td>
<div>
{{ data.brand }} <input type="text" name="brand" id="brand" value="{{data.brand}}">
<button type="submit">Update</button>
</div>
</td>
<td>cpu</td>
<td><button type="submit">Update</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</form>
To check All data in request.POST:
print(request.POST)
to print only one 'field'
print(request.POST['field'])

Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P<pk>\\d+)/delete/$']

I am getting:
django.urls.exceptions.NoReverseMatch: Reverse for 'company_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['company/(?P\d+)/delete/$']
and in my console it is showing:
- Failed to load resource: the server responded with a status of 500 (Internal Server Error)
My views.py
def company_delete(request,pk):
data = dict()
company = get_object_or_404(Company,pk=pk)
if request.method == "POST":
company.delete()
data['form_is_valid'] = True
companies = Company.objects.all()
data['company_list'] = render_to_string('company_list_2.html',{'companies': companies})
else:
context = {'company': company}
data['html_form'] = render_to_string('company_delete.html',context,request=request)
return JsonResponse(data)
my urls.py
urlpatterns = [
url(r'^company/$', views.company_list, name='company_list'),
url(r'^company/create/$', views.company_create, name='company_create'),
url(r'^company/(?P<pk>\d+)/update/$', views.company_update, name='company_update'),
url(r'^company/(?P<pk>\d+)/delete/$', views.company_delete, name='company_delete'),
]
my company_list_2.html
{% for c in companies %}
<tr>
<td>{{ c.name }}</td>
<td>{{ c.description }}</td>
<td>{{ c.website }}</td>
<td>{{ c.address }}</td>
<td>{{ c.phone }}</td>
<td>{{ c.email }}</td>
<td>{{ c.contact }}</td>
<td>
<button class="btn btn-warning show-form-update" data-url="{% url 'company_update' c.pk %}">
<span class="glyphicon glyphicon-pencil"></span>
Edit
</button>
</td>
<td>
<button class="btn btn-danger show-form-delete" data-url="{% url 'company_delete' c.pk %}">
<span class="glyphicon glyphicon-trash"></span>
Delete
</button>
</td>
</tr>
{% empty %}
<tr>
<td colspan="7" class="text-center bg-warning">No Company</td>
</tr>
{% endfor %}
my company_delete.html
{% load crispy_forms_tags %}
<form method="post" data-url="{% url 'company_delete' c.pk %}" class="delete-form">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title" >Delete Company</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="lead"> Are you sure you want to delete this company <strong>{{ c.name }}</strong></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Delete Company</button>
</div>
</form>
As say #Ivan Starostin just put company.pk instance c.pk in your url form
<form method="post" data-url="{% url 'company_delete' company.pk %}" class="delete-form">
...
</form>

How to create such a table with checkbox in django?

I want to have a table with a checkbox on each row with Django as shown in the image. My Django view.py, models.py and HTML file are mentioned below. How this can be done? Is there any built-in function in Django or what?
Table with check box
I have models file as:
class AppsDescription(db.Model):
aws_response = aws_list_conf_api_call()
CHOICES = [("yes", "YES"),
("no", "NO")]
OPTIONS = list()
for apps in aws_response:
OPTIONS.append(('{name1}'.format(name1=apps.lower()), '{name2}'.format(name2=apps)), )
name = db.CharField(max_length=256)
description = db.TextField()
plan_to_migrate = db.CharField(choices=CHOICES, max_length=256)
# app_names = MultiSelectField(choices=OPTIONS)
def __str__(self):
return self.name
My views.py as
def createapp(request):
# import ipdb; ipdb.set_trace()
form = DashboardForm()
if request.method == "POST":
form = DashboardForm(request.POST)
list_of_inputs = request.POST.getlist("inputs")
if form.is_valid:
form.save(commit=True)
return HttpResponseRedirect(reverse("aws:createapp"))
server = aws_server_list_conf()
return render(request, "createapp.html", {'server':server, 'form': form})
My html file as
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
<td><input type="checkbox" name="" value=""></td>
{% for k,v in apps.items %}
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>
I want to have a table with checkbox on each row with django as shown in the image.
Your HTML file needs to look like this:
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
{% for k,v in apps.items %}
<td><input type="checkbox" name="selected_options" value="v.id"></td>
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>

Call two different urls from a form or input submit button Django

I have a form in which I have a table.In table I have a record(title).Now along with title I have two buttons delete and edit.Now I want is that, if I click edit it calls separate url along with primary key going through it or if I click delete It calls separate url with primary key going through.
here's my code:
<form method="POST" action="{% url 'essay:delete_view' teacher.id %}">
<div class="page-header">
<div class="span4">
<h1>Manage Essays</h1>
</div>
</div>
<table>
<tr>
<th>Title</th>
<th>Edit</th>
<th>Delete</th>
</tr>
{% csrf_token %}
{% for uploadassignment in teacher.uploadassignment_set.all %}
<tr>
<th for="uploadassignment{{ forloop.counter }}">{{uploadassignment.id}}</th>
<th><input type="submit" id="Editthis" value="{{uploadassignmentEdit.id}}" class="btn btn-primary"/></th>
<th><input type="submit" id="uploadassignment{{ forloop.counter }}" value="{{uploadassignment.id}}" name="uploadassignment" class="btn btn-primary"/></th>
</tr>
{% endfor %}
</table>
</form>
I want this: one url is called by below (Edit button) with teacher.id
<th><input type="submit" id="Editthis" value="{{uploadassignmentEdit.id}}" class="btn btn-primary"/></th>
And another url is called when hit delete button with teacher id.
<th><input type="submit" id="uploadassignment{{ forloop.counter }}" value="{{uploadassignment.id}}" name="uploadassignment" class="btn btn-primary"/></th>
So far due to action ="{% url 'essay:delete_view' teacher.id %}" in form I can switch to only one url.Kindly help in my code so I can switch to different urls with teacher id when clicked on delete or edit button.
urls.py:
url(r'^$', views.Indexview.as_view(), name='index'),
url(r'^login/$',views.loginform.as_view(),name='login'),
url(r'^addfile/$',views.Addfile.as_view(),name='file'), #essay/addfile
url(r'^addfile/$',views.EditEssay.as_view(),name='eEssay'),
url(r'^text/$',views.writetext.as_view(),name='text'),
url(r'^about/$',views.aboutus.as_view(),name='about'),
url(r'^stdprofile/$',views.studentprofile.as_view(),name='stdprofile'),
url(r'^logout/$', LogoutView.as_view(), name='user_logout'),
url(r'^(?P<teacher_id>[0-9]+)/delEssay/$', views.delete_view, name='delete_view'),