In models.py:
class PUser(models.Model):
phone = models.TextField(blank=True, null=True)
email = models.TextField()
txt = models.TextField(blank=True, null=True)
I want to create Multidimensional Array for that.
For now this is what I have in the function in views.py:
def main(request):
users = []
for i in range (5):
for a in range(3):
users[i][a] = PUser.objects.all()
return render(request, 'main.html', {'users': users})
But I know its not correct, its not working.
How should I edit it?
And how the code in the main.html should be?
I was thinking about something like {{ users[2][3] }} for example. How the code should be? (I have read same questions but was not helpful for me)
Since PUser.objects.all() returns an array of PUser object, you just have to write :
def main(request):
users = PUsers.objects.all()
return render(request, 'main.html', {'users': users})
and in your template, iterate on users array :
{% for user in users %}
{{ user.phone }}
{{ user.email }}
{{ user.txt }}
{% endfor %}
If you wanna print a specific user, you can by specifying its index :
{{ users[3].phone }}
{{ users[3].email }}
{{ users[3].txt }}
# or
{{ users.3.phone }}
{{ users.3.email }}
{{ users.3.txt }}
Related
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" %}
In a simple view I pass a family in template like this:
def page(request):
family= Author.objects.all()
return render(request, "myapp/page.html", {'family':family})
and I render in template like this:
{% for item in family %}
{{ item.pk }}
{% endfor %}
But, if I put my family inside a for cycle; for example:
def page(request):
family = []
for i in range(5):
family= Author.objects.filter(name='John')[i]
return render(request, "myapp/page.html", {'family':family})
it not render anything in template...
Any idea?
EDIT 1
I have more users in my app, every user has different blog and every blog has different post...
So when user is logged i need to show his blog and for every blog show last 5 post.
I do:
#login_required
def page(request):
user = request.user.id
numblog = Blog.objects.filter(user_id=user).aggregate(c=Count('id'))
for i in range(numblog['c']):
blogquery = Blog.objects.filter(user_id=user)[i]
postquery = Post.objects.filter(blog_id=blogquery.pk)[:5]
return render(request, "myapp/page.html", {'blogquery ':blogquery,'postquery ':postquery })
expected result in template:
{% for b in blogquery %}
{{ b.name }} ### here name of blog
{% for p in postquery %}
{% if p.blog_id == b.pk %}
{{ p.content }} ### here last 5 post of THAT blog
{% endif %}
{% endfor %}
{% endfor %}
EDIT 2
In a view, if I print result it work but not render in template
#login_required
def page(request):
user = request.user.id
numblog = Blog.objects.filter(user_id=user).aggregate(c=Count('id'))
for i in range(numblog['c']):
blogquery = Blog.objects.filter(user_id=user)[i]
postquery = Post.objects.filter(blog_id=blogquery.pk)[:5]
for p in postquery:
print (blogquery.pk, p.pk)
return render(request, "myapp/page.html", {'blogquery ':blogquery,'postquery ':postquery })
It is surprising how you don't understand that repeatedly assigning to the same variable within a loop will just give you the last value.
But nevertheless, you don't need any of this code. You should just follow the relationship in the template.
#login_required
def page(request):
blogs = Blog.objects.filter(user=user).prefetch_related('post_set')
return render(request, "myapp/page.html", {'blogs ': blogs })
{% for blog in blogs %}
{{ blog.name }}
{% for post in blog.post_set.all|slice:"5" %}
{{ post.content }}
{% endfor %}
{% endfor %}
(You haven't shown your models so I presume the related_name from Blog to Post is called post_set, change as necessary.
UPDATE
That's not correct. You don't need to use for loop. If you need to get the last 5 rows you can do this i.e.:
def page(request):
family= Author.objects.all().order_by('-pk')[:5]
return render(request, "myapp/page.html", {'family':family})
another approach is to limit the results in your template:
{% for item in family %}
{% if forloop.counter < 6 %}
{{ item.pk }}
{% endif %}
{% endfor %}
I am trying to link the author of a post two his profile page, but when I click the on the link, get refered two /profiles/ not to the id of the author.
My views.py looks like this:
def userpage(request, id):
profil = get_object_or_404(UserProfile, pk=id)
context = {'profil': profil}
return render(request, 'gaestebuch/userpage.html', context)
My urls.py looks like this:
url(r'^profiles/(?P<id>[0-9]+)/$', views.userpage, name='userpage')
And the html part where I want to have the link looks like this:
{% for e in latest_eintrage_list %}
<li>
<div id="comment_main">
---> {{ e.author }}
<br>
</div>
{{ e.title }}
<br>
<div id="comment_main">
Comments: {{ e.comments.count }} | {{ e.created_date }} | {{ e.get_typ_display }}
</div>
{% if not forloop.last %}
<hr>
{% endif %}
</li>
{% endfor %}
The part marked with an arrow is the part, where I wanted the link to the author to be.
models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
info = models.CharField(max_length=200, blank = False, default=('keine Angabe'))
class Eintrag(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
NEED = 'ND'
GIVE = 'GV'
TYP_CHOICES = (
(NEED, 'Need'),
(GIVE, 'Give'),
)
typ = models.CharField(max_length=2, choices= TYP_CHOICES, default=NEED)
created_date = models.DateTimeField(default=timezone.now)
I am receving the following error-message:
Reverse for 'userpage' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'gaestebuch/profiles/(?P<id>[0-9]+)/$']
I am glad for any help :)
Inside the {% for e in latest_eintrage_list %} loop, you do have a variable profil. Therefore profil.id is treated as the empty string, and the url tag fails.
You can follow the foreign key from Eintrag.author foreign key to the User model, then follow the one to one field backwards to the UserProfile model:
{{ e.author }}
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'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 %}