Bootstrap Modal submit button not working with DeleteView in Django 2.2 - django

I am learning Django 2.2 and using a little bit of Bootstrap 4 to help with the front end. I have a Model created which stores some user information like first name and last name. I have created a DeleteView class which is supposed to delete entries from the database using the ID. Everything works fine as is. But if I try to implement the DeleteView class using a Bootstrap modal window, nothing seems to happen even if I click the submit button. I am not sure what I am doing wrong. I read in another thread here in Stackoverflow that we need to include the button inside a form which I have done too. But it still doesn't delete the entry. Below is all the code required.
Note - I have placed the Delete button inside the contacts_view.html file. The contacts_delete.html file is exactly the same. My idea is to provide the user to not just view the details but also update or even delete the specific entry. When I click on the Delete button, the modal pop up window appears. But when I click on the 'Confirm' button, the entry does not get deleted as required.
Please let me know how to proceed with this.
contacts_view.html / contacts_delete.html
{% extends 'base.html' %}
{% block content %}
<div class="container" style="width: 500px">
<div>
<div class="list-group" style="color: black">
<a class="list-group-item list-group-item-action my-1" style="background-color: wheat">
<div class="row">
<div class="col-4">
First Name
</div>
<div class="col-8">
{{ object.first_name }}
</div>
</div>
</a>
<a class="list-group-item list-group-item-action my-1" style="background-color: wheat">
<div class="row">
<div class="col-4">
last Name
</div>
<div class="col-8">
{{ object.last_name }}
</div>
</div>
</a>
</div>
</div>
<div class="border-top text-center my-4 pt-3">
<a class="btn btn-outline-danger ml-2" href="{% url 'contacts-delete' object.id %}" type="submit" data-toggle="modal" data-target="#myModal">Delete</a>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="background-color: whitesmoke; color: dimgray">
<div class="modal-header">
<h4 class="modal-title">Delete Contact</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body text-left">
form
<p>Do you really want to delete {{ object.first_name }} {{ object.last_name }}?</p>
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'contacts-delete' object.id %}">
{% csrf_token %}
<button class="btn btn-outline-warning ml-2" type="submit">Update</button>
<button type="button" class="btn btn-outline-danger" href="{% url 'contacts-delete' object.id %}" data-dismiss="modal">Delete</button>
</form>
<a type="button" class="btn btn-outline-secondary" href="{% url 'contacts-view' object.id %}" data-dismiss="modal">Cancel</a>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
views.py
from .models import Contact
from django.urls import reverse_lazy
from django.shortcuts import reverse
from django.views.generic import DetailView, DeleteView
class ContactDetailView(DetailView):
model = Contact
template_name = 'contacts/contacts_view.html'
class ContactDeleteView(DeleteView):
model = Contact
template_name = 'contacts_update.html'
success_url = reverse_lazy('contacts-browse')
models.py
from django.db import models
from django.contrib.auth.models import User
class Contact(models.Model):
added_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35, blank=True, default='')
def __str__(self):
return f"{self.first_name} {self.last_name}"
urls.py
from django.urls import path
from .views import ContactDetailView, ContactDeleteView
urlpatterns = [
path('view/<int:pk>/', ContactDetailView.as_view(), name='contacts-view'),
path('view/<int:pk>/delete/', ContactDeleteView.as_view(), name='contacts-delete'),
]

Related

django show pagination links First , Previous , Next , Last on edit page that uses UpdateView or DetailView

I am using django 3.2 along with datatables and bootstrap 5. it shows pagination correctly using datatables. I want to show Links/buttons like First, previous,Next and Last on edit productstatus form using datatables pagination or django pagination django.core.paginator whose details as shown below
class ProductStatus(models.Model):
ProductID = models.CharField(max_length=512, verbose_name="ProductID", null=False, blank=False)
Description = models.CharField(max_length=512, verbose_name="Description", null=True, blank=True)
CreateDate = models.DateTimeField(verbose_name=_("CreateDate"), blank=True)
modificationtime = models.DateTimeField(verbose_name="modificationtime", null=True, blank=True, )
...
def __str__(self):
return self.ProductID
def get_absolute_url(self):
return reverse('productdetail', args=[str(self.id)])
urls.py has entry as shown below
path('editproduct/int:pk/edit/', EditProductView.as_view(), name='editproduct'),
views.py contains following code
class EditProductView(LoginRequiredMixin, UpdateView):
model = ProductStatus
template_name = 'editproduct.html'
form_class = EditProductStatusForm
login_url = 'login'
def form_valid(self, form):
editedproduct = form.save(commit=False)
editedproduct.modificationtime = timezone.now()
editedproduct.save()
# self.object = editedproduct
return super().form_valid(form)
Forms.py contains
class EditProductStatusForm(forms.ModelForm):
class Meta:
model = ProductStatus
editproduct.html looks as shown below
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<!-- show 4 links in bootstrap navigation bar -->
<nav class="navbar navbar-expand-lg navbar-light">
<div class="container-fluid ">
<div class="nav navbar-left">
<ul class="nav navbar-nav">
<li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">« First</a></li>
<li><a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">‹ Previous</a></li>
</ul>
</div>
<div class="nav navbar-right">
<ul class="nav navbar-nav">
<li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">Next ›</a></li>
<li> <a class="btn btn-info btn-sm" style="padding-left:0px;margin-left:10px" href="#" role="button">Last »</a></li>
</ul>
</div>
</div>
</nav>
<h3 class="text-center">Change Product Status </h3>
<form class="form-inline" role="form">
<div class="row">
<div class="col">
<div class="input-group mb-3">
<span class="input-group-text" style="background-color: #ffffff" id="labelFor-Product ID">Product ID </span>
<input type="text" style="background-color: #ffffff" class="form-control" value="{{ object.ProductID }}" readonly>
</div>
</div>
</form>
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-6">
{{ form.Description| as_crispy_field }}
</div>
</div>
<br>
<button type="submit" class="btn btn-success">Save</button>
</form>
{% endblock content %}
editproduct url is invoked from other datatables using list page as . this page allows sorting by click on table header
I need to show pagination on editproduct page with 4 links/buttons First,Previous,Next and Last or datatables like pagination so that user dont have go back to product list page and then click on edit icon to open editproduct status page and user can go to first product, Previous product, next product or last product from edit product status page itself.
I am aware of datatables pagination that requires passing productstatus_list and using table but not sure how to use datatables pagination or django.core.paginator on this editproduct status page or on product details page that uses DetailView where only product id is passed and available as shown above. what change/update is needed in above code to show desired pagination on the edit productstatus page.

How to implement change password modal form?

EDIT 14/07/2021
Reading this blog post (https://simpleisbetterthancomplex.com/tips/2016/08/04/django-tip-9-password-change-form.html) I understand how to prevent user logout (update_session_auth_hash(self.request, self.object) added to form_valid function) and I am very close to the solution using attempt #2
BUT
there still have "grey" screen after user pasword successfully changed and user have to click on screen to make it disappeared...
EDIT 14/07/2021
I quite closeto the solution following this tutorial https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/
Neverthless it is not working correctly.
attempt #1: get_success_url
I override get_success_url funtion of PasswordChangeView to redirectto index page and use SuccessMessageMixin to confirm password change. Password is correctly changed but somthig is going wrong with return (see capture below)
attemp #2: form_valid
I've tried another way overriding form_valid function that return JsonObject. Password is also changed but screen stay as modal was still opened. When I click on screen, "grey" diappeared but if I refresh page (F5) i am redirected to home page and I am disconnected without error... and message "Your password has been successfully changed" is displayed even if modal return error...
I have implemented authentification using Django django.contrib.auth and it work but I would like change_password to be displayed using modal form and Ajax.
And I do not manage to even display the form inside modal (with all validation stuff).
I have already use bootstrap modal to display information but not for form submission. As it did not call a change_password view that render change_password_form.html template, form is not available and I got an error Parameter "form" should contain a valid Django Form.
How should I do this?
urls.py
class PasswordChangeView(SuccessMessageMixin, auth_views.PasswordChangeView):
<!-- attempt #1 -->
success_message = "Your password have been changed successfully."
def get_success_url(self):
return reverse('export:index')
<!-- attempt #2 -->
# def form_valid(self, form):
# self.object = form.save()
# update_session_auth_hash(self.request, self.object) # prevent user’s auth session to be invalidated and user have to log in again
# return JsonResponse ({'data': 'success'},status = 200)
app_name = 'registration'
urlpatterns = [
...
path('change_password/', PasswordChangeView.as_view(), name='password_change'),
...
]
password_change_form.html (modified)
{% load bootstrap4 %}
<div id = "password_change" class="modal-dialog modal-lg" role="document">
<form action="{% url 'registration:password_change' %}" method="post" id="password_change" class="form">{% csrf_token %}
<div class="modal-content">
<div class='card' style="border-top-width: 0px;border-left-width: 0px;border-bottom-width: 0px;border-right-width: 0px;">
<div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div>
<form method="post" class="form-signin">
<div class='card-body' style="padding-bottom:0px">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %}
</div>
<hr style="margin:1px">
<div class='card-body' style="padding-top:5px;padding-bottom:5px;">
<div>
<button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button>
<!--<i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %} -->
<span data-dismiss="modal" class="btn btn-light border" style="float:right;color:#326690;min-width:110px;margin-right:5px;"><i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %}</span>
</div>
</div>
</form>
</div>
</form>
</div>
<script>
var form_options = { target: '#modal', success: function(response) {
console.log('response',response);
//obj = JSON.parse(response);
$("#password_change_confirm").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><span>Your password has been changed successfully.</span></div>');
} };
$('#password_change').ajaxForm(form_options);
</script>
base.html (modified)
<a data-toggle="modal" data-target="#modal" class="dropdown-item" href="{% url 'registration:password_change' %}"><i class="fa fa-key" aria-hidden="true"></i>
{% trans 'Change password' %}</a>
<div class="modal" id="modal"></div>
index.html (added)
{% extends 'layouts/base.html' %}
...
<!-- message for change password in authentification module -->
<div id="password_change_confirm" style="padding-top:10px;padding-left:10px;padding-right:10px;"></div>
{% for message in messages %}
<div class="container-fluid" style="padding:10px 10px 10px 10px;">
<div id = 'msg' class="alert {{ message.tags }} alert-dismissible" role="alert" >
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
</div>
{% endfor %}
<!-- end message for change password in authentification module -->
OK, I finally find a 'hack' solution that works, do know if it is the better way but it's works:
base.html
<!-- https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/ -->
<div class="modal" id="modal" style="margin-top:150px;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#modal').on('show.bs.modal', function (event) {
var modal = $(this)
$.ajax({
url: "{% url 'registration:password_change' %}",
context: document.body
}).done(function(response) {
modal.html(response);
});
})
)};
registration/views.py
class PasswordChangeView(auth_views.PasswordChangeView):
def form_valid(self, form):
self.object = form.save()
update_session_auth_hash(self.request, self.object) # prevent user’s auth session to be invalidated and user have to log in again
return JsonResponse ({'data': form.is_valid()},status = 200)
registration/urls.py
app_name = 'registration'
urlpatterns = [path('change_password/', PasswordChangeView.as_view(), name='password_change'),]
registration/template/registration/password_change_form.html
<!-- https://www.abidibo.net/blog/2015/11/18/modal-django-forms-bootstrap-4/ -->
{% load i18n widget_tweaks %}
{% load bootstrap4 %}
<div id = "password_change" class="modal-dialog modal-lg" role="document">
<form action="{% url 'registration:password_change' %}" method="post" id="password_change" class="form">{% csrf_token %}
<div class="modal-content">
<div class='card' style="border-top-width: 0px;border-left-width: 0px;border-bottom-width: 0px;border-right-width: 0px;">
<div style="background-color:#326690;padding:5px 5px 5px 16px;color:white;font-weight:bold;border-radius: 2px 2px 0 0;">Change password</div>
<form method="post" class="form-signin">
<div class='card-body' style="padding-bottom:0px">
{% csrf_token %}
{% bootstrap_form form layout="horizontal" placeholder="None" size="medium" label_class="form-label col-md-3" %}
</div>
<hr style="margin:1px">
<div class='card-body' style="padding-top:5px;padding-bottom:5px;">
<div>
<button type="submit" class="btn block" style="float:right;background-color:#326690;color:white;min-width:110px;">{% trans 'Confirm' %}</button>
<span data-dismiss="modal" class="btn btn-light border" style="float:right;color:#326690;min-width:110px;margin-right:5px;"><i class="fa fa-times" aria-hidden="true"></i> {% trans 'Cancel' %}</span>
</div>
</div>
</form>
</div>
</form>
</div>
<script>
var form_options = { target: '#modal', success: function(response) {
<!-- test for form validation status: password changed confirmation message displayed only if form is valid -->
if(response.data == true){
<!-- remove grey background -->
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
$("#password_change_confirm").append('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><span>Your password has been changed successfully.</span></div>');
}
} };
$('#password_change').ajaxForm(form_options);
</script>
myapp/emplate/myapp/index.html
<!-- message for change password in authentification module -->
<div id="password_change_confirm" style="padding-top:10px;padding-left:10px;padding-right:10px;"></div>

Django 2.2 error - Integrity Error, NOT NULL constraint failed

I have a sample Django 2.2 project that has a search bar in the top right corner of the nav bar (taken from the Bootstrapers):
navbar.html:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="/search/">Search</a>
</li>
...
{% endif %}
<li class="nav-item">
<a class="nav-link" href="/a/">A</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/b/">B</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action = '/search/'>
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
It returns "You searched for [search argument]" to the url '/search/' and works fine. I would like to bring it from the nav bar under the 'Search' menu in the nav bar. I have the following:
searches/models.py
from django.db import models
from django.conf import settings
# Create your models here.
class SearchQuery(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null=True, on_delete=models.SET_NULL)
query = models.CharField(max_length=220)
timestamp = models.DateTimeField(auto_now_add=True)
searches/views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from .models import SearchQuery
# Create your views here.
#login_required
# staff_member_required
def search_view(request):
query = request.GET.get('q', None)
user = None
if request.user.is_authenticated:
user = request.user
SearchQuery.objects.create(user=user, query=query)
context = {"query": query}
return render(request, 'searches/view.html',context)
searches/templates/searches/view.html:
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form action = '/search/'>
<input type="search" name="q" aria-label="Search">
<button type="submit">Search</button>
</form>
<div class='row'>
<div class='col-12 col-8 mx-auto'>
<p class='lead'>You searched for {{ query }}</p>
</div>
</div>
{% endif %}
{% endblock %}
When I search from the search bar in the navigational pane, it returns the argument. But when I want to run the search from the search bar and click on the Search tab, I get this:
IntegrityError at /search/
NOT NULL constraint failed: searches_searchquery.query
...
...searches\views.py in search_view
SearchQuery.objects.create(user=user, query=query)
Why am I getting this ?
EDIT:
After making this change in searches/views.py:
query = request.POST.get('q', None)
I get this error in the runtime:
django.db.utils.IntegrityError: NOT NULL constraint failed: searches_searchquery.query
and in the browser:

How do you implement a Form in a ListView

I'm new to Django, I basically have a homepage which has a search bar that is being implement using a Django Form. Additionally, in the homepage I have bootstrap card whichis being used to display data from my model.
I'm using the def_get to render the form (since it's being used to query the DB). The form is very basic, it's just a CharField. However, when I use the def_get to render the Form in my class based view it now doesn't retrieve any of the data that goes into the bootstrap card which is causing the card to not display.
I've tried to render both the form and data in the card by using ModelFormMixin but it seems like this hasn't solved my issue yet, not sure whether this is the way to achieve this?
Forms.py
from django import forms
class SearchBarForm(forms.Form):
q = forms.CharField(label="", max_length=150, required=True)
Views.py
from django.views.generic import TemplateView
from django.views.generic.list import ListView
from property.models import Property
from pages.forms import SearchBarForm
from django.shortcuts import render
class HomePageView(ListView):
model = Property
template_name = 'home.html'
def get(self, request):
form = SearchBarForm()
return render(request, self.template_name, {'form': form})
Home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<div class="container">
<!-- search bar -->
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-8 custom-search-bar">
<form action="{% url 'property_for_rent' %}" method="get" id="search-form">
{{ form.as_p }}
</form>
</div>
<div class="col-xs-6-md-4 custom-search-bar-button">
<button type="submit" form="search-form" class="btn btn-light" value="For sale">For rent</button>
<button form="rent" type="submit" class="btn btn-light" value="For sale">For Sale</button>
</div>
</div>
<!-- search bar -->
<!-- property card -->
<div class="row">
{% for property in object_list|slice:"3" %}
<div class="col-lg-4 d-flex align-items-stretch custom-cards">
<div class="card" style="width: auto;">
<div class="card-img">
{% if property.image %}
<img class="card-img-top" src="{{property.image.url}}" alt="Card image cap"> {% endif %}
</div>
<div class="card-body">
<h5 class="card-title"> {{ property.location }} </h5>
<p class="card-text">{{ property.description }} </p>
<button type="button" class="btn btn-primary waves-effect waves-light" data-toggle="modal" data-target="#modal-{{ property.id }}">View</button>
</div>
<div class="card-footer">
<small class="text-muted">Last updated</small>
</div>
</div>
<!-- property card -->
<!-- Full Height Modal Right -->
<div class="modal fade right" id="modal-{{ property.id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<!-- Add class .modal-full-height and then add class .modal-right (or other classes from list above) to set a position to the modal -->
<div class="modal-dialog modal-full-height modal-right" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title w-100" id="myModalLabel">{{ property.location }}</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{ property.description }}</p>
<ul class="list-group z-depth-0">
<li class="list-group-item justify-content-between">
Bedrooms
<span class="badge badge-primary badge-pill">14</span>
</li>
<li class="list-group-item justify-content-between">
Price
<span class="badge badge-primary badge-pill">2</span>
</li>
<li class="list-group-item justify-content-between">
Location
<span class="badge badge-primary badge-pill">1</span>
</li>
<li class="list-group-item justify-content-between">
Property Type
<span class="badge badge-primary badge-pill">14</span>
</li>
</ul>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Full Height Modal Right -->
</div>
{% endfor %}
</div>
</div>
{% endblock %}
What I want to achieve is to both display the search bar and the cards which are using data from my models.
Any hints on how to achieve this is much appreciated as i'm just a beginner :) Thanks!
You can just pass your form in the get_context_data method [Django-doc]:
class HomePageView(ListView):
model = Property
template_name = 'home.html'
def get_context_data(self, *args, *kwargs):
context = super().get_context_data(*args, **kwargs)
context['form'] = SearchBarForm()
return context
or you can make this more declarative, by making use of the FormMixin mxin [Django-doc]:
from django.views.generic.edit import FormMixin
class HomePageView(FormMixin, ListView):
model = Property
template_name = 'home.html'
form_class = SearchBarForm

Django my models aren't carrying over from file to file

I am getting my menu items to display on the ListView page, but when I click on the link, none of the data displays properly.
Here is my menu-carousel.html
{% for item in object_list %}
<li>
<div class="impx-menu-page-item">
<div class="impx-menu-page-content">
<h4>{{ item.title }}</h4>
<div class="impx-menu-page-price">
<h5>${{ item.price }}</h5>
</div>
<p>{{ item.description }}</p>
</div>
</div>
</li>
{% endfor %}
And that works, now here is the broken part, when I got to /menu/1 or /menu/'whatever number'
<div class="container">
<div class="row">
<h3>{{ item.title }}</h3>
</div>
<div class="row">
<div class = "col-sm-12 col-md-4">
<img src="{{ item.image.url }}" height="300px" width="300px" class = "img img-responsive thumbnail"/>
</div>
<div class = "col-sm-12 col-md-4">
<h6>Price: ${{ item.price }}</h6>
<h6>Materials: {{ item.description }}</h6>
</div>
<div class = "col-sm-12 col-md-4">
<p>{{ item.description|safe|linebreaks }}</p><br /><br />
<hr />
<h5></h5>
</div>
<br><br>
</div>
</div>
This is what displays in my browser
<div class="container">
<div class="row">
<h3></h3>
</div>
<div class="row">
<div class = "col-sm-12 col-md-4">
<img src="" height="300px" width="300px" class = "img img-responsive thumbnail"/>
</div>
<div class = "col-sm-12 col-md-4">
<h6>Price: $</h6>
<h6>Materials: </h6>
</div>
<div class = "col-sm-12 col-md-4">
<p><p></p></p><br /><br />
<hr />
<h5></h5>
</div>
<br><br>
</div>
</div>
Here is my urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from django.contrib import admin
from . import views
from home.models import Menu
urlpatterns = [
url(r'^$', views.home, name="home"),
url(r'^menu/$', ListView.as_view(
queryset=Menu.objects.all().order_by("-title")[:25],
template_name="menu-carousel.html")),
url(r'^menu/(?P<pk>\d+)/$', DetailView.as_view(
model = Menu,
template_name="menu-item.html")),
]
and here is my models.py
from django.db import models
from django.conf import settings
class Menu(models.Model):
title = models.CharField(max_length = 140)
price = models.IntegerField()
description = models.TextField()
image = models.ImageField(upload_to = 'media/' )
menu = models.CharField(max_length = 10)
def __str__(self):
return self.title
I suppose you've used the wrong context object name in DetailView template. More details by link:
https://docs.djangoproject.com/es/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_object_name
Try to display menu item id with {{menu.id}} instead of {{item.id}}. Also you can use django debug template to see all context objects.