TemplateDoesNotExist at /inventory/render_results/ error message in django - django

I am using code that I've used before but it is throwing an error, 'TemplateDoesNotExist at /inventory/render_results/' and I cannot find the typo or logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss.
search_device_list.html
{% extends "inventory/base.html" %}
{% block content %}
<h2 align="left">Search Page</h2>
<form action="{% url 'render_results' %}" method="POST" >
{% csrf_token %}
<body>
<table>
<tr>
<td><b>Locations: </b></td>
<td>
<select name="location_name">
{% for locations in locations %}
<option value="{{locations.location_name}}">{{locations.location_name}}</option>{% endfor%}
</select>
</td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
{% endblock content %}
render_results.html
<html>
<h2 align="left">Render Device List based on Location Choice</h2>
<b> Locations: </b><br>{{locations }} <br><br><br>
<b> Devices: </b><br>
{% for device in devices %}{{device.device_name}} <br>{% endfor %} </td>
<br>
<button type="submit" id="save">Save</button>
</html>
views.py
def render_results (request):
location_name = request.POST.get('location_name')
my_devices = Devices.objects.filter(locations = Locations.objects.get(location_name = location_name))
context = {"devices": my_devices,
"locations": location_name}
return render(request, 'inventory/render_results.html', context)
def search_device_list(request):
locations = Locations.objects.all()
print(locations)
context = {"locations": locations}
for locations in context['locations']:
print(locations)
location_name=request.POST.get('location_name')
if request.method == 'GET':
form = LocationsForm()
print(locations)
return render(request, 'inventory/search_device_list.html', context)
and finally urls.py
...
url(r'^search_device_list/$', views.search_device_list, name='search_device_list'),
url(r'^render_results/$', views.render_results, name='render_results'),

Do you have os.path.join(BASE_DIR, 'templates') set in your settings file?
This would be in the templates section. This code should replace the empty list for DIRS = []
https://docs.djangoproject.com/en/3.0/topics/templates/
This is just speculation of course. It would help to see the full settings.py and urls.py. Also as previous stated, make sure the path to your templates is app_name/templates/app_name/html_file

<form action="{% url 'inventory:render_results' %}" method="POST" >

If your getting NoReverseMatch Error simply means you have an issue with the URL pattern either on the HTML end or in the URLconf. The reserve URL tag in your HTML templates can just be {% url 'url_pattern_name' %}
The tag you were first using {% url 'inventory:render_results' %}. Indicates that Django is to go to your URL conf, find the namespaced urls ie. app_name = 'inventory'. Then search in the namespace to find render_results. You can use either configuration but again the latter is stating your URL is namepspaced with app_name='inventory'.
I am not entirely sure if you can use the non-namespaced HTML tag {url 'url_pattern_name'%} with a namespace url config ex.
https://docs.djangoproject.com/en/3.0/topics/http/urls/#reversing-namespaced-urls

Related

Django Template doesn't work with a for loop in range. Why?

VIEWS.PY
def index(request):
posts = Post.objects.all()
posts_quantity = range(1)
return render(request, 'index.html', {'posts':posts, 'posts_quantity':posts_quantity})
HTML
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.index.slug %}" class = "post">
{% endfor %}
it gives me an error: Reverse for 'architectural_post' with arguments '('',)' not found.
But everything works well if I put 0 instead of index, like this (just for debugging):
{% for index in posts_quantity %}
<a href = "{% url 'architectural_post' posts.0.slug %}" class = "post">
{% endfor %}
Why and how to fix it?
Thanks.
Django is not interpreting posts.index.slug as posts.0.slug. Instead, Django is trying to find an attribute called index on the posts object.
It's not very intuitive, but that's how it is.
You can fix it by iterating over the posts directly:
{% for post in posts %}
<a href="{% url 'architectural_post' post.slug %}" class="post">
{% endfor %}

How to render template after failed form validation?

urls.py:
urlpatterns = [
path('employee/add_employee/', views.add_employee, name='add-employee'),
path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'),
]
I have add-employee page and some forms to fill there.
views.py:
def add_employee(request):
personal_form = PersonalEmployeeForm()
history_form = EmployeeHistoryForm()
return render(
request,
'sections/add_employee.html',
context={
'personal_form': personal_form,
'history_form': history_form,
}
)
def add_employee_action(request):
if request.method == "POST":
personal_form = PersonalEmployeeForm(request.POST)
history_form = EmployeeHistoryForm(request.POST)
if personal_form.is_valid() and history_form.is_valid():
# here is some logic with models
return redirect('add-employee')
else:
personal_form = PersonalEmployeeForm()
history_form = EmployeeHistoryForm()
return render(
request,
'sections/add_employee.html',
context={
'personal_form': personal_form,
'history_form': history_form,
}
)
template:
<form id="a-submit-form" action="add/" method="POST">
{% csrf_token %}
<div class="column-wrapper">
<div class="column">
<div class="form-wrapper">
{% for field in personal_form.visible_fields %}
{% include "elements/forms/form_line.html" %}
<br>
{% endfor %}
</div>
</div>
<div class="column">
<div class="form-wrapper">
{% for field in history_form.visible_fields %}
{% include "elements/forms/form_line.html" %}
<br>
{% endfor %}
</div>
</div>
</div>
<div class="button-bar-wrapper">
<div class="button_bar">
<a class="a-button positive" id="submit">Добавить</a>
<a class="a-button" href="{% url 'employee' %}">Сотрудники</a>
<a class="a-button" href="{% url 'index' %}">На главуную</a>
</div>
</div>
</form>
Submitting by <a> element is tested and worked well with jQuery script.
The problem is after submitting invalid forms I have a page with blah-blah/employee/add_employee/add/ URL. And if I try to submit forms again I have a page with blah-blah/employee/add_employee/add/add/ URL, which is incorrect. How can I render the page with blah-blah/employee/add_employee/ URL and show all error messages?
This is likely because you have written a relative URL in the <form> tag of the sections/add_employee.html template. The template thus contains something like:
<form method="post" action="add/">
...
</form>
You can use a URL with the {% url … %} template tag [Django-doc]:
<form method="post" action="{% url 'add-employee-action' %}">
...
</form>
Furthermore one usually uses the same path to handle both the GET and the POST request. So in fact you might simply remove the 'add-employee' path.

Why I can't save the edit of a Django ModelForm blog?

I was doing the Python Crash Course Ex. 19-1: Blogs, and I'm now stuck at saving the edit of any blog. I tried plugging in the .errors code in the blog.html (for showing each blog) but it shows nothing, so I guess my templates has no field errors (?)
Here're some codes I believe crucial for solving the not-saving-the-edit problem. The new_blog function in views.py works fine so I'll skip it.
The edit_blog function in views.py:
def edit_blog(request, blog_id):
idk = BlogPost.objects.get(id = blog_id)
if request.method != "POST":
form = BlogForm(instance = idk)
else:
form = BlogForm(instance = idk, data = request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blogs:blogs'))
content = {"editing_blog": form, "psst": idk}
return render(request, 'blogs/edit_blog.html', content)
new_blog.html:
{% extends "blogs/all.html" %}
{% block content %}
<p>Write a new blog:</p>
<form action="{% url 'blogs:new_blog' %}" method='post'>
{% csrf_token %}
<table border="1">
{{ new_blog }}
</table>
<p></p>
<button name="submit">Submit</button>
</form>
{% endblock content %}
edit_blog.html:
{% extends "blogs/all.html" %}
{% block content %}
<p>Edit the blog:</p>
<form action="{% url 'blogs:blog' psst.id %}" method='post'>
{% csrf_token %}
<table border="1">
{{ editing_blog }}
</table>
<p></p>
<button name="submit">Save changes</button>
</form>
{% endblock content %}
Btw, the urlpattern is here:
from django.urls import path, include
from . import views
app_name = 'blogs'
urlpatterns = [
# Home page
path('', views.homepage, name = 'homepage'),
# Show all blogs.
path('blogs/', views.blogs, name = 'blogs'),
# Show the detail of a blog.
path('blogs/<int:blog_id>', views.blog, name = 'blog'),
# Page for adding a new blog.
path('new_blog/', views.new_blog, name = 'new_blog'),
# Page for editing a blog.
path('edit_blog/<int:blog_id>', views.edit_blog, name = 'edit_blog'),
]
No matter how I change the title, or content, or both of the blog I don't see the changes saved. Is it:
A) My form action in edit_blog.html goes wrong, as wakandan mentioned?
B) I need to adjust something in edit_blog view function, like Bibhas said?
Many thanks. Also tell me if I need to add more codes for understanding.
Your form action is currently set to {% url 'blogs:blog' psst.id %}, which means you're posting to your views.blog view, which is just a detail view. You need to change the action to {% url 'blogs:edit_blog' psst.id %} so that the form is posted to your edit view.
It's not clear from the code you have posted where the editing_blog context variable is coming from - you will need to make sure that this is an instance of the same form that your edit view is looking for, otherwise you'll run into other problems.
Finally also note that you are not currently handling the case where the form has errors - i.e., there is no else condition specified for form.is_valid().

Display users' images in Django

I am learning Django and currently trying to make a simple website where users can post topics and stuff. What I want is only the uploaded images that belong to a certain topic to display when you open the topic. But I am so stuck at it now I can't get any image come up on the pages. I've tried many different things but none's worked so far. I can't get my head around how exactly the template should look like and how do I link it to the topic page...and my view is probably far from right but I've tried a lot of things and it's all got a bit messy...pretty much it's been 2 days of hassle and I will appreciate any directions
Thank you in advance
This is what i have:
models.py
class Image(models.Model):
"""images representation"""
image=models.ForeignKey(Topic, on_delete=models.CASCADE)
image=models.ImageField(upload_to= 'media/')
caption=models.CharField(max_length= 100)
uploaded_at=models.DateTimeField(auto_now_add=True)
views.py
def upload_image(request, topic_id):
"""Upload images"""
topic=Topic.objects.get(id=topic_id)
if request.method != 'POST':
# No data submitted; creaete a blank form
form=ImageForm()
else:
# Data submitted; Process data
form=ImageForm(request.POST, request.FILES)
if form.is_valid():
instance=form.save(commit=FALSE)
instance.topic=topic
instance.save()
return HttpResponseRedirect(reverse('the_horror:topic',
args=[topic_id]))
images=Image.objects.all()
context={'form':form, 'topic':topic, 'images':images}
return render(request, 'the_horror/topic.html', context)
upload_image.html
{% extends 'the_horror/base.html' %}
{% block content %}
{% if images %}
<ul>
{% for image in images %}
<li>
<a href="{{image.image.url}}">
<img source="{{image.image.url}}" alt="sth"></a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<form action="{% url 'upload_image' %}" method= "post" enctype= "multipart/form-data">
{% csrf_token %}
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
<button type="submit">name="upload photo"</button>
</form>
As i said i am not sure how to pass the images to the topic template
topic.html
{% extends 'the_horror/base.html' %}
{% block content %}
<p>Topic:{{topic}}</p>
<p>
edit topic
</p>
<p>Entries</p>
<p>
Add a new entry
</p>
<ul>
{% for entry in entries %}
<li>
<p>{{entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{entry.text|linebreaks}}</p>
<p>
<image class= "Image" source={{>
</p>
<p>
edit entry
</p>
</li>
{% empty %}
<li>
There are no entries for this topic yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
urls.py
path('upload_image/<topic_id>', views.upload_image, name= 'upload_image'),
# Single topic page
On your models.py you don't need to write media on your upload_to option, what you have to do is to add to your urls.py static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here
urls.py
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
On your upload_image.html why are you creating 2 input. Personally I use an input to take the image file
upload_image.html
...
<input name="image" type="file">
...
then in the views you started well but I will do as follow to store the image
views.py
def upload_image(request, topic_id):
...
imageObject = Image.objects.create()
image = request.FILES['image']
imageObject.image = image
...
Finally, you will get your image this way
topic.html
<img src="{{MEDIA_URL}}{{imageObject.image}}" alt="image">
Usually it works, I made several projects with this method or similar methods, if you still got error or question let me know

how to give {% url '' %} to a variable?

I have this requirement in django template:
{% if user.is_admin %}
<a href='{% url 'url_to_admin' %}'>admin url</a>
{% else %}
<a href='{% url 'url_to_other %}'>other url </a>
{% endif %}
and now, I want let it more simple, I want let url to a variable `xx', like this:
if user.is_admin:
myurl = {% url 'url_to_admin' %}
else:
myurl = {% url 'url_to_other' %}
<a href={{myurl}} > url </a>
But I don't know how to write in django's template?
The url tag can be assigned to a variable through using as.
{% url 'my_url' as foobar %}
{{ foobar }}
But that doesn't make sense in the current place where you're using it. Just assign the anchor tags inside of the if/else statements
{% if user.is_admin %}
admin
{% else %}
other
{% endif %}
Not the answer, but you may try this:
<a href='{% if user.is_admin %}{% url 'url_to_admin' %}{% else %}{% url 'url_to_other' %}'>other url </a>
why don't you handle it in the views before you render the template, try something like in your view.py
if User.is_admin:
url = 'url_to_admin'
else:
url = 'url_to_other'
render(request, "your_template.html", {'url' : url})
then you can go ahead and call your url in your template like
<a href= "{{ url }}>url</a>"
views.py
from django.core.urlresolvers import reverse
def my_view(request):
if request.user.is_admin:
my_url = reverse('my_admin_view')
else:
my_url = reverse('my_other_view')
return render(request, 'my_template.html', {'my_url': my_url })
Using django.core.urlresolvers.reverse
my_template.html
This is a link