Django file not showing input data in actual website - python

I'm currently attempting to learn how to use django to build a website but my input data in the models is not showing up properly
'''
from django.db import models
class products(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class typeWork(models.Model):
work = models.CharField(max_length = 255)
hoursWorked = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField()
genre = models.ForeignKey(products, on_delete=models.CASCADE)
'''
models.py
'''
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello, name='hello')
]
'''
urls.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import typeWork
def hello(request):
products2 = {typeWork.objects.all()}
return render(request, 'index.html', {products2})
views.py is slightly altered as i was messing with it in order to try and fix it the image shows the code with no alterations and my original issue arising from that code
views.py
<table class="table">
<thead>
<tr>
<th>Work</th>
<th>Type of Work</th>
<th>Hours needed</th>
</tr>
</thead>
<tbody>
{% for products2 in products%}
<tr>
<td>{{products2.work}}</td>
<td>{{products2.genre}}</td>
<td>{{products2.hoursWorked}}</td>
</tr>
{% endfor %}
</tbody>
indes.html is also slightly altered the image will show the original code before i tried fixing it again
index.html
Actual error and what it does show currently

You can try passing your products2 variable through a so-called "context dictionary".
Updated version of views.py:
I'm currently attempting to learn how to use django to build a website but my input data in the models is not showing up properly
from django.shortcuts import render
from django.http import HttpResponse
from .models import typeWork
def hello(request):
products2 = typeWork.objects.all()
context = {"products2": products2}
return render(request, 'index.html', context)
You had some idea on how to pass these variables when you put the {} symbols, but only adding names between these symbols will pass a set. A dictionary would mean the curly braces + a set of key-value pairs.
The main idea is, everytime you're trying to pass data to a view, you'll need to do it via a dictionary. The key you're using will also be used in the template. By replacing your code with the one I wrote, you're going to be okay because your template is iterating through something called products2.

Related

Django - printing variables in templates

I created an app called "jobs", basically I'd like to create new "jobs" from the admin console and be able to post it on the jobs.html page.
I created the model and views but I think there is something wrong with the views that doesn't allow me to print the "jobs" on the html template.
Can you please tell me if the error is in views.py?
jobs/models.py
from django.db import models
# Create your models here.
class post_job(models.Model):
posizione= models.TextField(max_length=20)
descrizione= models.TextField(max_length=20)
requisiti= models.TextField(max_length=20)
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
return self.posizione
jobs/admin.py
from django.contrib import admin
from .models import post_job
# Register your models here.
admin.site.register(post_job)
jobs/views.py
from django.shortcuts import render
from .models import post_job
# Create your views here.
def viz_job(request):
posizione = post_job.posizione
print(posizione)
return render(request,'jobs/jobs.html',{'posizione':posizione})
Proper answer:
In your views:
from django.shortcuts import render
from .models import PostJob # proper naming
def viz_job(request):
jobs = PostJob.objects.all()
return render(request,'jobs/jobs.html',{'jobs': jobs})
in your template:
<ul>
{% for job in jobs %}
<li>
<h3>{{ job.posizione }}</h3>
<div>
{{ job.descrizione }}
</div>
</li>
{% endfor %}
</ul>
Note that all this is documented.
NB: if you're only interested in those two fields and don't need any of the model's methods, related objects or whatever, you can optimize the query a bit by using a values queryset that will yield dicts with the selected fields instead of full model instances:
jobs = PostJob.objects.values("posizione", "descrizione")
Everything else remains the same.
You have to know what do you want to return for the template, for example in the views.py :
from django.shortcuts import render
from .models import post_job
# Create your views here.
def viz_job(request):
jobs = []
descriziones = []
posizione = Job.objects.all()
for pos in posizione:
jobs.append(pos.posizione)
descriziones.append(pos.descrizione)
context = {
'posizione': jobs,
'descrizione': descriziones
}
return render(request, 'jobs/jobs.html',
context=context) # this will return context dictonary to the template
You can filter and get to fetch specific data from your database

Django ListView

It's my first time to use ListView and it doesn't work and give me error.
I put get_query but they still give me same error. How can I fix the problem?
And everytime when I write code in views.py I always used 'def' not 'class'. But could see many people use (and also django documents) 'class' for ListView. So for general render stuffs we use 'def' and for django.views.generic stuffs we use class right? Why they distinguished these two?
This is error what I got.
ImproperlyConfigured at /search/results
ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset().
urls.py
from django.urls import path
from django.conf import settings
from django.views.generic import ListView, TemplateView
from . import views
app_name = 'search'
urlpatterns = [
path('', TemplateView.as_view(template_name = "search/index.html")),
path('results', ListView.as_view(template_name = 'search/results.html')),
path('beerlist', views.beerlist, name='beerlist'),
path('<int:beerinfo_id>', views.beerinfo, name='beerinfo'),
]
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Q
from django.views.generic import ListView, TemplateView
from .models import Beerinfo
# Create your views here.
def index(TemplateView):
template_name = 'search/index.html'
def results(ListView):
model = Beerinfo
template_name = 'search/results.html'
def get_queryset(self):
query = self.request.GET.get('q')
object_list = Beerinfo.objects.filter(
Q(name__icontains = query) | Q(label__icontains = query)
)
return obejct_list
index.html
<form action="{% url 'search:results' %}" name="se">
<label for='search'>What do you want to find?</label>
<input type="text" name='q'>
<input type="submit">
</form>
results.html
<ul>
{% for beer in ojbect_list %}
<li>{{ beer.name }}</li>
{% endfor %}
</ul>
models.py
from django.db import models
# Create your models here.
class Beerinfo(models.Model):
name = models.CharField(max_length=100)
label = models.CharField(max_length=500)
def __str__(self):
return self.name
You need to define the class that the list view will work with. For example:
class UserListView(ListView):
model = User
You can use a function (def) to accomplish the same thing that a generic view class, the difference is that most of what you write in the function is already defined in the class. In my example above, that class already handles the rendering of a default template, a context with the list of object of that template and pagination. The idea is to keep your code DRY.
The second advantage is that it creates a standard for your code, for example the default template to be used is
%(app_label)s/%(model_name)s%(template_name_suffix)s.html, so if your app name is users and your model is User, the this view expects a template named users/userlist.html
To use the pagiation simply set the paginate_by attribute of the class.
If you are trying to implement a simple view (for example all CRUD actions, then is very likely that you will benefit from using clases. Another good thing that classes give you, is that you can inherit goodies, for example, you can create a BaseListView class that inherits from ListView and set paginate_by to 25. If all your clases inherit from BaseListView then all your list will be paginated by 25 elements.
In views.py change def to class , you need to define a class to use Listview, Class Results(ListView). In urls.py, you are calling Listview , you should call views.Results.as_view()

Django display different models/tabells

I get stuck. I try to display each time a other table in django with the same def in my view.py code.
First problem is I can't transfer the string which I enter in the url to a model.
For example if I type 0.0.0.0:8000/polls/Cashflows I wanna display the table Cashflows of my db.
from django.http import HttpResponse
from django.template import loader
from django.apps import apps
from .models import Cashflows,Garbage,Inputacturial
def index(request):
list_cashflows=Cashflows.objects.all()
template=loader.get_template('polls/index.html')
context={'list_cashflows':list_cashflows,}
return HttpResponse(template.render(context,request))
def detail(request, table):
#model = apps.get_model('polls', 'table')
#model=apps.get_model ( 'polls',table.split('.',1))
model=Cashflows
liste_column=model.objects.all()
b=model._meta.get_fields()
#b=a[:]
liste_fields=list(b)
template=loader.get_template('polls/index2.html')
context={'liste_column':liste_column,'liste_fields':liste_fields,}
return HttpResponse(template.render(context,request))
I try different options but none of these really work for.
My next problem is to display these different tables.
I try to start with the field names.
<table>{% for item in liste_fields%}
<tr><th>liste_fields.item</th>
</tr>
{% endfor %}
</table>
It's just give me three rows with liste.fields.item and not columns with each field. Can you help me?
You have of use the o method verbose_name
For example:
list_fields = [field.verbose_name for field in Cashflows._meta.get_fields() if not field.is_relation or field.one_to_one or (field.many_to_one and field.related_model)]
https://docs.djangoproject.com/en/2.0/ref/models/meta/#migrating-from-the-old-api

Displaying attribute of first element of list in django

So I am trying to display the first attribute of the first object of my list in django template. I currently have tried
{{objArray.0.name}}
and
{{objArray.0.getName}}
In my template and
class ObjInfo():
def __init__(self,name):
self.name=name
def getName(self):
return self.name
is my class definition. I hard-coded my variables to be declared on any request but I printed it out to be sure it was declared. When I go to the page after running the server, nothing populates. Please help.
EDIT: Section of view is like this(from template):
<button class="accordion">Obj Info</button>
<div class="panel">
<div class="panel-table">
<table id="Obj" style="width:100%">
<tr>
<th>Obj Description</th>
</tr>
<tr>
<td>{{objobjArray.0.name}}</td>
</tr>
</table>
</div>
</div>
There's a few more sections on the table that I ommitted that are static right now, but that is the giist.
Sorry, semi new, here you go:
'''
Created on Jul 9, 2018
#author: packawd
'''
from django.http import HttpResponse
from django.shortcuts import render_to_response,render
from django.template import Context, loader
from django import forms
template_name='App Template.html'
class TicketForm(forms.Form):
ticketNumber=forms.CharField(label="Ticket number", required=False)
assetSerial=forms.CharField(label="Asset S/N")
RadioSerial=forms.CharField(label="Radio S/N")
#Will be used to setup API injection, create object arrays and pass on
#class asassasasasa():
class objInfo():
def __init__(self,name):
self.name=name
def getName(self):
return self.name
def index(request):
if request.method =="POST":
form=TicketForm(request.POST)
if form.is_valid():
#Simple check to see if we are pulling data correctly
"""
print(form.cleaned_data['ticketNumber'])
print(form.cleaned_data['assetSerial'])
print(form.cleaned_data['RadioSerial'])
"""
#Data injection test pt 1
#obj="engine69420"
objobj1=objInfo("Engine1")
objobj2=objInfo("Engine2")
objobjArray=[]
objobjArray.append(objobj1)
objobjArray.append(objobj2)
#Allows us to use the above fields to call an API or something
#We need to switch the below to be CAT endpoint and secure the API
#response = requests.get('http://freegeoip.net/json/%s' % ip_address)
#geodata = response.json()
else:
form=TicketForm()
objobj1=objInfo("Engine1")
objobj2=objInfo("Engine2")
objobjArray=[]
objobjArray.append(objobj1)
objobjArray.append(objobj2)
return render(request, template_name, {'form': form, 'objobjarray':objobjArray,})
It looks like the name you are using in creating the context objobjarray doesn't match the name you are using in your template ecmobjArray.
So what this turned out being is that I was trying to reference objobjArray instead of objobjarrayin my context. It'd probably be handy for me in the future to use the same name for both in this area:
'objobjarray':objobjArray

Reverse for 'data' with arguments '(1,)' and keyword arguments '{}' not found

I am new to Django. I am trying to make a simple web app which contains some name of stocks then you have to click on one then next window will be of what data you want like "Get percentage change" and then it will show the percentage change in that stock. I know some part of code should be better but I am just trying different parts of Django. I am getting problem in second part, after selecting stock, I am getting error and I have tried my best but not able to remove it.
This is my urls.py file:
# project/stocks.urls.py
from django.conf.urls import patterns, url
from stocks import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<stocks_id>\d+)/$', views.choice, name='choice'),
url(r'^(?P<stocks_id>\d+)/(?P<choice_id>\d+)/$', views.data, name='data')
)
This is my views file:
# project/stocks.views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from stocks.models import Stocks, DataChoice
from NewStock_API import Get_Quote, Get_percent_change
from django.views import generic
def index(request):
latest_stocks = Stocks.objects.all()
context = {'latest_stocks': latest_stocks}
return render(request, 'stocks/index.html', context)
def choice(request, stocks_id):
total_choice = DataChoice.objects.all()
context = {'total_choice': total_choice}
return render(request, 'stocks/choice.html', context)
def data(request, stocks_id, choice_id):
selected_stock = Stocks.objects.get(id=stocks_id)
selected_symbol = selected_stock.symbol
stocks = Get_Quote(selected_symbol)
return render(request, 'stocks/data.html', {'stocks': stocks})
This is my models file:
# project/stocks.models.py
from django.db import models
class Stocks(models.Model):
symbol = models.CharField(max_length=20)
def __unicode__(self):
return self.symbol
class DataChoice(models.Model):
choice_text = models.CharField(max_length=20)
def __unicode__(self):
return self.choice_text
The error I am getting is:
Error during template rendering
In template /home/mukesh/markets/stocks/templates/stocks/choice.html, error at line 3
Reverse for 'data' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried:
[u'stocks/(?P<stocks_id>\\d+)/(?P<choice_id>\\d+)/$']
My choice.html file is:
<ul>
{% for choice in total_choice %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
Your data url pattern takes two arguments a stock id and a choice id; you are only supplying one.
You need to supply both, like this:
{% url 'stocks:data' stocks_id=stocks.id choice_id=choice.id %}

Categories