How do I retrieve timedate from the database and display in template? - python

I'm a complete Python and Django noob so any help is appreciated. This is what my model looks like:
class Matches(models.Model):
id = models.AutoField(primary_key=True)
date = models.DateTimeField()
court = models.ForeignKey(Courts)
class Participants(models.Model):
id = models.AutoField(primary_key=True)
match = models.ForeignKey(Matches)
userid = models.ForeignKey(User)
games_won = models.IntegerField()
This is what my view looks like:
def index(request):
latest_matches_list = Matches.objects.all()[:5]
return render_to_response('squash/index.html', {'latest_matches_list': latest_matches_list})
return HttpResponse(output)
And my template:
{% if latest_matches_list %}
{% for matches in latest_matches_list %}
{{ match.id }}
{% endfor %}
{% else %}
<p>No matches are available.</p>
{% endif %}
Two questions:
When I do Matches.objects.all() in the shell console it returns: [<Matches: Matches object>]. Why doesn't it print out the id and date?
In the template file I'm initially trying to test printing out the id of Matches but it doesn't seem to be working. What variable do I need for {{ match.id }}. The goal is to print out the following per match:
[matchid] [date] [time] [player1_wins] [player2_wins]
1 1-1-2011 20:00 6 8

1: how would it know to print id and date out of all fields you might have?
You can define what your object returns when printed by defining __unicode__
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.unicode
# ... model class
def __unicode__(self):
return "%s %s" % (self.id, self.date)
2: In your template, you iterate over latest_matches_list with the variable matches yet you use {{ match.id }} which isn't defined. Use {{ matches.id }}.
{% for matches in latest_matches_list %}
{{ match.id }} <!-- not defined -->
{{ matches.id }} <!-- this is your variable -->
{% 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" %}

Value is none when calling out a value of foreign key

I am trying to display a brand of a bike, but the value shows as None.
Models.py:
class Bike(models.Model):
item = models.OneToOneField(Item, on_delete=models.CASCADE)
brand = models.ManyToManyField(Brand, null=True)
class Brand(models.Model):
name = models.CharField(max_length=20)
and here's my template:
{% for item in items %}
{{ item.bike.brand.name }} {{ item.title }}
{% endfor %}
I am calling the brand by {{ item.bike.brand.name }} and it displays as None for every Bike
if your view is like this,
class BikeListView(ListView):
model = Bike
template_name = '----.html'
you can call it in your templates as
{% for obj in object_list %}
{{ obj.field_name in your item model }}
{% for brand_name in obj.brand.all %}
{{ brand_name.name }}
{% endfor %}{% endfor %}

Foreign key relation in Django template

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 %}

Generate a dynamic form using flask-wtf and sqlalchemy

I have a webapp that allows users to create their own fields to be rendered in a form later on.
I have a model Formfield like so:
class Formfield(db.Model):
id = db.Column(db.Integer, primary_key = True)
form_id = db.Column(db.Integer, db.ForeignKey('formbooking.id'))
label = db.Column(db.String(80))
placeholder_text = db.Column(db.String(80))
help_text = db.Column(db.String(500))
box_checked = db.Column(db.Boolean, nullable = True, default = False)
options = db.Column(db.String) # JSON goes here?
answer = db.Column(db.String)
required = db.Column(db.Boolean, nullable = False, default = False)
order = db.Column(db.Integer)
fieldtype = db.Column(db.Integer)
that I use to represent a field, whatever the kind (checkbox, input, more in the future).
As you can see, every field has a FK to a form_id.
I’m trying to generate a dynamic form for a given form_id.
The catch is that I need to determine the type of field to render for every Formfield.
So I also need to process the fieldtype at some point.
I guess a solution would be to somehow pass the form_id to a function in my Form class.
I have no clue how to do it or where to look for a solution.
Any help would be very appreciated!
I think I managed to create dynamic forms with the idea from here https://groups.google.com/forum/#!topic/wtforms/cJl3aqzZieA
you have to create a dynamic form at view function, fetch the form field you want to get, and iterate every field to construct this form object. I used for fieldtypes simple text instead of integer values. Since it seems easy to read at code level.
class FormView(MethodView):
def get(self):
class DynamicForm(wtforms.Form): pass
dform = main.models.Form.objects.get(name="name2")
name = dform.name
for f in dform.fields:
print f.label
setattr(DynamicForm , f.label, self.getField(f))
d = DynamicForm() # Dont forget to instantiate your new form before rendering
for field in d:
print field # you can see html output of fields
return render_template("customform.html", form=d)
def getField(self, field):
if field.fieldtype == "text":
return TextField(field.label)
if field.fieldtype == "password":
return PasswordField(field.label)
# can extend if clauses at every new fieldtype
for a simple form render jinja template 'forms.html'
{% macro render(form) -%}
<fieldset>
{% for field in form %}
{% if field.type in ['CSRFTokenField', 'HiddenField'] %}
{{ field() }}
{% else %}
<div class="form-group {% if field.errors %}error{% endif %}">
{{ field.label }}
<div class="input">
{% if field.name == "body" %}
{{ field(rows=10, cols=40) }}
{% else %}
{{ field() }}
{% endif %}
{% if field.errors or field.help_text %}
<span class="help-inline">
{% if field.errors %}
{{ field.errors|join(' ') }}
{% else %}
{{ field.help_text }}
{% endif %}
</span>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
</fieldset>
{% endmacro %}
and customform.html is like this
{% extends "base.html" %}
{% import "forms.html" as forms %}
{% block content %}
{{ forms.render(form) }}
{% endblock %}

Returning more than one field from Django model

How would one go about returning more than one field from a Django model declaration?
For instance: I have defined:
class C_I(models.Model):
c_id = models.CharField('c_id', max_length=12)
name = models.CharField('name', max_length=100)
def __str__(self):
return '%s' % (self.name)
which I can use, when called in a views.py function to return
{{ c_index }}
{% for c in c_index %}
<div class='c-index-item' c-id=''>
<p>{{ c.name }}</p>
</div>
{% endfor %}
from a template. This is being called in my views.py like so:
c_index = C_I.objects.all()
t = get_template('index.html')
c = Context({'c_index': c_index})
html = t.render(c)
How would I also include the c_id defined in the model above, so that I can include {{c.name}} and {{c.c_id}} in my template? When I remove the str method, I appear to get all of the results, however, it just returns blank entries in the template and will not let me reference the individual components of the object.
What you have is fine. Your template should be:
{% for c in c_index %}
<div class='c-index-item' c-id='{{ c.c_id }}'>
<p>{{ c.name }}</p>
</div>
{% endfor %}

Categories

Resources