Content not visible on webpage - python

I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and on the page, but nothing else appears. When I click on the link, I go to luokka_id/number. I must be missing something but can't figure out what the problem is.
models.py
class luokka(models.Model):
nimi = models.CharField('Pääkäyttöluokka', max_length=100)
vara = models.CharField('Varakäyttöluokka', max_length=100)
varaaja = models.CharField('Varakäyttöluokka', max_length=100)
def __str__(self):
return self.nimi
and on the näytä_luokka.html (show class):
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{luokkalistaus}}
{{luokka}}
{{ luokka.nimi }}
{{ luokka.vara }}
{{ luokka.varaaja }}
</center>
{% endblock %}
and views.py:
def näytä_luokka(request, luokka_id):
luokkalistaus = luokka.objects.get(pk=luokka_id)
return render(request, 'tietokanta/näytä_luokat.html',
{'luokkalistaus': luokkalistaus})
I don't get any errors to help me out here. It's just an empty page, but it should show some extra data.

You have named the key of context as luokkalistaus not luokka, so the template should be:
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{ luokkalistaus.nimi }}
{{ luokkalistaus.vara }}
{{ luokkalistaus.varaaja }}
</center>
{% endblock %}

Related

Django context isn't passing information to template

I try to pass information to an html template from a view function. Every time I try to call the variable from the html template it doesn't show anything.
Here is my configure_peplink.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Configure Peplink</h1>
<p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p>
{% if peplink %}
<p>Serial Number: {{ peplink.serial_number }}</p>
<p>IP Address: {{ peplink.ip_address }}</p>
<p>Mac Address: {{ peplink.mac_address }}</p>
<p>Name: {{ peplink.name }}</p>
{% else %}
<p>No Data Found Off Device</p>
{% endif %}
{% endblock %}
Here is the view function configure_peplink:
def configure_peplink(request, peplink):
selected_peplink = PeplinkDevice.objects.get(serial_number=peplink)
print(selected_peplink.ip_address)
print(selected_peplink.serial_number)
print(selected_peplink.mac_address)
context = {
'peplink': selected_peplink
}
return render(request, 'configure_peplink.html', context=context)
Here is the url line to call the view:
re_path(r'^configurepeplink/(?P<peplink>.*)/$', views.configure_peplink, name='configurepeplink')
I've tested to make sure that the context has data in it (as seen with the print statements). Even though the context variable has data and is getting past the if statement in the html template it still doesn't display any data. I have tried clearing my cache on the browser and restarting all my services (django, celery, redis-server).
Here is a picture of the webpage:
The peplink variable (which is being used by the regex url and the view function) seems to be causing the problem. Change the name of the key or change the regex url variable for this to work. To get this to work by changing the key name in the view function do the following in the view function:
def configure_peplink(request, peplink):
selected_peplink = PeplinkDevice.objects.get(serial_number=peplink)
print(selected_peplink.ip_address)
print(selected_peplink.serial_number)
print(selected_peplink.mac_address)
context = {
'selected_peplink': selected_peplink
}
return render(request, 'configure_peplink.html', context=context)
Then change the html template to the following:
{% extends "base_generic.html" %}
{% block content %}
<h1>Configure Peplink</h1>
<p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p>
{% if selected_peplink %}
<p>Serial Number: {{ selected_peplink.serial_number }}</p>
<p>IP Address: {{ selected_peplink.ip_address }}</p>
<p>Mac Address: {{ selected_peplink.mac_address }}</p>
<p>Name: {{ selected_peplink.name }}</p>
{% else %}
<p>No Data Found Off Device</p>
{% endif %}
{% endblock %}

How do you iterate through two items in a model and display on site using Django?

I have a models.py with the following fields:
class ChatStream(models.Model):
bot = models.TextField()
user = models.TextField()
name = models.CharField(max_length=100, null=True)
created_date = models.DateTimeField(auto_now_add=True)
And I'd like on a website to iterate through "bot" and "user" one at a time, so the site would hypothetically display something like:
bot: hello!
user: what's up?
bot: I'm good
user: What's your name
bot: bot is my name
.... etc. this would keep going...
So in my views.py I have
def displayDict(request):
m = ChatStream.objects.all()
return render(request, 'chatStream.html',
{"chat": m})
def send(request):
message = request.POST.get('userMessage', False)
ip = visitor_ip_address(request)
response = routes(message, ip)
print(ip, "user sent:", message, "bot response:", response)
chatItem = ChatStream(bot=response, user=message, name=ip)
chatItem.save()
return HttpResponseRedirect('/chat/')
Then in my template, chat.html I have
{% block chatStream %} {% endblock %}
And chatStream.html (this is where the error is happening I believe... how do you iterate through two items in the model so they appear one after the other on the html file?)
{% extends 'chat.html' %}
{% block chatStream %}
{% for a in bot%}
{% for b in user%}
<p>
<b>bot:</b> {{a}} <br>
<b>user:</b> {{b}} <br>
</p>
{% endfor %}
<form action="/send/" method = "post">{% csrf_token %}
<input type="text" name="userMessage">
<input type="submit" value="Send to smallest_steps bot">
</form>
{% endblock %}
But this does not work -- no text from the model is displayed on the site. I am not understanding how to iterate through two items within the model at once inside of the chatStream.html.
A lot going on here, lets try to break it down:
First, you need to pass context variables to your templates if you want to render them using the (jinja-like) Django template rendering system.
Your view function for rendering the template would look like this:
views.py
def render_chat_page(request):
# do some logic:
...
# pack the context variables:
context = {
'some_key' : 'some_value',
'chat_streams' : ChatStream.objects.all(),
...
}
return render(request, 'chat_page.html', context=context)
Ok, now that we've passed the context variables to the template, we can render html elements using the variables like so:
template.html
<div> The value of "some_key" is: {{some_key}} </div>
{% for chat_stream in chat_streams %}
<div> user says: {{chat_stream.user}}</div>
<div> bot says: {{chat_stream.bot}}</div>
{% endfor %}
This will render the user and bot messages for each ChatStream object. However my hunch is that this is not entirely what you're after, instead you may want something more dynamic.
In your displayDict view you're passing a QuerySet to the context. So, you need to loop over the QuerySet in your template.
{% extends 'chat.html' %}
{% block chatStream %}
{% for item in chat %}
<p>
<b>bot:</b> {{item.bot}} <br>
<b>user:</b> {{item.user}} <br>
</p>
{% endfor %}
<form action="/send/" method = "post">{% csrf_token %}
<input type="text" name="userMessage">
<input type="submit" value="Send to smallest_steps bot">
</form>
{% endblock %}

Django: How to display author of query of posts?

I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.
views.py
class UserProfileView(generic.ListView):
template_name = 'howl/user-profile.html'
context_object_name = 'user_howls'
def get_queryset(self):
author = self.request.user
u = User.objects.get(username=author)
return Howl.objects.filter(author=u)
models.py
class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
Here is where I'm stuck.
user-profile.html
{% extends 'howl/base.html' %}
{% block content %}
<h1>User: {{user_howl.author}}</h1>
{% for user_howl in user_howls %}
<ul>
<li>{{user_howl.content}}</li>
</ul>
{% endfor %}
{% endblock %}
The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop?
I've tried:
{% for author in user_howls.author %}
<h1>User: {{author}}</h1>
{% endfor %}
and
{% if user_howls.author %}
<h1>User: {{user_howl.author}}</h1>
{% endif %}
Still the same outcome, displaying "User: "
user_howls is a queryset so it won't have an author attribute, you need to get the author of the iterated object
{% for howl in user_howls %}
<h1>User: {{ howl.author}}</h1>
{% endfor %}
More to the point though, it doesn't make sense to start from a Howl list, when you are just returning the results for the user_profile, nor does it make sense to use a ListView. so instead, start from the user and then look up its howls
user_obj.howl_set.all()
Since your queryset is based on the posts belonging to the current user, you can shortcut all of this and just show the user directly:
User: {{ user }}

Form.media not being injected into a template

I wrote a simple app that is a custom DateField widget for mezzanine. Afaik it's, it's a simple case and besides overextending a template it would be the same in pure django or django-cms (feel free to correct me if I'm wrong).
The widget:
class DatePickerInput(forms.DateInput):
def __init__(self, attrs = None, format = None):
super(DatePickerInput, self).__init__(attrs, format)
self.attrs["class"] = "datepicker"
class Media:
css = { "all": ('css/ui-lightness/jquery-ui-1.10.3.custom.min.css',) }
js = (
"mezzanine/js/" + getattr(settings, "JQUERY_UI_FILENAME", "jquery-ui-1.9.1.custom.min.js"),
"js/datepicker_setup.js",)
I overextend base.html template to insert form.media:
{% overextends "base.html" %}
{% load pages_tags mezzanine_tags i18n future staticfiles %}
{% block extra_head %}{{ block.super }}
{{ form.media }}
{% endblock %}
Now, I create a form for my model class.
Here's the class:
class PlayerProfile(models.Model):
user = models.OneToOneField("auth.User")
# Can be later changed to use a setting variable instead of a fixed date
date_of_birth = models.DateField(default=date(1990, 1, 1))
Here's the model form:
from DateWidgets.widgets import DatePickerInput
from PlayerProfiles.models import PlayerProfile
class EditPlayerProfileForm(Html5Mixin, forms.ModelForm):
class Meta:
model = PlayerProfile
fields = ("date_of_birth", )
widgets = { 'date_of_birth': DatePickerInput }
def __init__(self, *args, **kwargs):
super(EditPlayerProfileForm, self).__init__(*args, **kwargs)
Here's the view:
#login_required
def profile_update(request, template="accounts/account_profile_update.html"):
"""
Profile update form.
"""
pform = forms.EditPlayerProfileForm
player_form = pform(request.POST or None, request.FILES or None, instance=request.user.playerprofile)
context = {"pform": player_form, "title": _("Update Profile"), "profile_user": request.user}
return render(request, template, context)
Here's the template:
{% overextends "accounts/account_profile_update.html" %}
{% load i18n mezzanine_tags %}
{% block main %}
<fieldset>
<legend>{{ title }}</legend>
<form method="post"{% if pform.is_multipart %} enctype="multipart/form-data"{% endif %}>
{% fields_for pform %}
<div class="form-actions">
<input class="btn btn-primary btn-large" type="submit" value="{{ title }}">
</div>
</form>
</fieldset>
{% endblock %}
Now if I view the form in a browser, the custom widget is there (I can tell because the input html tag has my custom class attribute value) but it doesn't inject the form media, it's missing. Any idea what's going on here? Thanks in advance! Cheers :-)
form isn't available in the template, because you've called your form variable pform.
Try {{ pform.media }}.
I was googled here with the same problem under different conditions and spotted another error that may appear under other conditions (my case is extending change_form.html in Django 2.1): I had to use extrahead instead of extra_head
{% block extrahead %}{{ block.super }}
{{ form.media }}
{% endblock %}

Django template not receiving variables

I am writing a django template Configuration_Detail.html and it renders correctly on the relevant urls. It does not, however, take any variables whatsoever from the view class. I had a very similar template Configuration_List.html which worked fine, though that was a ListView not a DetailView.
Configuration_Detail.html:
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans 'MySite Database' %}{% endblock %}
{% block branding %}
<h1 id="site-name">{% trans 'MySite Database: Current Instrumentation Configuration' %}</h1>
{% endblock %}
{% block content %}
Here is some text {{name}} with a variable in the middle.
{% endblock %}
The page renders the title bar fine, but the content block becomes "Here is some text with a variable in the middle."
I believe it should be taking the variable {{ name }} from here.
views.py:
class ConfigurationDetail(DetailView):
model = Configuration
def getname(self):
name = 'debug'
return name
But it does not...
Any suggestions on how to fix this would be greatly appreciated.
Edited to add:
Models.py - Configuration:
class Configuration(models.Model):
title = models.CharField(max_length=100,unique=True,blank=False)
author = models.ForeignKey(User)
created = models.DateField("date created",auto_now_add=True)
modified = models.DateField("date modified",auto_now=True)
description = models.CharField(max_length=512)
drawing = models.ForeignKey(Drawing,blank=True,null=True)
instruments = models.ManyToManyField(Instrument)
def __unicode__(self):
return self.title
The get_context_data() method is using ctx['author'] = Configuration.author
For DetailView, an object variable is added in the context which points to the database object for which the view is being rendered. So in your template you can do:
{% block content %}
Here is some text {{ object.author.get_full_name }}
with a variable in the middle.
{% endblock %}
The get_full_name method is from the User object.
if i understood correctly you need to access a model property from within a template, but for that is sufficient to do {{ configuration.author }} without modifying the context data at all!
the DetailView puts in the context the selected model, accessible with the dot notation.

Categories

Resources