I have some problems to get the content out of the django database.
I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff.
So to come to my problem I initalized my modules in models.py
from django.db import models
class Aboutme(models.Model):
author = models.CharField(max_length=30)
...
This works because I could add content to the database.
So there is no mistake.
Now in the views.py
from django.shortcuts import render
from portfolio.models import Aboutme
def portfolio_index(request):
aboutme = Aboutme.objects.all()
context = {'aboutme': aboutme}
return render(request, 'portfolio_index.html', context)
So finally in my HTML file, called portfolio_index.html, I call the content via
<h1>{{ aboutme.author }}</h1>
I guess it's right. But the content of author doesn't showup, so what did I miss?
I can call static files via django, so couldn't be something wrong with django...
Can anyone help.
Thanks in advance.
I think that you need to use a for loop to show "aboutme" because with "aboutme = Aboutme.objects.all()" you query a list of elements.
{% for aboutme_item in aboutme %}
<h1>{{ aboutme_item.author }}</h1>
{% endfor %}
Related
I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the ActivityPeriod(model) of that user. Please check my code for the clarity:
Here is my code:
views.py
from .models import User,ActivityPeriod
def call_response(request):
user = User.objects.all()
return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})
Test/list.html
{% for user in users %}
'real_name': {{ user.real_name}}},
'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
{{ activity.start_time }}
{% endwith %}
{% endfor %}
But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'
What is the correct way? Can anyone please share it with me.
Django template don't understand the filter action of Model. This part shoud be in view.
activity=activityperiod.objects.get(id =user)
You should prepare your data and manipulate them before sending to template (a dictionary may help you). And remember that result of action "User.objects.all()" is a list.
views.py
def call_response(request):
user = User.objects.filter(user=request.user)
activityperiod = activityperiod.objects.get(user=user)
context={'user':user,'activityperiod':activityperiod}
return render(request, "Test/list.html",context})
Test/list.html
'real_name': {{ user.real_name}}
'activity_periods':{{ activityperiod.start_time }}
Your question suggests that you think you can a function in the templates like a normal function (ie activityperiod.objects.get(...)).
You can't, the templating system is not made like this (for security reasons amongst others).
You should do something like, in your models:
def call_response(request):
# ! first() not "all()" (if > 1 user, you'll have problem)!
user = User.objects.first()
activityperiod = activityperiod.objects.get(user=user)
return render(request, "Test/list.html",
{"users":user ,"activityperiod":activityperiod})
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates).
Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it).
1) The QuerySet isn't loading at all in the HTML file.
I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page.
2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed).
I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere?
Thanks for the help, I appreciate it!
Here are my local files:
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
]
views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
post_list.html
<html>
<head>
<title>Dina's blog</title>
</head>
<body>
<div>
<h1>Dina's Blog</h1>
</div>
{{ posts }}
</body>
</html>
you cant just use the query_list like that in the template, you need to loop through it in the template and it will show all posts titles so your template will be like this
{% for post in posts %}
<p>{{post.post_title}}</p>
{% endfor %}
i recommend following this blog
I don't know if you have already done it or not, but when actually creating the posts you will also have to save it. So for example:
Example form.py
from django import forms
class createPostForm(forms.Form):
title = forms.CharField(required = True)
detail = forms.CharField(required = True)
Example views.py
import models
def createPost(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
title = form.cleaned_data.get('title')
detail = form.cleaned_data.get('detail')
newPost = models.Post(title = title, detail = detail)
newPost.save()
return redirect('blog/post_list.html')
Otherwise you won't be able to access it, since your website will take the inputs in and it will look like a post was created if the fields were valid, but your posts won't actually get created and your database will be empty! Also get a database viewer so that you can see if the entries are actually there.
I'm working on a site to better learn the Django-framework. I've currently set up views and links to template files to display content on the main page. In my views.py file I've added a dictionary that is displays the dict value for each key in in the index.html page when it gets rendered:
views.py:
def Index(request):
projectmessage = {
"projectMessage":"This is text from a dictionary value. written in views.py",
"projectTitle":"Title from dict",
"projectText": "Text from dict",
}
return render(request,'wbdev/index.html', context=projectmessage)
Relevant lines in index.html:
<h3>{{ projectTitle }}</h3>
<p>{{ projectMessage }}</p>
I'm wondering if this could be made visible on the django admin page so that I can change the dict text directly from the GUI. Could this be done or am I way off in the sense that this is not the intended for the django admin page? From what I've red django admin parses the models.py file to set up text fields and buttons. I've followed the official django tutorial and some of the "How to tango with django" book but I cant wrap my head around how I should proceed in getting the functions that I want.
I'm sorry for the noob question. I will return to my books and I will probably understand how this works down the line. If anyone could help me with an explanation of how I can achieve this I will be most grateful.
Thank you.
You'll probably want to create a Model for Projects, so projects can be saved to a Database and easily displayed in the Admin.
Inside models.py include the following:
class Project(models.Model):
message = models.CharField(max_length=20)
title = models.CharField(max_length=20)
text = models.CharField(max_length=20)
Inside admin.py if you register the model it should then appear in the admin
from dajngo.contrib import admin
from .models import Project
admin.site.register(Project)
Finally for your index in views.py you'll want to query the database for the project objects in question before rendering them to the template
def index(request):
projects = Project.objects.all()
return render(request,'wbdev/index.html', context={'projects': projects})
Inside your template you can then iterate over all the projects in your database like
{% for project in projects %}
{{ project.message }}
{{ project.title }}
{{ project.text }}
{% endfor %}
So I'd like to think what I'm doing is fairly common. I'm attempting to display a result set using Django. I have looked online for a while and here is what I've come up with:
models.py{
from django.db import models
from django.conf import settings
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep)
sold_on = models.DateField("Sold On")
}
sales_view.py{
from salesteam.models import SalesRep, Sales
from django.views.generic import ListView
class SellerHome(List View):
model = SalesRep
template_name = 'production/sales.html'
#property
def rep_sales(self):
return Sales.objects.filter(SalesRep=self)
}
sales.html{
<div id="total-sales">
{% for sale in SellerHome.rep_sales%}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</div>
}
For the sake of completeness I even tried writing just the property out as Sales.objects.all() but still no luck. Thanks for taking a look as I'm fairly new to HTML, Django, and Python. Any help on what I'm doing wrong would be much appreciated. Let me know if you have any questions :)
I'm not sure what tutorial you've followed, but there is a lot of errors in your code... I'm assuming you would like to display all Sales for the logged in user?
In this scenario, I would change the model slightly to add a related_name to Sales foreign key to SalesRep:
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep, related_name='sales')
sold_on = models.DateField('Sold On')
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.related_name
And I would change the views to use DetailView:
from django.views.generic import DetailView
class SellerDetailView(DetailView):
model = SalesRep
template_name = 'production/sales.html'
context_object_name = 'seller'
def get_object(self):
return self.request.user
Docs on DetailView — https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-display/#detailview
<div id="total-sales">
<ul>
{% for sale in seller.sales.all %}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</ul>
</div>
First, I'd recommend avoiding class based views, at least as you are learning Django, since they are not really necessary and needlessly complicated for what you are doing.
Anyway, to answer your question using class-based views, your problem is in your template and your view. You'll want to put your rep_sales logic in a get_queryset, set the model to be Sales, not SalesRep, and then reference object_list in the template. More info.
However, I'd instead recommend writing a normal, function-based Django view. Something like this might get you started:
def view_all_sales(request):
my_sales_rep = SalesRep.objects.get(request.user)
all_my_sales = Sales.objects.filter(seller=my_sales_rep)
return render(request, "production/sales.html", {
"sales": all_my_sales
})
I asked in past time about how generate an url with similar caracterist starting from an ID you said me that is better use slugs to do that. On this time I wanna generate dinamics urls with slugs. My objective is obtain this result:
I have five products that I named cards in models.py (Ysera, Neltharion, Nozdormu, Alexstrasza, Malygos). I need the respective url of each of the products:
localhost:8000/card/ysera
localhost:8000/card/neltharion
localhost:8000/card/nozdormu ... etc.
I try to generate these urls but i dont know if I made a good applying of commands, either I don't know how I can specify the id card like the main name of the card (ysera, neltharion...). I was trying to follow an answer posted here in this community a little blind and this is my "reconfiguration":
Here my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
def shop(request):
tarj = card.objects.filter(status=True)
ctx = {'tarjetas':tarj}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
def singleCard(request, slug, id):
try:
tarj = card.objects.get(slug=slug, id=id_tarj)
except ObjectDoesNotExist:
tarj = get_object_or_404(card, id=id_tarj)
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
My urls.py (I have an urls.py by app and the main urls.py):
url(r'^card/(?P<slug>[-\w]+)/(?P<id_tarj>\d+)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
My models.py:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.nombre
My common template for all cards:
{% extends 'base.html' %}
{% block title %} Tarjeta {{card.nombre}} {% endblock %}
{% block content %}
<h1>{{ card.nombre }}</h1><br>
<p> {{ card.descripcion }}</p>
{% endblock %}
I don't know if my slug building in views.py was find, I'm convinced that the urls.py is bad but i don't know how build it?
please excuse me if I edit my own question to prolong it, Recently I'm trying to learn django by my side and I have many gaps in my learning
apologizeme in advance my extensive question and if I overlook something.
Thanks!!
This line:
tarj = card.objects.get(slug=slug, id=id_tarj)
tries to load a card object where the id field is set to is id_tarj and the slug field is set to slug. Your model does not have a field named slug. You will need to add one.
A good candidate for it would be a SlugField - https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield
You will need to make sure that your slug field contains a proper value in each case.