Hate to ask such a simple question (I spent hours trying to solve it). I watched tons of tutorials and posts (also on this site) all explain the same thing but I can't access my data on the template.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import YTLink
def ytlinks(request):
queryset = YTLink.objects.all()
return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml')
home.html
{% extends "links/header.html" %}
{% block content %}
{% if queryset %}
queryset is filled
{% else %}
queryset is not filled
{% endif %}
<br> <br> <br>
{% for ytlink in queryset %}
{{ ytlink.link }}><br>
{% endfor %}
My queryset is never filled. What is wrong with this code?
try this:
def ytlinks(request):
try:
queryset = YTLink.objects.all()
except:
queryset = None
return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml')
in home.html
change
{% if queryset %}
to
{% if queryset is not None %}
Related
I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem?
class Post(models.Model):
created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False)
title =models.CharField(max_length=255,blank=False,null=False)
body =models.TextField(blank=True,null=False)
def __str__(self):
return self.title
views.py
from Todolist import models
from django.views.generic import ListView
from django.utils import timezone
class TodayView(ListView):
model = models.Post
template_name ='Todolist/today.html'
def get_queryset(self):
Today_list= models.Post.objects.filter(
created=timezone.now()).order_by('-id')
return Today_list
todaylist.html
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in Today_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
urls.py
urlpatterns=[
path('today/' ,views.TodayView.as_view() ,name='today')
]
use get_context_data to add Today_list to context
ref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['Today_list'] = self.get_queryset()
return context
or you can simply use in template model.name_list in your case it will be post_list instead of today_list
{% extends "Todolist/base.html" %}
{% block content %}
{% for item in post_list %}
<tr>
<td>{{item.title}}</td>
</tr>
{% endfor %}
{% endblock %}
problem is where you want objects that created today, but your queryset filter just right now, not today.
So to achieve today's posts, you can do this:
from django.utils import timezone
def get_queryset(self):
Today_list = models.Post.objects.filter(
created__gte=timezone.now().replace(hour=0, minute=0, second=0),
created__lte=timezone.now().replace(hour=23, minute=59, second=59)
).order_by('-id')
return Today_list
this queryset returns objects that have been created today.
For some reason, my forms.py doesn't view any of the fields, instead, it only shows the 'Add' button and I don't know what to do anymore. I'd really appreciate if someone who knows what they're doing could tell me what I did, or didn't do.
Please note that I'm new to Django, thank you.
Here's my views.py:
from django.shortcuts import render
from django.utils import timezone
from .models import Measurement
from .forms import MeasurementForm
from django.views import generic
class IndexView(generic.ListView):
model = Measurement
context_object_name = 'measurement_list'
template_name = 'index.html'
queryset = Measurement.objects.all()
def new_measurement(request):
if request.method == "POST":
form = MeasurementForm(request.POST)
if form.is_valid():
measurement = form.save(commit=False)
measurement.measurement_date = timezone.now()
measurement.save()
else:
form = MeasurementForm()
return render(request, 'index.html', {'form': form})
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]
forms.py:
from django import forms
from .models import Measurement
class MeasurementForm(forms.ModelForm):
class Meta:
model = Measurement
fields = ('measurement_value', 'measurement_unit')
index.html:
{% extends "base.html" %}
{% block content %}
<h1>Climate Measurement Tool</h1>
<h2>Add a new measurement</h2>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save">Add</button>
</form>
<h2>Measurements</h2>
{% if measurement_list %}
<ul>
{% for measurement in measurement_list %}
<li>
<p>{{ measurement }}</p>
</li>
{% endfor %}
</ul>
{% else %}
<p>No measurements yet</p>
{% endif %}
{% endblock %}
The new_measurement() view correctly initializes a form instance and passes it to the template.
Unfortunately, that view is never called.
urls.py defines only one url, handled by IndexView.as_view(), which does not pass a form instance to the template.
I'm just built my django project but have some problem. I want to display title that is in Academy. When I run python manage.py runserver everything is okay but the title is not displayed. I don't know what the problem is.
class.html
{% extends "base.html" %}
{% block content %}
<div>
<div style="margin-top: 200px;">
</div>
{% for academy in academys %}
<h3>{{ academy.title }}</h3>
{% endfor %}
</div>
{% endblock %}
urls.py
...
url(r'^academy/class', 'academy.views.class', name='class'),
views.py
from django.shortcuts import render, Http404
from .models import Academy
def class(request):
template = 'academy/class.html'
try:
academys = Academy.objects.all()
context = {'academy': academys}
except Academy.DoesNotExit:
raise Http404
if request.user.is_authenticated():
return render(request, template, context)
else:
return HttpResponseRedirect("/account/login/")
models.py
...
class Academy(models.Model):
title = models.CharField(max_length=50)
def __unicode__(self):
return self.title
Your context dictionary key is incorrect. Instead of
context = {'academy': academys}
type
context = {'academys': academys}
You've passing 'academy' in your context not 'academys'
context={'academys ': academys}
I am working on extending the webapp we're left off with after completing the official Django Tutorial.
One of the functionalities I am looking to add is the ability for users to add polls themselves.
I am struggling with getting the page to process the data and then redirect to the index page ('/polls').
When I submit a new poll as a logged in user, I am returned to my index page, which is supposed to show most recently published polls, or in the event of no polls, the message "No polls are available."
For some reason, I always see "No polls are available", but once I click to the index page via a link on the site, it displays all of my polls, including my most recently created one, data intact!
Any thoughts here? I think I have included the relevant info below but happy to supply more. Thanks in advance for any help/advice.
views.py
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Poll.objects.order_by('-pub_date')[:15]
#login_required
def add_poll(request):
ChoiceFormSet = formset_factory(ChoiceForm, extra=3, min_num=2, validate_min=2)
if request.method == 'POST':
form = PollForm(request.POST)
formset = ChoiceFormSet(request.POST)
if all([form.is_valid(), formset.is_valid()]):
poll = form.save()
for inline_form in formset:
if inline_form.cleaned_data:
choice = inline_form.save(commit=False)
choice.question = poll
choice.save()
return render(request, 'polls/index.html', {})
else:
form = PollForm()
formset = ChoiceFormSet()
return render(request, 'polls/add_poll.html', {'form': form, 'formset': formset})
add_poll.html
{% extends 'polls/base.html' %}
{% block title %}Add Poll{% endblock %}
{% block body_block %}
<form role="form" id="poll_form" method="post" action="{% url 'polls:add_poll' %}">
<h2 class="form-signin-heading">Add a Poll</h2>
{% csrf_token %}
<table>
{{ form }}
{{ formset }}
</table>
<br/>
<button class="btn btn-primary" type="submit" name="submit">Create Poll</button>
</form>
{% endblock %}
index.html
{% extends 'polls/base.html' %}
{% block body_block %}
{% if latest_question_list %}
<ul>
{% for poll in latest_question_list %}
<li>{{ poll.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% endblock %}
urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^add_poll/$', views.add_poll, name='add_poll'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
url(r'^profile_page/$', views.ProfileView.as_view(), name='profile_page'),
url(r'^edit_profile/$', views.edit_profile, name='edit_profile'),
)
When you save your form you are not redirecting.
Your are returning 'polls/index.html' with empty polls data, that's why you always get "No polls are available". But this is very incorrect, you must follow the Post/Redirect/Get (PRG) pattern, so instead of:
return render(request, 'polls/index.html', {})
do this:
return HttpResponseRedirect(reverse('polls:index'))
You don't do any redirect right now, you are just rendering your index template with an empty context (that's why you don't see anything). To redirect, you need to use HttpResponseRedirect when your form is valid.
So, please change line:
return render(request, 'polls/index.html', {})
(just over the else) to
return HttpResponseRedirect(reverse('index'))
I finally figured it out. I had to change my html form to this:
<form method="POST" action="{% url 'new_beam:beam_diagram' beam_id=1 %}" enctype="multipart/form-data">
This is my index.html file:
{% extends "base_site.html" %}
{% block content %}
{% if info %}
<ul>
{% for object in info %}
{{ Hello }}
{% endfor %}
</ul>
{% else %}
<p>No objects are available.</p>
{% endif %}
{% endblock %}
This is my views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from notendur.models import *
from django.views import generic
class IndexView(generic.ListView):
template_name = 'notendur/index.html'
context_object_name = "info"
def get_queryset(self):
"""Return the last five published polls."""
return Information.objects.all()
This is my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Information(models.Model):
title = models.CharField(max_length = 200)
body = models.TextField()
date = models.DateTimeField()
def __unicode__(self):
return self.title
class InformationChild(models.Model):
information = models.ForeignKey(Information)
child_text = models.CharField(max_length = 200)
def __unicode__(self):
return self.child_text
When I start the server, however, nothing appears. This has to be some url-link issue, because the else clause doesn't even activate. Perhaps you want urls.py as well?
Let me know if you need further information.
The error is not in the use of info, it's in what's inside the for loop: {{ Hello }} is not an item in the context. Use {{ object.title }}, for example.