I'm trying to get my head around Django and understand how I can show results of Python functions in Django's templates. As a simple example, let's say I have a model with a list of questions and I want to use a function to return the number of questions and for this result to be shown in a template. How can I do it?
I tried to do it below but it doesn't work!
Thanks in advance
models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
views.py
from django.shortcuts import render
from django_app import models
from django.views.generic import ListView
from django_app.models import Question
class TestListView(ListView):
model = Question
context_object_name = 'test_details'
def Test(self):
return Question.objects.count()
urls.py
from django.urls import path
from django_app import views
from django_app.views import TestListView
app_name = 'django_app'
urlpatterns = [
path('',TestListView.as_view(), name='Test'),
]
question_list.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for item in test_details %}
{{Test}}
{{item.question_text}}
{% endfor %}
</body>
</html>
You can override the get_context_data method of your view to add extra variable into your context
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Test'] = Question.objects.count()
return context
You can also get the count of the questions without having to alter the context. You can get it from the queryset
{{ test_details.count }}
Related
I am a beginner in Django. I recently came across a problem: When I am trying to fetch objects, it is saying
DoesNotExist: Value matching query does not exist.
I searched the web but still I got no clue as to why this is happening.
My models.py
from django.db import models
class Value(models.Model):
eq_input = models.CharField(max_length=20, default='x**2 + y**2')
color = models.CharField(max_length=20, default='Magma')
My forms.py
from django import forms
from .models import Value
class ViewForm(forms.ModelForm):
Equation = forms.CharField(max_length=20, label='Equation')
Color = forms.CharField(max_length=20,label='Color')
class Meta:
model = Value
fields = {
'Equation',
'Color'
}
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Value
from .forms import ViewForm
def home_view(request):
if request.method == "POST":
form = ViewForm(request.POST)
if form.is_valid():
form.save()
else:
form = ViewForm()
context = {
'form': form
}
return render(request, "home.html", context)
My home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>3D Graph Plotter</title>
</head>
<body>
<center><h1>This is a 3D plotter</h1></center>
<center>
<form action="." method="POST">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Save" />
</form>
</center>
</body>
</html>
and my urls.py
from django.contrib import admin
from django.urls import path, include
from equation.views import eq, home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='hv')
]
Is there something I am missing or something is wrong there? Can you point that out?
the problem is inside your forms.py try this
from django import forms
from .models import Value
class ViewForm(forms.ModelForm):
class Meta:
model = Value
fields = ['eq_input','color']
and if you want to add label
class Value(models.Model):
eq_input = models.CharField(max_length=20,verbose_name='Equation', default='x**2 + y**2')
color = models.CharField(max_length=20,verbose_name='Color' ,default='Magma')
after that do not forget to run makemigrations and migrate.
I am learning to create a blog website using django. I encountered an issue while calling my model method inside template file. The site is not displaying contents inside the body. It was working fine when i used article.body but its not working when i use article.snippet.
models.py file:-
...
from django.db import models
class Article(models.Model):
title = models.CharField(max_length = 100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]
...
articles_list.html file:-
...
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Articles</title>
</head>
<body>
<h1>Articles List</h1>
<div class="articles">
{% for article in articles %}
<div class="article">
<h2>{{article.title}}</h2>
<p>{{article.body.snippet}}</p>
<p>{{article.date}}</p>
</div>
{% endfor %}
</div>
</body>
</html>
...
views.py file:-
...
from django.shortcuts import render
from django.http import HttpResponse
from .models import Article
def articles_list(request):
articles = Article.objects.all()
return render(request, 'articles/articles_list.html', {'articles': articles})
...
There is no error displayed in code but still there is no output inside body tag.
You can make use of a built-in Slice filter in your template
like this
<p<{{ article.body|slice:":50" }}</p>
But for some reason, if you want to call any model methods from the templates you can use #property decorator to access it.
like this
class Article(models.Model):
...
#property
def snippet(self):
return self.body[:50]
You can just call
<p>{{article.snippet}}</p>
instead of:
<p>{{article.body.snippet}}</p>
because snippet is a method in the same model so you can call it directly, and body is not a ForeignKey
I was learning Django but I got in some trouble, Please Help!
There is no error on either server or webpage.
My HomePage(index.html) is working fine but DetailPage(post.html) is rendering blank.
blog/views.py
from .models import Article
from django.views import generic
class HomePage(generic.ListView):
template_name = 'blog/index.html'
queryset = Article.objects.filter().order_by('date')
context_object_name = 'Article_list'
class DetailPage(generic.DetailView):
template_name = 'blog/post.html'
model = Article
blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.HomePage.as_view(), name='home'),
path('<int:pk>/', views.DetailPage.as_view(), name='detail')
]
blog/models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def snippet(self):
return self.body[:200]
blog/templates/blog/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="margin:10%">
{% for Article in Article_list %}
<h1 align="center" style="padding-bottom:20px">
{{Article.title}}
</h1>
{{Article.date}}<br><br>
{{Article.snippet}}...<br><hr>
{% endfor %}
</body>
</html>
blog/templates/blog/post.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<h1>{{Article.body}}</h1>
{{Article.body}}<br>
{{Article.body}}
</body>
</html>
NOTE: other elements of the webpage are rendering except Python variables i.e, {{Article.body}}, {{Article.body}}, {{Article.body}}
Change {{Article.body}} to {{object.body}}
You haven't set article as a context in your DetailView so the template won't recognise article. If you wanted to use article instead of object you'd have to set it as context, but that's completely unnecessary.
I'm creating Django forms using model forms because u I wanted the forms to be created automatically, but when I created this code the forms do not appear in the index.html page
models.py
from django.db import models
class BaseCase(models.Model):
base_case_name = models.CharField(primary_key=True, max_length=255)
version = models.TextField(blank=True, null=True)
default = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'base_case'
forms.py
from django import forms
from SFP.models import *
class BaseCaseForm(forms.ModelForm):
class Meta :
model = BaseCase
fields='__all__'
views.py
from django.shortcuts import render,redirect
from .models import *
from .forms import *
def addbc(self, request):
bcform=BaseCaseForm(request.POST)
bcform.save()
basecasename = bcform.cleaned_data['post']
version = bcform.cleaned_data['post']
default = bcform.cleaned_data['post']
bcform = BaseCaseForm()
return redirect('index.html')
args = {'bcform':bcform,
'basecasename': basecasename,
'version': version,
'default' :default}
return render(request, 'index.html', args)
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ bcform }}
<input type="submit" value="add">
</body>
</html>
and i think that this is important too
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^$', views.addbc),
]
I was expecting the form fields to be generated automatically but they don't appear!
You can try CreateView which will create forms for your model. Find more about it in the docs
In your case, create a view like this:
views.py
class BaseCaseCreate(CreateView):
model = BaseCase
template_name = 'index.html'
success_url = reverse_lazy('app:home')
fields = ('base_case_name','version','default')
index.html
<!DOCTYPE html>
<html>
<head>
<title>S&FP</title>
</head>
<body>
<h1>Forms</h1>
{% csrf_token %}
{{ form }}
<input type="submit" value="add">
</body>
I hope this helps.
I wrote in results.html,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Score</title>
</head>
<body>
<h1>Score</h1>
<h2>Your score is {{ scoreresults.result }}</h2>
</body>
</html>
But now, this part {{ user.result }} of <h2>Your score is {{ user.result }}
</h2> is blank in my browser.
I wrote in models.py
from django.db import models
from django.contrib.auth.models import User
class ImageAndUser(models.Model):
user = models.ForeignKey("auth.User", verbose_name="imageforegin")
result = models.CharField(max_length=64, null=True)
def __str__(self):
return '{} {}'.format(self.user,self.id)
So,ImageAndUser model has result data.
I cannot understand how to designate ImageAndUser model in results.html.
Furthermore,
I wrote in serializer.py
from .forms import UserImageForm
from rest_framework import serializers
from .models import ImageAndUser
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = ImageAndUser
fields =(
'image',
'result',
'user',
'id',
)
read_only_fields = (
'user',
)
def create(self, attrs):
attrs['user'] = self.context.get('request').user
print(attrs)
return super(ImageSerializer,self).create(attrs)
Now,I wrote in views.py
def scoreresults(request):
d = {
'scoreresults': ImageAndUser.objects.result(),
}
return render(request, 'registration/accounts/results.html', d)
in urls.py
from django.conf.urls import url
from . import views
from django.views.generic import TemplateView
urlpatterns = [
url(r'^scoreresults$', TemplateView.as_view(template_name='registration/accounts/results.html'),
name='tcresults'),
]
But it did not work.
So,how can I fix this?
You have a lot of bits here but none of them are linked up to one another.
The main problem is your url; it does not point to your view. Instead of using a TemplateView declared in the url itself, you should point it to the view function you have defined:
url(r'^scoreresults$', views.scoreresults, name='tcresults')
You don't seem to be using the serializer at all; and you don't need it.