Foreign Key not Responding while fetching, Django - python

I am making a Django Project, A Business Directory.
In which while fetching data from DB, I am unable to fetch the data related to Foreign Key,
Please help
my models.py is::
from django.db import models
class Directory(models.Model):
Bussiness_name = models.CharField(max_length=300)
Description = models.CharField(max_length=900)
Number = models.CharField(max_length=100)
Web_url = models.CharField(max_length=800)
Catogory = models.CharField(max_length=200)
def __unicode__(self):
return self.Bussiness_name
class Adress(models.Model):
directory = models.ForeignKey(Directory)
adress_name = models.CharField(max_length=300)
def __unicode__(self):
return self.adress_name
class Photos(models.Model):
directory = models.ForeignKey(Directory)
Photo_path = models.CharField(max_length=100)
Photo_name = models.CharField(max_length=100)
def __unicode__(self):
return self.Photo_name
My view.py is ::
# Create your views here.
from django.http import HttpResponse
from crawlerapp.models import Directory
from crawlerapp.models import Adress
from crawlerapp.models import Photos
from django.template import Context, loader
from django.shortcuts import render
def index(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/index.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def contactus(request):
Directory_list = Directory.objects.all()
t=loader.get_template('C:/Python27/django/crawler/templates/crawlertemplates/contactus.html')
c = Context({'Directory_list': Directory_list,})
return HttpResponse(t.render(c))
def search(request):
if 'what' in request.GET and request.GET['what']:
what = request.GET['what']
crawlerapp = Directory.objects.filter(Catogory__icontains=what)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': what})
elif 'who' in request.GET and request.GET['who']:
who = request.GET['who']
crawlerapp = Directory.objects.filter(Bussiness_name__icontains=who)
return render(request, 'C:/Python27/django/crawler/templates/crawlertemplates/search.html',
{'crawlerapp': crawlerapp, 'query': who})
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
When I am trying to fetch data from my DB(MySQL), It is only fetching the data of the class Directory, form Models.py
And the code I used in html page for fetching is::
<p>You searched for: <strong>{{ query }}</strong></p>
{% if crawlerapp %}
<p>Found {{ crawlerapp|length }} in this Category{{ crawlerapp|pluralize }}.</p>
<ul>
{% for Directory in crawlerapp %}
<li>Business Name: {{ Directory.Bussiness_name }}</li>
Description: {{ Directory.Description }}</br>
Contact Number: {{ Directory.Number }}</br>
Web_URL: {{ Directory.Web_url }}</br>
Adress: {{ Adress.adress_name }}</br>
Photo: {{ Photos.Photo_name }}</br></br>
{% endfor %}
</ul>
{% else %}
<p>No Business matched your search criteria.</p>
{% endif %}
The OutPut I am getting is somewhat like below
like for example: You searched for: computer repair
Found 1 in this Categorys
Business Name: C S Tecj
Description: hello
Contact Number: 098754
Web_URL: www.rrrrrr.co
Adress:
Photo:
Please help me to fetch the data for the foreign keys, that is Adress: and Photo: ,too
Please help to solve this.

You can access the ForeignKey objects in the reverse order like this:
{% for Directory in crawlerapp %}
<li>Business Name: {{ Directory.Bussiness_name }}</li>
Description: {{ Directory.Description }}</br>
Contact Number: {{ Directory.Number }}</br>
Web_URL: {{ Directory.Web_url }}</br>
Adress: {% for Adress in Directory.adress_set.all %}{{ Adress.adress_name }}</br>{% endfor %}
Photo: {% for Photos in Directory.photos_set.all %}{{ Photos.Photo_name }}</br>{% endfor %}</br>
{% endfor %}

Related

no such column: student_student.course_id

I am creating a simple system using Django Sqlite but I am facing this error whenever i try to open the table as an admin in the django/admin by clicking Studends table. The error is the following:
OperationalError at /admin/student/student/
no such column: student_student.course_id
I searched allot but could not find any exact solution to my problem.
The following is my code.
views.py
from django.shortcuts import render
from .models import Student
# Create your views here.
def index(request):
return render(request, "student/index.html",{
"student": Student.objects.all()
})
index.html
{% extends "student/layou.html" %}
{% block body %}
<h2>Student information</h2>
<ul>
{% for student in Student %}
<li> {{ student.id }} Student Full Name: {{ student.f_name }}{{ student.l_name }} in {{ student.grade }} with {{ student.gpa }} in {{ student.course_id }}</li>
{% empty %}
No information entered
{% endfor %}
</ul>
{% endblock %}
models.py
from django.db import models
# Create your models here.
class Course(models.Model):
code = models.CharField(max_length=10)
course_name = models.CharField(max_length=64)
def __str__(self):
return f"Course name: {self.course_name} with course code ({self.code})"
class Student(models.Model):
f_name = models.CharField(max_length=64)
l_name = models.CharField(max_length=64)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name= "Classes" )
grade = models.CharField(max_length=10)
gpa = models.DecimalField(max_digits=4.0, max_length=4, decimal_places=2)
def __str__(self):
return f"{self.id} Full Name: {self.f_name} {self.l_name} in {self.grade} with a gpa {self.gpa} in course {self.course_id}"
You cannot refer to Course object via Student object with that:
{{ student.course_id }}
You can get to object or it's id like that:
{{ student.course }} # returns related Course object
{{ student.course.id }} # returns related Course object's id
For future reference, you also want to make more changes:
"student": Student.objects.all()
# change to:
"students": Student.objects.all()
{% for student in Student %}
# change to:
{% for student in students %}
{% extends "student/layou.html" %}
# probably change to:
{% extends "student/layout.html" %}

Adding a maximum limit to the number of post using python

I need to limit the number of posts in Django queries. I have tried to add a min and max but nothing seemed to have worked. I have added home.html into the code.
Example: I should only have the 15 most recent posts in my blog. The rest can be seen by clicking on the category button.
Home.html:
{% extends 'base.html' %}
{% block content %}
<h1>Posts</h1>
<ul>
{% for post in object_list %}
<li>{{post.title}}
<style>
a {
text-transform: capitalize;
}
</style>
- {{ post.category }} - <a href="{% url 'show_profile_page' post.author.profile.id %}">{{ post.author.first_name }}
{{ post.author.last_name }}</a> - {{ post.post_date }} <small>
{% if user.is_authenticated %}
{% if user.id == post.author.id %}
- (Edit)
(Delete)
{% elif user.id == 1 %}
- (Edit)
(Delete)
{% endif %}
{% endif %}
</small><br/>
{{ post.snippet }}</li>
{% endfor %}
</ul>
{% endblock %}
view.py:
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-id']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args,**kwargs)
context["cat_menu"] = cat_menu
return context
models.py:
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to='images/')
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='intro')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='post_likes')
dislikes = models.ManyToManyField(User, related_name='post_dislikes')
I think you have another template for displaying categorised objects when you click category button. As you said
"I should only have the 15 most recent posts in my blog. The rest can
be seen by clicking on the category button."
In this case you can use a simple hack to display most recent posts from your table.
query all objects in descending order in views
all_objs = Post.objects.all().order_by('-id')
Then use {% if forloop.counter <= 15 %} to display last 15 items only. as follow.
templates
{% for post in object_list %}
{% if forloop.counter <= 15 %}
<h4>{{obj}} #or anything really that is meant to be shown on the home page.</h4>
{% endif %}
{% endfor %}
You can do something like this:
def get_context_data(self, *args, **kwargs):
context = super(HomeView, self).get_context_data(*args,**kwargs)
context["cat_menu"] = Category.objects.all()
context["most_recent_posts"] = Post.objects.filter(author=self.request.user).order_by('-post_date')[:15]
return context
This will get the 15 most recent posts authored by the current user, ordered by the date it was posted.
Then just handle displaying this in home.html for example:
<ul>
{% for p in most_recent_posts %}
<li>{{ p.title }}</li>
{% endfor %}
</ul>
Just limit your query to the latest 15 entries sorted by post_date:
cat_menu = Category.objects.latest("post_date")[:15]
https://docs.djangoproject.com/en/3.2/topics/pagination/
The best way is Django Pagintion.
{% for contact in page_obj %}
{# Each "contact" is a Contact model object. #}
{{ contact.full_name|upper }}<br>
...
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
from django.core.paginator import Paginator
from django.shortcuts import render
from myapp.models import Contact
def listing(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page.
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'list.html', {'page_obj': page_obj})
you can use Django pagination api . Manage your data through page number. Initially pass 1 and after that page number given by pagination.
paginator = Paginator(yourquerysetdata, 20)
page_num = request.data.get('page')
result = yourSerializerName(paginator.get_page(page_num) many=True).data
try:
page = paginator.page(page_num)
except:
page = paginator.page(1)
count = paginator.num_pages
resultobj = paginator.get_page(page_num)
has_prev = resultobj.has_previous()
has_next = resultobj.has_next()
page_range = resultobj.paginator.page_range.stop - 1
if has_prev:
prev_page_no = resultobj.previous_page_number()
else:
prev_page_no = 0
if has_next:
next_page_no = resultobj.next_page_number()
else:
next_page_no = None
context = dict()
context['page'] = page.number
context['page_no'] = count
It is very simple. You just have to modify the query that you are using to fetch the posts.
In the get_context_data() method, replace cat_menu = Category.objects.all() with cat_menu = Category.objects.all().order_by('-post_date')[:15]. This will limit the number of results to 15 most recent objects.
For more understanding, you can take a look at the official Django docs for Limiting QuerySets.

Django: Reverse not found. 'teachers_detail' is not a valid view function or pattern name

I'm new in django. I am using this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views, but can't get the right work of my application.
I created an app "education" in my "edusys" project. I'm trying to get the list of teachers from database and go to every teacher's page, where I'll be able to see their information from database.
I get the next error when I use "runserver":
Reverse for 'teachers_detail' not found. 'teachers_detail' is not a valid view function or pattern name.
What am I doing wrong? I can't solve the problem myself and can't find the right answer in google.
My files of this project looks like this:
education/models.py :
from django.db import models
from django.urls import reverse
class Teachers(models.Model):
tcode = models.CharField(max_length=10, primary_key=True)
last_name = models.CharField(max_length=20)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=20, null=True, blank=True)
department_s = models.ForeignKey('Departments', on_delete=models.SET_NULL, null=True)
employee_post = models.CharField(max_length=20)
academic_degree = models.CharField(max_length=40)
email = models.EmailField(max_length=50)
GENDER_UNIT = (
('m', 'Мужчина'),
('f', 'Женщина'),
)
gender = models.CharField(max_length=1, choices=GENDER_UNIT)
class Meta:
ordering = ['last_name']
def __str__(self):
return '%s %s %s' % (self.last_name, self.first_name, self.middle_name)
def get_absolute_url(self):
return reverse("teachers_detail", args=[str(self.tcode)])
education/urls.py :
from django.urls import path
from . import views
from django.conf.urls import url
app_name = 'education'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^teachers/$', views.TeachersListView.as_view(), name='teachers'),
#url(r'^teachers/(?P<pk>\d+)$', views.TeachersDetailView.as_view(), name='teachers_detail'),
url(r'^teachers/<int:pk>$', views.TeachersDetailView.as_view(), name='teachers_detail'),
]
education/views.py :
from django.shortcuts import render
from django.http import HttpResponse
from .models import Teachers
from django.views import generic
def teachers_detail(request, pk):
context = dict()
return render(request, 'education/teachers_detail.html', context)
class TeachersListView(generic.ListView):
model = Teachers
paginate_by = 10
context_object_name = 'teachers_list'
template_name = 'education/teachers_list.html'
class TeachersDetailView(generic.DetailView):
model = Teachers
#book_id=Teachers.objects.get(pk=Teachers.tcode)
education/teachers_list.html :
{% extends "base_generic.html" %}
{% block content %}
<div class="container"><div class="col-12"><h1>Teachers list</h1></div></div>
<div class="container">
{% if teachers_list %}
<table class="table">
<tbody>
{% for Teachers in teachers_list %}
<tr>
<th scope="row"></th>
<td>{{ Teachers.last_name }} {{ Teachers.first_name }} {{ Teachers.middle_name|default_if_none:"" }} ({{Teachers.department_s}})</td>
<th scope="row"></th>
<td>{{ Teachers.email }}</a></td>
<th scope="row"></th>
<td>Профиль</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>list is empty.</p>
{% endif %}
</div>
{% endblock %}
education/teachers_detail.html :
{% extends "base_generic.html" %}
{% block content %}
<h1>{{ Teachers.last_name }} {{ Teachers.first_name }} {{ Teachers.middle_name }}</h1>
<p><strong>email:</strong> {{ Teachers.email }}</a></p>
<p><strong>department:</strong> {{ Teachers.department_s }}</a></p>
<p><strong>employee post:</strong> {{ Teachers.employee_post }}</a></p>
<p><strong>academic dehree:</strong> {{ Teachers.academic_degree }}</a></p>
{% endblock %}
As per urls and models.py file problem lies in get_absolute_url method as url is expecting a keyword argument named pk while you are supplying an args in get_absolute_url ie.args=[str(self.tcode)].Kindly change the same as below.
updated one:
def get_absolute_url(self):
return reverse("teachers_detail",kwargs = {'pk': self.tcode })
Old one:
def get_absolute_url(self):
return reverse("teachers_detail", args=[str(self.tcode)])
Note: Also as per ulrs.py the pk should be a integer value while as per model tcode is primary key and its a char field you can either use the correct field type or update the url keyword argument.I mean to say both should be in sync to avoid any explicit type casting.
url(r'^teachers/<int:pk>$', views.TeachersDetailView.as_view(), name='teachers_detail'),
The issue is due to the teachers_detail URL path taking an integer parameter (<int:pk>) when the Teachers model has a custom primary key (tcode) and it is a string.
The following path should work (I tested it with the rest of your code):
path('teachers/<str:tcode>', views.TeachersDetailView.as_view(), name='teachers_detail')

Annotate method in django

I have a little problem with annotate. I want to display records from my class Kategorie in the main html file. I used the annotate method to take the query from db. I used in the second class Firmy the ForeignKey to class Kategorie. Now I dont know how to display for example how many websites added in the class Firmy are in the for example in category Business. Now I have something like: "Business (2)(3)(4)" when I used annotate with count by id. This is my models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
And some part from views.py
from django.db.models import Count
wpisy_kat = Kategorie.objects.annotate(cnt_witryna=Count('Witryna'))
So what kind of method or tags I have to use to display for example:
Business(34)
Industry(21)
Health Care(11)
where the name od category is field from class Kategorie and integer is a result from query to database how many websites are in for example Business category?
My html file is:
{% for kategoria in kategorie %}
<table>
<tr>
<td>
<li>{{ kategoria.glowna|linebreaksbr }} </li>
{% for wpis in wpisy_kat %}
{{ wpis }} ({{ cat.cnt_witryna }})
{% endfor %}
</td>
</tr>
</table>
{% endfor %}
and the main html file:
{% include 'firmy/header.html' %}
<html>
<body>
<p>
<center>
<ul id="menu">
<li>Strona główna</li>
<li>Jak dodać stronę</li>
<li>Regulamin</li>
<li>Kontakt</li>
</ul>
</center>
<div class="glowna">
<div class="lewe_menu">
<h3><center>Ostatnio dodane</center></h3>
{%include 'firmy/widok_strony.html'%}
</div>
<div class="srodek">
<h3><center>Kategorie</center></h3>
<center>{%include 'firmy/widok_kategorii.html'%} </center>
</div>
<div class="prawe_menu">
<h3><center>Reklama</center></h3>
<center>Tutaj wpisz kod reklamy </center>
</div>
{% include 'firmy/footer.html' %}
</div>
</body>
</html>
view.py file
from django.shortcuts import render, get_object_or_404
from .models import Witryna, Kategorie
from django.utils import timezone
from django.db.models import Count
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all()
wpisy_kat = Witryna.objects.annotate(cnt_kategoria=Count('kategoria'))
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat,})
def index(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
kategorie = Kategorie.objects.order_by('glowna')
wpisy_kat = Witryna.objects.annotate(cnt_witryna=Count('kategoria'))
return render(request, 'firmy/index.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat, 'firmy': firmy})
def detale_strony(request, slug):
det_wpisu = get_object_or_404(Witryna, slug=slug)
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/detale_strony.html', {'det_wpisu': det_wpisu, 'firmy': firmy})
def detale_kat(request, slug_kat):
det_kategorii = get_object_or_404(Kategorie, slug_kat=slug_kat)
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/detale_kat.html', {'det_kategorii': det_kategorii, 'firmy': firmy})
Your view needs to return something like :
wpisy_kat = Kategorie.objects.annotate(cnt_witryna=Count('witryna'))
return render(request, 'app/template.html', {'wpisy_kat': wpisy_kat})
template.html :
<ul>
{% for cat in wpisy_kat %}
<li>{{ cat }} ({{ cat.cnt_witryna }})</li>
{% endfor %}
</ul>
EDIT :
You can add sorting or filtering to the annotate query, no need to pass 2 parameters from the view, and no need to perform to for/loops :
replace the query in the view :
wpisy_kat = Kategorie.objects.annotate(cnt_witryna=Count('witryna')).order_by('glowna')
Then in the HTML:
<ul>
{% for cat in wpisy_kat %}
<li>{{ cat }} ({{ cat.cnt_witryna }}) </li>
{% endfor %}
</ul>

Django foreign key object image in template

Ok I know a thousand people asked this but I have looked all over this site to no success(also google) here is my models.py
VENUE_IMAGE_PATH = os.path.join('images', 'venue_profiles/%Y/%m/%d')
class Venue(models.Model):
.....................
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
...........................
class VenueImage(models.Model):
venue = models.ForeignKey(Venue, related_name="venue")
image = models.ImageField(upload_to=VENUE_IMAGE_PATH, max_length=255)
Here is my views.py
def list(request):
venues = Venue.objects.all()
images=VenueImage.objects.all()
return render_to_response('venues/list.html', {'venues':venues,'images':images},
context_instance = RequestContext(request))
here is my template
{% for v in venues %}
<a href='#'>{{v.name}}</a>
edit
{% if images %}
<img class='venue_image' src='images/venue_profiles/2012/10/25/{{images.url}}'
alt=''>
{% endif %}
{% endfor %}
Now I have tried {{images.images.url}} and {{images.url}}. {{MEDIA_URL}}images/venue_profiles/%Y/%m/%d/{{image.url}}.
I also tried {%for i in images %} {{i.url}} {% endfor %}.
I also tried without that 'images/venue_profiles/2012/10/25' prefix and nothing seems to work.
Can someone please help me see what I am doing wrong.
# In models.py
class Venue(models.Model):
....
name = models.CharField(max_length=100)
....
images = models.ForeignKey(VenueImage)
class VenueImage(models.Model):
image = models.ImageField(upload_to=VENUE_IMAGE_PATH)
# In views.py
def list(request):
venues = Venue.objects.all()
return render(request,
'venues/list.html',
{'venues': venues'})
# In template
{% for venue in venues %}
<a href '#'>{{ venue.name }}</a>
...
{% for image in venue.images %}
<img class='venue_image' src=''{{ image.url }}' alt=''>
{% endfor %}
{% endfor %}

Categories

Resources