Django Tutorail - Part 3 - Cannot Access Model Values - django

I did the entire django site tutorial and I am now trying to redo it without consulting the tutorial, to see which parts I remembered and which I did not.
I can successfully load a template when I go to the correct url.
post_list.html
<h1>The Blogs Index Page</h1>
<h2> Posts </h2>
{% for post in latest_post_list %}
<p> {{ post.title }}<p>
{% endfor %}
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
pub_date = models.DateTimeField()
def __str__(self):
return self.title
Relevant views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from .models import Post
def index(request):
latest_post_list = Post.objects.order_by('pub_date')
context = {'latest_post_list': latest_post_list}
return render(request, 'blog/index.html', context)
The page only displays the H1 and H2 tag information, everything else is just blank. I have a suspicion that latest_post_list does not exist.
When using the shell, I am able to...
>>> from blog.models import Post
>>> Post.objects.all()
[<Post: First Post>, <Post: Second Post>, <Post: Third Post>]
So the titles exist. I am at a loss to why I can not access my post.titles from the Template.

Related

Django submit form POST not valid

I am attempting to submit a form to populate the database. I can't get the POST working. It doesn't look valid, but I can't figure out what I need to do to correct it.
I have put some debugging on to see what happens when I click submit & the POST gets sent. I can't figure out how to send created_at or created_by. I assume these are the reason why the POST is not valid and the database is not populating.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class Order(models.Model):
order_name = models.CharField(max_length=100, unique=True, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING)
def __str__(self):
return self.order_name
class Ce_Base(models.Model):
ce_hostname = models.CharField(max_length=15)
new = models.BooleanField()
location = models.TextField()
order_reference = models.ManyToManyField(Order)
forms.py
from django.forms import ModelForm
from .models import Order
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ['order_name']
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import Order
from .models import Ce_Base
from .forms import OrderForm
#login_required
def home(request):
form = OrderForm()
if request.method == 'POST':
form = OrderForm()
form.instance.created_by = request.user
print(request.POST)
if form.is_valid():
form.save()
context = {
'order': Order.objects.all(),
'form': form,
}
return render(request, 'orchestration/order_create.html', context)
#login_required
def orderprocessing(request):
context = {
'ce_base': Ce_Base.objects.all()
}
return render(request, 'orchestration/order_processing.html', context)
html
{% extends "orchestration/base.html" %}
{% block content %}
<h1>Input Form</h1>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" >
</form>
<h1>Orders</h1>
{% for each_order in order %}
<p>Order Name: {{ each_order.order_name }}</p>
<p>Created On: {{ each_order.created_at }}</p>
<p>Created By: {{ each_order.created_by }}</p>
{% endfor %}
{% endblock content %}
Here is my terminal output when i hit the submit button
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
May 12, 2022 - 16:15:40
Django version 4.0.2, using settings 'dcn_automation.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
<QueryDict: {'csrfmiddlewaretoken': ['MQVrDwqyT8Y6ARAF9CCyuCSwavz5BAVmi2GdxMgvxFlHmiD1M8Cq6y0VRVummR82'], 'order_name': ['test']}>
If don't pass the data in the form, the validation fails.
form = OrderForm(request.POST)

Display data from a database in a HTML page using django views

I have a problem with creating a view with data from the database. I created a view that should download data from videos (var films) and display them, unstable
views.py
from .models import Films
def index(request):
filmy = Films.objects
return render(request, 'films/index.html',{'filmy':filmy})
index.html
<h1>Films</h1>
{% for film in films.all %}
{{filmy.summary}}
<br>
{% endfor %}
models.py
class Films(models.Model):
image = models.ImageField(upload_to='images/')
summary = models.CharField(max_length=200)
def __str__(self):
return self.summary
I only have a blank page.
Your views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Films
# Create your views here.
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
In index.html
{% for film in films %}
<p> {{film.summary}} </p>
{% endfor %}
I hope that helps.

Using Django ModelForm for one-to-many relationships

I'm trying to extend the Django (version 2.0) tutorial so that it uses ModelForm to create a question with a least one or two choices. I have two models Question and Choice which have a one-to-many relationship. What do I need to do to my model, form, views, and template to generate a field(s) for choice? I've seen a few posts suggesting Inline but that seems like it's only for admin pages.
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
polls/forms.py
from django.forms import ModelForm
from .models import Choice, Question
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ['question_text', 'pub_date', 'choice']
polls/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic
from .forms import QuestionForm
from .models import Choice, Question
def create_question(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
question_text = form.cleaned_data['question_text']
pub_date = form.cleaned_data['pub_date']
question = Question(question_text=question_text, pub_date=pub_date)
question.save()
return HttpResponseRedirect(reverse('polls:index'))
else:
form = QuestionForm()
return render(request, 'polls/create-question.html', {'form': form})
polls/create-question.html
{% extends 'polls/base.html' %}
{% block scripts %}{% endblock scripts %}
{% block content %}
<div class="container">
<h1>Create question</h1>
<form action="{% url 'polls:create-question' %}" method="post">
{% csrf_token %}
{{ form }}
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Create">
</form>
</div>
{% endblock content %}
To use ModelForm you should add a ManyToManyField to the Question model in order to connect choices with the certain question. For example like choices = models.ManyToManyField(Choice, on_delete=models.CASCADE).

Django Template not displaying model data, showing blank page

Django Template not displaying model data, showing blank page
...Have a look at it:
models.py
class appointment(models.Model):
patient_name1= models.ForeignKey('identity')
appoint_date= models.DateTimeField('Appoinment time and date')
patient_info= models.TextField()
fees= models.CharField('Fees',max_length=100,blank=True)
class Meta:
verbose_name = 'Appointment Detail'
verbose_name_plural = 'Appoinment Details'
ordering = ['appoint_date']
def __str__(self):
return '%s (%s)' % (self. patient_name1, self.appoint_date)
views.py
from django.shortcuts import render
from .models import identity, appointment
def index(request):
return render(request, 'appoint/index.html')
def appointment_list(request):
Appointments = appointment.objects.all()
context = {'Appointments': Appointments}
return render(request, 'appoint/appointment_list.html', context)
appointment_list.html
<p>{{Appointments.patient_name1}}</p>
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^appointment_list/$', views.appointment_list, name='appointment_list'),
url(r'^aboutme/$', views.aboutme, name='about_us'),
url(r'^contact/$', views.contact, name='contact_us'),
url(r'^apply_appoint/$', views.apply_appoint, name='apply_appoint'),
]
please help me i am new to Django 1.9
you need to iterate over the queryset and then access object's attribute:
<p>
{% for appointment in Appointments %}
{{ appointment.patient_name1 }}
{% endfor %}
</p>
Appointments is a queryset which is a list of instances of Appointment class.
and you need to name your classes with Capital letter btw. Normally objects are in lowercase and class names begin with Capital letter.
Appointments is a list of model objects you need to loop over them in template
like this:
<p>
{% for object in Appointments %}
{{ object.patient_name1 }} , {{ object.appoint_date }}
{% endfor %}
</p>

django form.save() fails to write to disk on model instance update

Ive been Playing around with django to create an asset management app and have hit a wall on the file upload to model instance behaviour.
I am attempting to use the ModelForm class in Forms.py
Basically im pretty certain that form.save() is not writing my uploaded file to disk to update my model instance.
Do I have to write a form.save definition into my AssetForm ? or have I missed something else.
Appreciate any help.
My project is built around the Polls tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01/ and the minimal file upload tutorial at Need a minimal Django file upload example.
Here is my model .py
class Category(models.Model):
category_text = models.CharField(max_length=200)
def __str__(self): # __unicode__ on Python 2
return self.category_text
class Asset(models.Model):
asset_text = models.CharField(max_length=200)
asset_tag = models.CharField(max_length=200)
asset_category = models.ForeignKey(Category)
cert_date = models.DateTimeField('cert published')
def __str__(self): # __unicode__ on Python 2
return self.asset_text
def was_certed_recently(self):
return self.cert_date >= timezone.now() - datetime.timedelta(days=365)
was_certed_recently.admin_order_field = 'cert_date'
was_certed_recently.boolean = True
was_certed_recently.short_description = 'Certified recently?'
docfile = models.FileField(upload_to='documents')
Here is my forms.py
from django import forms
from django.forms import ModelForm
from polls.models import Asset
class AssetForm(ModelForm):
class Meta:
model = Asset
fields = '__all__'
Here is my views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
#from django.template import RequestContext, loader
from django.shortcuts import get_object_or_404, render
from django.http import Http404
from polls.models import Asset
from polls.forms import AssetForm
def list(request, asset_id):
# Handle file upload
ID = asset_id
p = get_object_or_404(Asset, pk = asset_id)
if request.method == 'POST':
form = AssetForm(request.POST, request.FILES, instance= p )
if form.is_valid():
form.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list', args=(p.id,)))
else:
form = AssetForm() # A empty, unbound form
# Load documents for the list page
documents = p
# Render list page with the documents and the form
return render_to_response(
'polls/list.html',
{'documents': documents, 'ID': ID, 'form': form},
context_instance=RequestContext(request )
)
def index(request):
latest_asset_list = Asset.objects.order_by('-cert_date')[:]
context = {'latest_asset_list': latest_asset_list}
return render(request, 'polls/index.html', context)
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^/list/$', 'list', name='list'),
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<asset_id>[0-9]+)/$', views.list, name='list'),
# ex: /polls/5/results/
url(r'^(?P<asset_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<asset_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
Finally my list.html template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
<p>Current Doc.</p>
<li>{{ documents.docfile.name }}</li>
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<ul>
{{ ID }}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' ID %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
You're doing various things twice. For example, at the start of your function, you get an Asset into p and then you get the same one into a. Why?
More significantly, in the is_valid() block you create a new Asset object just from the uploaded file, with no other data from the form, but then you save the form itself which should update the existing Asset. This might be the cause of your problem - you should remove the lines with docfile and just save the form.