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

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.

Related

Model infos not showing up on HTML page Django

I am trying to create an educational website using Django, so when I am trying to render {{ profile.institution }} or {{ profile.grade }} or {{ profile.user.username }} they are not being rendered.I don't know why they aren't. Can anyone help me solve this?
My models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
institution = models.CharField(max_length = 100)
grade = models.CharField(max_length=100, choices= YEAR_IN_SCHOOL_CHOICES)
bio = models.TextField(max_length=300)
def __str__(self):
return f'{self.user.username} Profile'
My views.py:
class User_Profile(LoginRequiredMixin, ListView):
model = Profile
template_name = 'class/profile.html'
context_object_name = 'profile'
def get_queryset(self):
return Profile.objects.filter(user=self.request.user)
My html:
{% extends "class/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<div class="row d-flex justify-content-center">
<h1 style="color: #f5a425">Hello {{ user.username }}</h1>
</div>
<div class="container mt-5">
<div class="row d-flex justify-content-center">
<div class="col-md-7">
<div class="card p-3 py-4">
<div class="text-center">
<i class='fas fa-user-alt' style='font-size:36px'></i>
<!-- <img src="" width="100" class="rounded-circle"> -->
</div>
<div class="text-center mt-3">
<span class="bg-secondary p-1 px-4 rounded text-white">Pro</span>
<h5 class="mt-2 mb-0">{{ profile.user.username }}</h5>
<span>{{ profile.institution }}</span>
<span>{{ profile.grade }} Grade</span>
<div class="px-4 mt-1">
<p class="fonts">{{ profile.bio }}</p>
</div>
<div class="buttons">
<button class="btn btn-outline-primary px-4">Message</button>
<button class="btn btn-primary px-4 ms-3">Contact</button>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
what part of the code should I change to make this work ?
ListView it is about many objects ant iteration through the object_list. In this case the answer of #PouyaEsmaeili is correct.
But. The mistake is - you have a wrong view. DetailView is the right choose.
This returns always one object or nothing.
Profile.objects.filter(user=self.request.user)
In your case:
class User_Profile(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'class/profile.html'
context_object_name = 'profile'
def get_object(self):
return get_object_or_404(self.model, user=self.request.user)
If you set name for template profile_detail.html, you don't need template_name attribute. It should be find automatically.
If you don't change the model_name in Profile._meta - , you don't need context_object_name attribute. It should be defined automatically.
Please, don't forget about Django-views naming best practices.
Last version of your view can be:
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
def get_object(self):
return get_object_or_404(self.model, user=self.request.user)

How can I sort posts by date in my web application in Django?

I have a web application and I was trying to order it by most recent date, that is, the most current above and the oldest dates below, but for some reason it orders me the other way around and on other computers it orders well, the strange thing is that on my local server it is fine, it orders me as I want but at the time of showing it on the website it shows as I had mentioned before.
models.py
from django.db import models
class Publicacion(models.Model):
foto = models.ImageField()
titulo = models.CharField(max_length=200)
contenido = models.TextField()
fecha = models.DateField(auto_now_add=True)
contenido_largo = models.TextField(max_length=10000, default='', null=True, blank=True)
def __str__(self):
return self.titulo
views.py
class ListarPublicaciones(ListView):
model = Publicacion
template_name = 'Publicacion/listarPublicaciones.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
pedidos = Pedido.objects.filter(cliente = self.request.user).aggregate(Sum('cantidad'))
context['Pedido'] = pedidos
context['object_list'] = Publicacion.objects.all().order_by('-fecha')
return context
I have tried with order_by('-fecha__year','-fecha__month','-fecha__day')
html
<section class="py-5"><!-- Page Content -->
<div class="container"><!-- Container página principal -->
<div class="row">
<div class="col-md-12">
<div class="panel">
{% for p in object_list %}
<div class="row">
<br>
<div class="col-md-3 col-sm-3 text-center">
<a class="story-img" href="{% url 'publicacion:detallePublicacion' p.pk %}">
<img src="{{p.foto.url}}" class="rounded" style="width: 250px;"></a>
</div>
<div class="col-md-8 col-sm-9">
<a class="subt" href="{% url 'publicacion:detallePublicacion' p.pk %}"><h2>{{p.titulo}}</h2></a>
<div class="row">
<div class="col-md-12">
<p class="texto">{{p.contenido|urlize}}</p>
<div class="redes list_op" style="text-align: right;">
<ul class="list-inline list-unstyled" >
{% if p.contenido_largo %}
<li>
<a class="plus" href="{% url 'publicacion:detallePublicacion' p.pk %}">Ver más</a>
</li>
<li>|</li>
{% endif %}
<li>{{p.fecha.day}}-{{p.fecha.month}}-{{p.fecha.year}}</li>
<li>|</li>
<li>
<i class="fa fa-share" aria-hidden="true" style="font-size: 12px; color: #2c5d63;"></i> Compartir:
<a target="_blank" href="http://www.facebook.com/sharer.php?u=http://feriacultiva.com/publicaciones/detallepublicacion/{{p.pk}}"><img src="{% static 'icon/facebook.png' %}" border=0 height="25" class="facebook" /></a>
<img class="whatsapp" border="0" src="{% static 'icon/whatsapp.png' %}">
<img class="twitter" border="0" src="{% static 'icon/twitter.png' %}" height="25">
</li>
</ul>
</div>
</div>
<div class="col-xs-3">
</div>
</div>
<br><br>
</div>
</div>
<hr>
{% endfor %}
</div>
</div>
</div>
</div>
</section>
It can be resolved by using '''DateTimeField'''
Then '''order_by''' will work
Replace and remigrate it works fine for me

Bootstrap Modal submit button not working with DeleteView in Django 2.2

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'),
]

How to count objects in django

Thank you all for always sharing your knowledge here.
I have an issue with counting an object in Django. I am currently learning and working on a basic HR system and already have my views, models, et al set up. I plan to have an interface whereby I can print out employees count based on gender. The one I currently have set up is increasing the counts for both male and female any time I create a new employee. Please how do I correct this anomaly?
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2.export import TableExport
from .models import Employee
from .models import EmployeeFilter
from .tables import EmployeeTable
#login_required()
def employees(request):
filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
table = EmployeeTable(filter.qs)
RequestConfig(request, paginate={"per_page": 15}).configure(table)
count = Employee.objects.all().count()
male_count = Employee.objects.filter(gender__contains='Male').count()
female_count = Employee.objects.filter(gender__contains='Female').count()
user_count = User.objects.all().count()
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format("csv", "xlsx"))
return render(request, "employees/employees.html", {
"table": table,
"filter": filter,
"count": count,
"male_count": male_count,
"female_count": female_count,
"user_count": user_count,
})
template.html
{% extends "employees/base.html" %}
{% load render_table from django_tables2 %}
{% load django_tables2 %}
{% load querystring from django_tables2 %}
{% block content %}
<!--Data overview-->
<div class="container data overview">
<div class="row">
<div class="col-md-3">
<div class="container-fluid bg-warning data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading font-weight-bold">Total Employees</h6>
<p class="data-text ">{{ count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users data-icon"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-dark data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Male Employees</h6>
<p class="data-text text-white">{{ male_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-male data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-danger data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Female Employees</h6>
<p class="data-text text-white">{{ female_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-female data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-secondary data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading text-white font-weight-bold">Active Users</h6>
<p class="data-text text-white">{{ user_count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users-cog data-icon text-white"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Employees data-->
<div class="filter-container container-fluid">
<div class="row">
<div class="col-md-9">
<!--filter form-->
<form action="" class="form form-inline employee-filter-form" method="get">
<legend class="mb-2">Filter employee records</legend>
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ filter.form.first_name.errors }}
{{ filter.form.first_name }}
</div>
<div class="fieldWrapper">
{{ filter.form.last_name.errors }}
{{ filter.form.last_name }}
</div>
<button aria-expanded="false" aria-haspopup="true"
class="ml-2 btn btn-danger filter-btn" type="submit">
Filter
</button>
</form>
</div>
<div class="col-md-3 download-btn-col">
<button aria-expanded="false" aria-haspopup="true"
class="mr-3 btn btn-success" type="submit">
<i class="fas fa-upload"></i> Import
</button>
<div class="btn-group download-btn">
<button aria-expanded="false" aria-haspopup="true"
class="btn btn-warning dropdown-toggle"
data-toggle="dropdown" type="button">
<i class="fas fa-file-export"></i> Export
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% querystring '_export'='csv' %}">csv</a>
<a class="dropdown-item" href="{% querystring '_export'='xlsx' %}">xlsx</a>
</div>
</div>
</div>
</div>
</div>
<!-- data rendered here -->
{% render_table table 'django_tables2/bootstrap.html' %}
<!-- data rendered here -->
{% endblock content %}
models.py
...
GENDER_CHOICES = (
('FEMALE', 'Female'),
('MALE', 'Male'),
("DWTS" "Don't want to say"),
)
...
#python_2_unicode_compatible
class Employee(models.Model):
# basic information of employee
first_name = models.CharField(_('first name'), max_length=40)
last_name = models.CharField(_('last name'), max_length=40)
emp_photo = models.ImageField(_('passport'))
date_of_birth = models.DateField(_('birthday'))
gender = models.CharField(_('gender'), max_length=15, choices=GENDER_CHOICES, default=['MALE', 'Male'])
house_address = models.CharField(_('house address'), max_length=100)
city_of_residence = models.CharField(_('city'), max_length=100)
state_of_residence = models.CharField(_('state'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
country_of_residence = models.CharField(_('country'), max_length=100, choices=COUNTRY_CHOICES,
default=[156, 'Nigeria'])
state_of_origin = models.CharField(_('state of origin'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
class Meta:
verbose_name = _('Employee')
verbose_name_plural = _('Employees')
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
#python_2_unicode_compatible
class EmployeeFilter(django_filters.FilterSet):
first_name = django_filters.CharFilter(lookup_expr='iexact', widget=TextInput(
attrs={'placeholder': 'First name', 'class': 'input_search'}))
last_name = django_filters.CharFilter(lookup_expr='iexact',
widget=TextInput(attrs={'placeholder': 'Last name', 'class': 'input_search'}))
class Meta:
model = Employee
fields = ["first_name", "last_name", ]
I think you need to remove contains from your filter:
male_count = Employee.objects.filter(gender='Male').count()
female_count = Employee.objects.filter(gender='Female').count()
Or make a single request:
male_femail_count = Employee.objects.values('gender').annotate(count=Count('id'))
# result
# [{'gender': 'Male', 'count': 2}, {'gender': 'Female', 'count': 3}]

How to insert a second model into my ListView

views.py
from django.shortcuts import render, get_object_or_404
from library.models import Game
from .models import Post
from django.views.generic import (
ListView
)
from django.template import context
# Create your views here.
def home(request):
context = {
'recent': Game.objects.all().order_by('post__date_posted')[:5],
'posts': Post.objects.all()
}
return render(request, 'main/home.html', context)
class TitlePostListView(ListView):
model = Post
template_name = 'main/title_posts.html'
context_object_name = 'posts'
def get_queryset(self):
title = get_object_or_404(Game, title=self.kwargs.get('title'))
return Post.objects.filter(game=title).order_by('-date_posted')[:5]
title_posts.html
{% extends "main/base.html" %}
{% load static %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'main/title_posts.css' %}">
{% endblock styles %}
{% block content %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
<hr>
{% for post in posts %}
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
{% endblock content %}
models.py
class Post(models.Model):
article_title = models.CharField(max_length=60, default="Article Title Place Holder")
content = HTMLField(default="Article Content Pace Holder")
date_posted = models.DateTimeField(default=timezone.now)
game = models.ForeignKey('library.Game', on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png')
class Game(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
cover = models.ImageField()
cover_display = models.ImageField(default='default.png')
developer = models.CharField(max_length=100)
Edit: I have a page that displays posts/articles for a certain video game. Currently my query returns the posts from the Post model for that video game. However, I am unsure of how to also display the video games description and images on that same page. The {{game.cover.url}}, ((game.description}}, and {{game.cover_display.url}} do not show up when I load the page because I am unsure how to also get that specific games objects from the Game model.
{% for post in posts %}
{% with post.game.set.all|first as game %}
<style>
body {
background-image: url("{{ game.cover_display.url }}");
background-repeat: no-repeat;
background-size: 100% 1000px;
background-color: #171717;
}
</style>
<div class="container margin-top-300 black">
<div class="row justify-content-center">
<div class="col-3 text-center">
<img src="{{ game.cover.url }}">
</div>
<div class="col">
<p>{{ game.description| safe }}</p>
</div>
</div>
{% endwith %}
<hr>
<div class="row">
<div class="col-4 article-column-height text-center">
<img class="article-image-height" src="{{ post.article_image.url }}">
</div>
<div class="col-8 article-column-height">
<h2><a class="article-title" href="#">{{ post.article_title }}</a></h2>
</div>
</div>
<hr>
</div>
{% endfor %}
You are using ForeignKey. So use like this in loop
{% with post.game_set.all|first as game %}
<img src="{{ game.url }}" />
{% endwith %}
As you are already filtering by game then only add the game in your get_context_data() method
def get_context_data(self, **kwargs):
context = super(TitlePostListView, self).get_context_data(**kwargs)
context['game'] = get_object_or_404(Game, title=self.kwargs.get('title'))
return context