Django displaying data from database in template - python

I'm having some trouble displaying data from my database on the template in django
model:
class CityInfo (models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
landmark_type = models.CharField(blank=True, max_length=30)
business = 'Business'
student = 'Student'
tourist = 'Tourist'
def __str__(self):
return self.name
relevant view:
def itemget(request):
data=CityInfo.objects.all()
return render(request,'CityApp/infopage.html', {'data': data})
relevant url:
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
infopage.html:
<ul>
{% for item in data %}
<li>
<h1>{{ item.name }}</h1>
</li>
{% endfor %}
<ul>
The above html results in a blank list and I have no idea why.

Try changing views.py to the following:
def itemget(request):
data = CityInfo.objects.all()
context={
'data': data
}
return render(request, "CityApp/infopage.html", context)

Try this :
def __str__(self):
return "%s" % self.name
I'm not sure because I'm on my old smartphone.
Otherwise, your def __str__ is well indented in your class ?
Are you using Python 2 or Python 3 ? str if for Python 3. Else you have to use __unicode__
EDIT :
From you urls.py file, you have :
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
Remove your template_name part which is already in your view and don't forget to add ^ before itemget
url(r'^itemget/$',views.itemget ,name='itemget'),

Related

How to append queried objects from Django database?

I have a model with 2 fields for numbers. I am trying to query those numbers and append them to each others. How do I do that? How do I work with queried objects?
This is Model
class Post(models.Model):
title = models.CharField(max_length=100)
num1 = models.IntegerField(blank=True,default=0)
num2 = models.IntegerField(blank=True,default=0)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('diary:post-detail', kwargs={'pk': self.pk})
This is view (here I am trying to query and work with queried objects)
def home(request):
a = Post.objects.values('num1')
b = Post.objects.values('num2')
result = a + b
context = {
'result': result,
}
return render(request, 'diary/home.html', context)
This is a working part of my template
{% for x in result %}
<p> {{ x }} </p>
{% endfor %}
This is the error I get
TypeError at /
unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'
C:\Users\detal\Coding\Trading Diary3\TradingDiary\diary\views.py, line 11, in home
result = a + b
The return of your query will be dictionary. To add both query's you can try
result = q.union(b)
for a much more cleaner look
records = query1 | query2
If you don't want duplicates, then add .distinct()
records = (query1 | query2).distinct()
if you want specific field only you can try
Post.objects.all().values_list(
"num2").union(Post1.objects.all().values_list("num1"))
or if it is from same table
Post1.objects.all().values_list("num1","num2"))
I solved it. Here's my view code:
def home(request):
x = Post.objects.all().values_list("num1","num2")
array = []
for i in x:
y = i[0] + i[1]
array.append(y)
context = {
'posts': Post.objects.all(),
'array':array,
}
return render(request, 'diary/home.html', context)
and template code:
{% for i in array %}
<p> {{ i }} </p>
{% endfor %}
The output is the list of appended numbers of num1 and num2. There was also problem for me while solving - you don't need to "return" the for loop result in views. It works only without it

Reversing a url with two slugs

I am trying to understand a basic example of adding both categories and detail slugs from 2 related classes.
The /categories URL works, but I can't make /categories/detail work. I get the following error:
Reverse for 'categorydetail' with arguments '('onedetailfromcategory',)' not found. 1 pattern(s) tried: ['(?P<cat_slug>[^/]+)/(?P<det_slug>[^/]+)$']
Here are my files:
#Models:
class Categories(models.Model):
name = models.CharField(max_length=50,unique=True)
cat_slug = models.SlugField(max_length=100,unique=True)
def __str__(self):
return self.name
class Details(models.Model):
title = models.CharField(max_length=100)
det_slug= models.SlugField(max_length=100,unique=True)
categorie = models.ForeignKey('Categories', on_delete=models.CASCADE, related_name="Categories")
def __str__(self):
return self.title
#Views:
class ListCategorie(DetailView):
model = Categories
slug_field = 'cat_slug'
context_object_name = "listcategories"
template_name = "show/categories.html"
class DetailCategorie(DetailView):
model = Details
slug_field = 'det_slug'
context_object_name = "categorydetail"
template_name = "show/detail.html"
#Urls:
path('<cat_slug>', views.ListCategorie.as_view(), name='listcategories'),
path('<cat_slug>/<det_slug>', views.DetailCategorie.as_view(), name='categorydetail'),
#Categories.html
{% for x in listcategories.Categories.all %}
<p> {{x.title}} </p>
<li>URL</li>
{% endfor %}
Your URL pattern is
path('<cat_slug>/<det_slug>', views.DetailCategorie.as_view(), name='categorydetail'),
Therefore you need to provide cat_slug and det_slug when reversing the URL:
{% url 'categorydetail' x.categorie.cat_slug x.det_slug %}

Django view with get context not working

Have a quick question. Trying to use a relational model in one DetailView. However, no matter what I try the data does not display. I've tried a few versions of template tags to no avail.
html
{% for parts in relatedparts %}{{ parts.name }}
</div>{% endfor %}
views.py
class ErrorCodeView(DetailView):
context_object_name = 'error_code_details'
model = models.ErrorCodes
template_name = 'error_code_details.html'
def get_context_data(self, **kwargs):
# xxx will be available in the template as the related objects
context = super(ErrorCodeView, self).get_context_data(**kwargs)
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
return context
models.py
class ErrorCodes(models.Model):
name = models.CharField(max_length=256)
description = models.CharField(max_length=400)
instructions = models.CharField(max_length=256)
PartsNeeded = models.CharField(max_length=120, default='')
usercomments = models.CharField(max_length=400, default='', blank=True)
relpic = models.ImageField(upload_to='media/',blank=True)
relpictwo = models.ImageField(upload_to='media/',blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("errorcodes:errorcodeview",kwargs={'name':self.name})
class RelatedParts(models.Model):
name = models.CharField(max_length=256)
related_error_code = models.ForeignKey(ErrorCodes, on_delete=models.PROTECT)
def __str__(self):
return self.name
You don't need to do this at all. You can follow the relationship in the template.
{% for part in object.relatedparts_set.all %}{{ part.name }}{% endfor %}
You don't need any code in the view to enable this.
could it be that "name=self.get_object()" should be "name=self.get_object().name" ?
You currently have:
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
but that is probably producing an empty queryset.

How can I display content in a model object in template?

How can I display country, and city of an UserType1 object in template?
class UserType1(models.Model):
user=models.OneToOneField(User,parent_link=True,primary_key=True)
country = models.CharField(max_length=50)
city = models.CharField(max_length=50)
def __str__(self):
return str(self.user)
def get_country(self):
return self.country
def get_city(self):
return self.city
I have the below in views.py
def profile(request,userid):
basic_info = User.objects.get(pk=int(userid))
profile = UserType1.objects.filter(user=int(userid))
template_name = 'users/profile.html'
return render(request, template_name, {'userid':userid,'basic_info':basic_info, 'profile':profile})
and the following in template
{% if profile %}
{{ profile.get_city }}
{{ profile.city }}
{% endif %}
Neither worked. Thanks!
It looks like you are accessing properties on a queryset, rather than a model instance, as you haven't called get on UserType1.
Try:
profile = UserType1.objects.get(user=int(userid))
As an aside though, a small change would simplify your code a little:
user = models.OneToOneField(User, parent_link=True, primary_key=True, related_name='profile')
...
basic_info = User.objects.get(pk=int(userid))
profile = basic_info.profile

I can't display detail_page with absolute_url?

When I got this error I understood that I didn't learn URL -HTML- views-model relationship. First, let me show my codes.
This is my views.py:
def category_detail(request, category_name):
links = Link.objects.filter(category__name=category_name)
return render_to_response("category_detail.html", {"links":links}, context_instance=RequestContext(request))
This is models.py:
class Category(models.Model):
name = models.CharField(_("Category"), max_length=255)
user = models.ManyToManyField(User)
def __unicode__(self):
return "%s %s" %(self.user, self.name)
def admin_names(self):
return ', '.join([a.username for a in self.user.all()])
admin_names.short_description = "User Names"
def get_absolute_url(self):
return "/category/%s" % self.name
class Link(models.Model):
user = models.ForeignKey(User)
posted_at = models.DateTimeField(auto_now_add=True)
url = models.URLField()
title = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(Category)
def __unicode__(self):
return "%s %s %s" %(self.url, self.title, self.category)
This is HTML page:
<div id="profilemenu">
index<p>
{% for category in categories %}
<p>{{category.name }}
{% endfor %}
<p>
</div>
and urls.py:
url(r'^category/(?P<category_name>.*)', 'link.views.category_detail', name="category_detail"),
When I click a category name to open category_detail.html, the URL in browser is like :
http://127.0.0.1:8000/category`/
I can't get categoryname. Please can you tell me my stupid mistake? :\ Thanks for time.
If you are using the namespace in your urls you would need to reference it without quotes in the template.
<p>{{category.name }}
Note: You'll want to ensure the namespace is fully qualified. If you have embedded namespaces you should separate them with :.
<p>{{category.name }}
Hopefully this solves your problem.
You should follow get_absolute_url reference:
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('link.views.category_detail', args=[str(self.name)])
html
{{ category.name }}

Categories

Resources