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" %}
Related
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')
I have parent class and child class, that inherits parent class. And that is okay, I can iterate with for loop. Now I want to access child class (example: 'product_type' So basically, I'm confused how we inherits stuff from child class inside the same loop...
views.py
from django.views import generic
from . models import Category
from django.shortcuts import render
class CategoryListView(generic.ListView):
model = Category
template_name = 'category_list.html'
models.py
from django.db import models
import uuid
class Category(models.Model):
name = models.CharField(max_length=100, help_text='Category name')
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Categories'
class Product(models.Model):
product_name = models.CharField(max_length=255, help_text='Product name')
# product_spec = models.TextField(max_length=5000, help_text='Product specs')
product_type = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.product_name
category_list.html
{% extends 'base.html' %}
{% block body %}
{% for page in category_list %}
<li>{{ page.name }}</li>
<li>{{ page.product_name }} # <--------------- Now this is the point of
#my problem, I want to get
#product name from child
#class
#this returns empty <li>
{% endfor %}
{% endblock %}
you can to this
{% extends 'base.html' %}
{% block body %}
{% for page in category_list %}
<li>{{ page.name }}</li>
<li>{{ page.product_set.first.product_name }}
product name from child class, this returns empty <li>
{% endfor %}
{% endblock %}
First off change your product_type name to just category its way easier to understand and add an attribute related_name to it like this:
class Product(models.Model):
name = models.CharField(max_length=255, help_text='Product name')
category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, related_name='products')
then in your template
{% for category in category_list %}
{{ category.name }}
{% for product in category.products.all %}
{{ product.name}}
... other product data
{% endfor %}
{% endfior %}
product_typein Product is a ForaignKey which means their will be multiple products having same Category so their exist two solutions
make product_type in Product one to one key, with this you shuld get single name by {{ page.product.product_name }}
print list of all products of the category, you can do this by iterating page.product_set as it is a list (iterable) with for loop.
I know this question is asked before many times but I still can't solve it.
model.py
class Awb (models.Model):
awb_id = models.CharField(primary_key=True, max_length=50)
awb_shipment_date = models.DateTimeField()
awb_shipper = models.CharField(max_length=250)
awb_sender_contact = models.CharField(max_length= 50)
class History (models.Model):
history_id = models.AutoField(primary_key=True)
awb = models.ForeignKey(Awb)
history_city_hub = models.CharField(max_length=250)
history_name_receiver = models.CharField(max_length=250)
view.py
def awb_list_view(request):
data = {}
data['awb'] = Awb.objects.all()
data['history'] = History.objects.all()
return render(request, 'portal/awb-list.html', data)
templates
{% for s in awb.history_set.all %}
{{ s.awb_id }}
{{ s.history_id }}
{% endfor %}
When I tried it with this code, there is no results in templates. I want to show awb_id and history_id in templates. Could you help me?
First let's take a look at the view code...
def awb_list_view(request):
data = {}
data['awb'] = Awb.objects.all()
data['history'] = History.objects.all()
return render(request, 'portal/awb-list.html', data)
The context dictionary being passed to the template contains an item with key 'awb' and respective QuerySet Awb.objects.all().
Now let's take a look at the template for loop...
{% for s in awb.history_set.all %}
This opening for loop template tag is trying to produce a reverse set of History objects. In order to achieve this, we would need a single AWB object instance. Instead, the 'awb' variable is a QuerySet which was passed as context to the template.
If the goal of this code is to show all AWB objects with their related History objects, the following template code should be valid.
{% for awb_obj in awb %}
{% for history_obj in awb_obj.history_set.all %}
{{ awb_obj.id }}
{{ history_obj.id }}
{% endfor %}
{% endfor %}
The Awb.history_set.all only applies to one Awb object, not a queryset.
This would work:
data['awb'] = Awb.objects.first() # If the first one has history
or:
Loop through all the Awb objects in the template to access the history_set for each one.
{% for a in awb %}
awb: {{ a.awb_id }}<br>
{% for h in a.history_set.all %}
history: {{ h.history_id }}<br>
{% endfor %}
{% endfor %}
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 %}
Consider this model
class Exercise(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Score(models.Model):
"""Scores of users by exercise"""
exo = models.ForeignKey(Exercise)
user = models.ForeignKey(User)
score = models.IntegerField()
class Meta:
unique_together = (('exo', 'user',),)
I have a template which displays the Exercises.
<ul>
{% for exo in exos %}
<li>{{ exo }}</li>
{% endfor %}
</ul>
Here is the view
def view_exos(request):
"""Lists Exercises"""
objs = {
'exos': Exercise.objects.all(),
}
return render_to_response('content/contents.html', objs
, context_instance=RequestContext(request)
)
Now I'd like to display the Score of the current user in front of each Exercise (if there is one) in order to access it from the template in this manner:
<li>{{ exo }} - {{ exo.user_score }}</li>
What I'd do would be to get all the user's current scores up front, create a dictionary mapping exercise to score, then add the score as an attribute of each exercise. Something like:
user_scores = request.user.score_set.all()
score_dict = dict((sc.exo_id, sc.score) for sc in user_scores)
exos = Exercise.objects.all()
for ex in exos:
ex.current_user_score = score_dict.get(ex.id)
Now each exercise in exos has a current_user_score attribute, which is the current user's score for that exercise (or None).
django.contrib.auth has a context processor that adds a user variable to the template context, referencing the current user. This can enable you to get all scores for the current user, then you can create a template filter that returns the score for a particular exercise.
In a file named exercises.py within a templatetags package.
[Put the package in the folder of one of your apps in INSTALLED_APPS. Remember templatetags must be a valid Python package ie. with an __init__.py]
from django.template import Library
register = Library()
#register.filter
def score_for_exercise(scores, exercise):
s = scores.filter(exo=exercise)
if s:
return s[0].score
return None
In the template:
{% load exercises %}
{% with user.score_set.all as user_scores %}
<ul>
{% for exo in exos %}
{% with user_scores|score_for_exercise:exo as score %}
<li>{{ exo }}{% if score %} - {{score}}{% endif %}</li>
{% endwith %}
{% endfor %}
</ul>
{% endwith %}
Maybe you can add an attribute to your Exercise:
class Exercise(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
def user_score(self):
return Score.objects.get(exo=self).score