Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['job_category/(?P<category_slug>[^/]+)/$']
{% extends 'base1.html' %}
{% block content %}
<div class="left col-sm-4" style="float:left; width: 360px;">
<h6 class="p-2" style="background:#A9CCE3; color:#2F4F4F;">JOB CATEGORIES</h6>
<ul class="list-group">
{% for x in categories %}
<li class="list-group-item c1 list-group-item-action" style="color: rgb(2,96,170);">
<div class="p-2">
<h7 class="card-title">
{{x.name}}
</h7>
</div>
<div class="overlay1"></div>
</li>
{% endfor %}
</ul>
</div>
<div class="right col-sm-8" style="float: right; width:825px;">
<!--{% if category %}{{category.name}}{% endif %} !-->
<div class="row container-fluid">
{% for job in jobs %}
<div class="col-sm-3 mt-3">
<div class="card c1">
<div class="overlay1"></div>
<div class="card-body">
<h5 class="card-title" style="color: rgb(2,96,170);">
{{job.post}}</h5>
<h6 class="card-text" style="color: rgb(85, 85, 85);">
{{job.job_id.comp_name}}</h6>
<p><i class="fas fa-map-marker-alt mr-1"></i>{{job.address}}<i
class="far fa-calendar-alt ml-3 mr-1"></i>{{job.todate|date:'d M, Y'}}</p>
<a href="{% url 'job_detail' job.job_id.id %}" class="btn btn-primary btn-sm right"
style="position:relative; float:right;">View more</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
views.py:
def job_category(request, category_slug=None):
category = None
job_requirements = []
categories = Category.objects.all()
jobs = Job.objects.all()
if category_slug:
category = Category.objects.get(slug=category_slug)
print(category.slug)
jobs = Job.objects.filter(job_category=category.slug)
for job in jobs:
job_requirements.append(JobRequirements.objects.get(job_id=job))
return render(request, 'JobCategory/category.html', {'categories': categories,
'jobs': job_requirements})
urls.py:
path('job_category/<str:category_slug>/', views.job_category, name='job_category'),
Models.py:
class Category(models.Model):
name = models.CharField(max_length=40, blank=True, null=True)
slug = models.CharField(max_length=4, unique=True)
def __str__(self):
return self.name
def get_absolute_path(self):
return reverse('job_category', kwargs={'category_slug': self.slug})
I've been trying to filter my page category wise. I cannot find where my mistake is at and can't simply decode this error message. I'm very new to this. Please help!
(Update) Traceback:
Internal Server Error: /job_category/IT/
Traceback (most recent call last):
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\DELL\PycharmProjects\RECRUIT\Home\views.py", line 33, in job_category
'jobs': job_requirements})
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\template\defaulttags.py", line 443, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\DELL\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['
job_category/(?P<category_slug>[^/]+)/$']
[14/Dec/2020 11:08:58] "GET /job_category/IT/ HTTP/1.1" 500 173336
I solved this problem by replacing my kwargs 'category_slug' with 'id'. But, I have no clue why it didn't take category_slug as an kwargs.
class Category(models.Model):
name = models.CharField(max_length=40, blank=True, null=True)
slug = models.CharField(max_length=4, unique=True)
def __str__(self):
return self.name
def get_absolute_path(self):
return reverse('job_category', kwargs={'id': self.slug})
urls.py
path('job_category/<str:id>/', views.job_category, name='job_category')
views.py
def job_category(request, id=None):
category = None
job_requirements = []
categories = Category.objects.all()
jobs = Job.objects.all()
if id:
category = Category.objects.get(slug=id)
print(category.slug)
jobs = Job.objects.filter(job_category=category.slug)
for job in jobs:
job_requirements.append(JobRequirements.objects.get(job_id=job))
print(job_requirements)
return render(request, 'JobCategory/category.html', {'categories': categories,
'jobs': job_requirements})
Related
I am getting the following error: Reverse for 'order_pdf' with arguments '('',)' not found. 1 pattern(s) tried: ['business_plan/(?P<id>[0-9]+)/pdf/$']
I am not sure exactly what is the reason for it.
Here is the model:
class Info(models.Model):
logo = models.ImageField(default='report-cover.jpg', null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
name = models.CharField(null=True, blank=True, max_length=100)
Here is the views.py
def add_business_plan(request):
# info=Info.objects.all()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = infoForm(request.POST)
# check whether it's valid:
if form.is_valid():
form.save()
business_name = form.cleaned_data.get('businessName')
messages.success(request, f'PDF created for {business_name}!')
# return redirect('businessplan:businessplan')
# redirect(reverse('businessplan:businessplan', kwargs={'successful_submit': True}))
return render(request, 'businessplan/businessplan.html', {'successful_submit': True})
# if a GET (or any other method) we'll create a blank form
else:
form = infoForm()
print(form.errors)
return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': False,
# "Info": info
})
def order_pdf(request, info_id):
info = get_object_or_404(Info, id=info_id)
html = render_to_string('businessplan/pdf.html', {'info': info})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}-Business Plan.pdf"'.format(info.businessName)
weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response,
stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True)
return response
def admin_order_pdf(request, info_id):
info = get_object_or_404(Info, id=info_id)
html = render_to_string('businessplan/pdf.html', {'info': info})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="{}-Business Plan.pdf"'.format(info.businessName)
weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response,
stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True)
return response
Here is the urls.py
urlpatterns = [
path('', add_business_plan, name='businessplan'),
path('businessplan/admin/info/<str:info_id>/pdf/', admin_order_pdf, name='admin_order_pdf'),
#path('<str:info_id>/pdf/', admin_order_pdf, name='admin_order_pdf'),
path('<str:info_id>/pdf/', order_pdf, name='order_pdf'),
]
Here is the businessplan.html snippet of the template:
....modal divs
<a href="{% url 'businessplan:order_pdf' Info.id %}">
<!--<a href="{% url 'businessplan:order_pdf' obj.id %}">-->
<!--<a href="{% url 'businessplan:order_pdf' Info.info_id %}">-->
....modal divs
<form class="needs-validation" method="post" novalidate enctype="multipart/form-data">
{% csrf_token %}
<div class="form-outline mb-4 mt-3">
<input required autocomplete="off" type="text" class="form-control" name=" name"
{% if form.is_bound %} value= "{{ form.name.value }}" {% endif %}>
<label class="form-label">Name</label>
</div>
{% for err in form.name.errors %}
<small class="text-danger ml-2">{{ err }}</small>
{% endfor %}
</div>
</form>
{% if successful_submit %}
<script type="text/javascript">
$(document).ready(function(){
$("#exampleModal").modal('show');
});
</script>
{% endif %}
I can access the pdf from the admin but I am trying to access to add this button for easier functionality.
I have tried changing the info_id to id it didn't work.
What is the reason for this error?
Here is the traceback:
Internal Server Error: /business_plan/
Traceback (most recent call last):
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\Desktop\Portfolio\businessplan\views.py", line 30, in add_business_plan
return render(request, 'businessplan/businessplan.html', {'form': form, 'successful_submit': False })
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'order_pdf' with arguments '('',)' not found. 1 pattern(s) tried: ['business_plan/(?P<info_id>[^/]+)/pdf/$']
[10/Oct/2021 06:58:51] "GET /business_plan/ HTTP/1.1" 500 143694
Looks like <a href="{% url 'businessplan:order_pdf' Info.id %}"> doesn't work because you don't pass it to the template context.
As a result, the call fails because Info.id is an empty string (cf https://docs.djangoproject.com/en/3.2/ref/templates/api/#invalid-template-variables), hence breaking the URL reversing logic.
You should pass your info instance to the template context to make this work, e.g like this:
return render(
request,
'businessplan/businessplan.html',
{
'form': form,
'successful_submit': False,
"Info": info_instance
}
)
I'm trying to create a searchbar in my blog in python, but I'm receiving the following error: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P[0-9]+)$'] and I'm not sure why, so here's the code so you guys can see what's going on here:
Traceback
Traceback (most recent call last):
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 187, in searchbar
return render(request, 'app1/search.html', {'query':query, 'results':results})
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\backends\django.py", line 61,
in render
return self.template.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 150, in
render
return compiled_parent._render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 312, in
render
return nodelist.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 211, in
render
nodelist.append(node.render_annotated(context))
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\template\defaulttags.py", line 446, in
render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'article-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app1/article/(?P<pk>[0-9]+)$']
Models.py
class StockNames(models.Model):
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class Post(models.Model):
title = models.CharField(max_length= 255)
header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank = True, null = True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='coding')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name = 'blog_posts')
stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('app1:article-detail', args=(self.id,))
Views.py
def searchbar(request):
query = None
results = []
if request.method == 'GET':
query=request.GET.get("search")
results= Post.objects.filter(Q(title__icontains=query) | Q(stock__symbol__icontains=query))
return render(request, 'app1/search.html', {'query':query, 'results':results})
search.html
{% extends "app1/base.html" %}
{% block body_block %}
<div class="container">
<h1>Search Page</h1>
{% if query %}
<h3>{% with results.count as total_results %}
Found {{total_results}} total results
{% endwith %}
</h3>
{% for x in results %}
<li>{{sym}} -
{{post.author}} - <small>{{post.post_date}}</small> -
{% if user.is_authenticated %}
<small>Edit</small><small>
- Delete
</small></li>
{% endif %}
</div>
{% empty %}
<h1>There's no query</h1>
{% endfor %}
{% else %}
<h3>Error in your query</h3>
{% endif %}
{% endblock %}
base.html (specifically the search input)
<form action="{% url 'app1:searchbar' %}" class="form-inline my-2 my-lg-0" method="GET">
<input name="search" class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search", name='search'>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
urls.py (the last one)
app_name = 'app1'
urlpatterns = [
path('post/', PostView.as_view(), name = 'Post'),
path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-detail'),
path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
path('update_post/<int:pk>', UpdatePostView.as_view(), name = 'updatepost'),
path('delete_post/<int:pk>', DeletePostView.as_view(), name = 'deletepost'),
path('add_category/', AddCategoryView.as_view(), name = 'add_category'),
path('category/<str:cats>/', views.CategoryView, name = 'category'),
path('category-list/', views.CategoryListView, name ='category-list'),
path('like/<int:pk>/', views.LikeView, name = 'like_post'),
path('my_posts/', views.MyPostsView.as_view(), name = 'my_posts'),
path('article/<int:pk>/add_comment/', AddCommentView.as_view(), name = 'add_comment'),
path('update_comment/<int:pk>', UpdateCommentView.as_view(), name = 'updatecomment'),
path('delete_comment/<int:pk>', DeleteCommentView.as_view(), name = 'deletecomment'),
path('stock/<str:sym>/', views.StockView, name = 'stock'),
path('searchbar/', views.searchbar, name = 'searchbar'),
]
Thanks in advance!
{% for post in results %}
<li>{{sym}} -
{% if user.is_authenticated %}
<small>Edit</small><small>
- Delete
</small></li>
{% endif %}
<a href="{% url 'app1:article-detail' post.pk %}">
here 'post' is not declared/contexted/retrieved from db.thats why you are getting error.
Error:
Request Method: GET Request
URL: http://127.0.0.1:8000/Verwaltung/Anhang/10 Django Version: 3.0.1
Exception Type: NoReverseMatch Exception Value: Reverse for
'anhangdelete' with arguments '('',)' not found. 1 pattern(s) tried:
['Verwaltung/AnhangDelete/(?P[0-9]+)$'] Exception
Location: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\urls\resolvers.py
in _reverse_with_prefix, line 677 Python
Executable: C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\Scripts\python.exe
Python Version: 3.8.0
views.py
#login_required()
def anhang_view(request, id=None):
contextoo = {}
item = Kunden.objects.get(id=id)
kontaktform_form = KontaktForm(request.POST or None, instance=item)
creatorform_form = CreateANform()
contextoo['creatorform_form'] = creatorform_form
if Kunden.objects.filter(KN=item.KN).exists():
item14 = Kunden.objects.get(KN=item.KN)
editkontakto_form = InfoKontaktoForm(request.POST or None, instance=item14)
contextoo['editkontakto_form'] = editkontakto_form
if Anhang.objects.filter(KN=item.KN).exists():
item15 = Anhang.objects.filter(KN=item.KN)
contextoo['ANform_form'] = item15
if request.method == 'POST':
creatorform_form = CreateANform(request.POST)
if creatorform_form.is_valid():
cre = creatorform_form.save(commit=True)
cre.save()
return redirect('/Verwaltung/KontaktAnlegen')
else:
return render(request, 'blog/anhang.html', contextoo)
#login_required()
def AnhangDeleteView(request, id):
anh = Anhang.objects.get(id=id)
anh.delete()
return redirect(reverse('blog:Anhang'))
urls.py
path('AnhangDelete/<int:id>', views.AnhangDeleteView, name='anhangdelete'),
anhang.html
.
.
.
{% if ANform_form %}
{% for obj in ANform_form %}
<table class="table" width="100%" border="0" cellspacing="0" cellpadding="0">
<thead class="thead-light">
<tr>
<td width="11%" border="0" cellspacing="0" cellpadding="0">
<b>
{% csrf_token %}
{{ obj.Thema }}
</b>
</td>
<td width="15%" border="0" cellspacing="0" cellpadding="0">Username</td>
<td width="19%" border="0" cellspacing="0" cellpadding="0">Password</td>
<td width="18%" border="0" cellspacing="0" cellpadding="0">E-Mail</td>
<td width="37%" border="0" cellspacing="0" cellpadding="0">Anhang</td>
<td>
</td>
<td></td>
</tr>
</thead>
<tbody>
<td></td>
<td>
{% csrf_token %}
{{ obj.Username }}
</td>
<td>
{% csrf_token %}
{{ obj.Password }}
</td>
<td>
{% csrf_token %}
{{ obj.Email }}
</td>
<td>
{% csrf_token %}
{{ obj.Anhang }}
</td>
<td>
<button type="button" class="btn btn-danger">Löschen</button> </td>
</td>
</tbody>
</table>
{% endfor %}
{% endif %}
models.py
class Anhang(models.Model):
KN = models.IntegerField(unique=False)
Thema = models.CharField(max_length=100, blank=True, unique=False)
Username = models.CharField(max_length=100, blank=True, unique=False)
Password = models.CharField(max_length=100, blank=True, unique=False)
Email = models.CharField(max_length=100, blank=True, unique=False)
Anhang = models.CharField(max_length=250, blank=True, unique=False)
class Kunden(models.Model):
KN = models.IntegerField(unique=True)
Anrede = models.CharField(max_length=30, blank=True)
Name = models.CharField(max_length=30, blank=True)
Vorname = models.CharField(max_length=30, blank=True)
Infos = models.CharField(max_length=250, default='Notiz:', editable=True)
so... all my delete_views work except that, because normally they have their source from "Kunden.id" but this delete_view orientates on Anhang.KN as much as i think and i dont know where the issue is...
TRACEBACK
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Verwaltung/Anhang/10
Django Version: 3.0.1
Python Version: 3.8.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'rlwebs',
'django_tables2',
'bootstrap4']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template C:\Users\PC\PycharmProjects\AddressLizenzbuch\web\blog\templates\blog\base.html, error at line 0
Reverse for 'AnhangDelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P<id>[0-9]+)$']
1 :
2 : <!DOCTYPE html>
3 : <html lang="en">
4 : <div class="p-3 mb-2 bg-secondary text-white">
5 :
6 : <head>
7 : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
8 : <meta charset="UTF-8">
9 : <title>{% block supertitle %} Home {% endblock %}</title>
10 : <!-- Bootstrap Core CSS -->
Traceback (most recent call last):
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\web\blog\views.py", line 200, in anhang_view
return render(request, 'blog/anhang.html', contextoo)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\defaulttags.py", line 309, in render
return nodelist.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\defaulttags.py", line 209, in render
nodelist.append(node.render_annotated(context))
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\template\defaulttags.py", line 443, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\PC\PycharmProjects\AddressLizenzbuch\venv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /Verwaltung/Anhang/10
Exception Value: Reverse for 'AnhangDelete' with arguments '('',)' not found. 1 pattern(s) tried: ['Verwaltung/AnhangDelete/(?P<id>[0-9]+)$']
Traceback is with this code sample in anhang.html
<button type="button" class="btn btn-danger">Löschen</button> </td>
Within my maintenance app, I have six models. I will include only 2 of the models that are relevant towards this question. There is a list of equipment (Listview) which displays properly. However, I'm having a problem creating a DetailView for each equipment. When I go to the http://127.0.0.1:8000/maintenance/equipments/1 it should display all equipment instance (details) relevant to equipment 1 but it displays back the equipment list page, i.e, http://127.0.0.1:8000/maintenance/equipments/.
models.py
from django.db import models
class Equipment(models.Model):
"""
Model representing an Equipment (but not a specific type of equipment).
"""
title = models.CharField(max_length=200)
physicist = models.ForeignKey('Physicist', null=True, help_text= 'add information about the physicist')
technician = models.ForeignKey('Technician', null=True, help_text= 'add information about the technician')
# Physicist as a string rather than object because it hasn't been declared yet in the file.
features = models.TextField(max_length=1000, help_text='Enter a brief description of the features of the equipment')
machine_number = models.CharField('Number', max_length=30, null=True, help_text='Enter the Equipment number')
specialty = models.ForeignKey(Specialty, null=True, help_text='Select a specialty for an equipment')
# Specialty class has already been defined so we can specify the object above.
assigned_technician = models.CharField(max_length=50, null= True, blank=True)
#This is for the Technician who the repair of the Equipment is assigned to.
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('equipment-detail', args=[str(self.id)])
def display_specialty(self):
return ', '.join([ specialty.name for specialty in self.specialty.all()[:3] ])
display_specialty.short_description = 'Specialty'
class Meta:
ordering = ['-id']
class EquipmentInstance(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular equipment across the entire database")
equipment = models.ForeignKey('Equipment', on_delete=models.SET_NULL, null=True)
imprint = models.CharField(max_length=200)
due_date = models.DateField(null=True, blank=True)
delegate = models.ForeignKey('Physicist', on_delete=models.SET_NULL, null=True, blank=True)
def is_overdue(self):
if self.due_date and date.today() > self.due_date:
return True
return False
MAINTENANCE_STATUS = (
('p', 'Past Maintenance'),
('o', 'On Maintenance'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(max_length=1, choices = MAINTENANCE_STATUS, blank=True, default='m', help_text='Equipment availability')
class Meta:
ordering = ["due_date"]
permissions = (("can_mark_maintained", "Set equipment as maintained"),)
def __str__(self):
"""
String for representing the Model object
"""
return '{0} ({1})'.format(self.id,self.equipment.title)
maintanance/urls.py
from django.conf.urls import url
from qatrack.maintenance import views
from qatrack.maintenance import models
urlpatterns = [
url(r'^$', views.MDashboard, name='m_dash'),
url(r'^equipments/$', views.EquipmentListView.as_view(), name='equipments'),
url(r'^equipment(?P<pk>\d+)/$', views.EquipmentDetailView.as_view(), name='equipment-detail'),
]
views.py
from django.shortcuts import render
from django.views.generic import DetailView, ListView
from qatrack.maintenance import models
class EquipmentListView(ListView):
template_name = 'maintenance/equipment_list.html'
def get_queryset(self):
return models.Equipment.objects.all()
paginate_by = 10
class EquipmentDetailView(DetailView):
model = models.Equipment
template_name = 'maintenance/equipment_detail.html'
context_object_name = 'equipment'
equipment_list.html
{% extends "maintenance/m_base.html" %}
{% block body %}
<div class="row">
<div class="col-md-12">
<div class="box">
<h1>Equipment List</h1>
{% if equipment_list %}
<ul>
{% for equipment in equipment_list %}
<li>
{{ equipment.title }} ({{equipment.physicist}}, {{equipment.technician}})
</li>
{% endfor %}
</ul>
{% else %}
<p>There are no equipments in the database.</p>
{% endif %}
</div>
</div>
</div>
{% endblock body %}
equipment_detail.html
{% extends "maintenance/m_base.html" %}
{% block title %}Equipment Details{% endblock %}
{% block body %}
<h1>Title: {{ equipment.title }}</h1>
<h2>Machine Detail</h2>
<p><strong>Physicist:</strong> {{ equipment.physicist }}</p> <!-- physicist detail link not yet defined -->
<p><strong>Technician:</strong> {{ equipment.technician }}</p> <!-- technician detail link not yet defined -->
<p><strong>Features:</strong> {{ equipment.features }}</p>
<p><strong>Machine_number:</strong> {{ equipment.machine_number }}</p>
<p><strong>Specialty:</strong> {% for specialty in equipment.specialty.all %} {{ specialty }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
{% for type in equipment.equipmentinstance_set.all %}
<hr>
<p class="{% if type.status == 'a' %}text-success{% elif type.status == 'm' %}text-danger{% else %}text-warning{% endif %}">{{ type.get_status_display }}</p>
{% if type.status != 'a' %}<p><strong>Due to be maintained:</strong> {{type.due_date}}</p>{% endif %}
<p><strong>Imprint:</strong> {{type.imprint}}</p>
<p class="text-muted"><strong>Id:</strong> {{type.id}}</p>
{% endfor %}
</div>
{% endblock body %}
urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.generic.base import TemplateView, RedirectView
from django.contrib.staticfiles.templatetags.staticfiles import static as static_url
from django.contrib import admin
from qatrack.maintenance.views import get_data
admin.autodiscover()
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="homepage.html"), name="home"),
url(r'^accounts/', include('qatrack.accounts.urls')),
url(r'^qa/', include('qatrack.qa.urls')),
url(r'^servicelog/', include('qatrack.service_log.urls')),
url(r'^parts/', include('qatrack.parts.urls')),
url(r'^units/', include('qatrack.units.urls')),
url(r'^issues/', include('qatrack.issue_tracker.urls')),
url(r'^maintenance/', include('qatrack.maintenance.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have gone through a lot of questions similar to this here and applied them but I still can't get the DetailView to work. I will really appreciate any help. Thanks. After making changes I encountered this traceback error
Internal Server Error: /maintenance/equipment1/ Traceback (most recent
call last): File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/urls/base.py",
line 77, in reverse
extra, resolver = resolver.namespace_dict[ns] KeyError: 'equipments'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/exception.py",
line 41, in inner
response = get_response(request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/base.py",
line 217, in _get_response
response = self.process_exception_by_middleware(e, request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/core/handlers/base.py",
line 215, in _get_response
response = response.render() File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/response.py",
line 107, in render
self.content = self.rendered_content File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/response.py",
line 84, in rendered_content
content = template.render(context, self._request) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/backends/django.py",
line 66, in render
return self.template.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 207, in render
return self._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 177, in render
return compiled_parent._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 177, in render
return compiled_parent._render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/test/utils.py",
line 107, in instrumented_test_render
return self.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/loader_tags.py",
line 72, in render
result = block.nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/defaulttags.py",
line 322, in render
return nodelist.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 990, in render
bit = node.render_annotated(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/base.py",
line 957, in render_annotated
return self.render(context) File "/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/template/defaulttags.py",
line 458, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File
"/home/blesjoe1/venvs/qatrack3/lib/python3.5/site-packages/django/urls/base.py",
line 87, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'equipments' is not a
registered namespace [14/May/2018 16:05:33] "GET
/maintenance/equipment1/ HTTP/1.1" 500 215728
Your url is not correct
instead of
url(r'^equipment(?:/(?P<pk>\d+))?/$', views.EquipmentDetailView.as_view(), name="equipment_detail"),
it should be:
url(r'^equipment/(?P<pk>\d+)/$', views.EquipmentDetailView.as_view(), name="equipment_detail"),
Update your DetailView with this:
class EquipmentDetailView(DetailView):
model = models.Equipment
template_name = 'maintenance/equipment_detail.html'
context_object_name = 'equipment'
You don't need to override default method if you are not doing anything extra than the DetailView offers.
Im trying to combine an add and edit form into one and am receiving an error The 'site_image' attribute has no file associated with it.
I could edit files but could not add files, but now when I load the site files page I am receiving the below error, I havent changed the model so am unsure as to why im receiving this error.
the list of files shouldn't really care if site_image is there or not as its set to blank and null?
my file model:
class SiteFiles(models.Model):
site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT)
site_image = models.ImageField(upload_to='site_files/', blank=True, null=True)
site_image_thumbnail = ImageSpecField(source='site_image',
processors=[ResizeToFill(200, 150)],
format='JPEG',
options={'quality': 60})
site_file = models.FileField(blank=True, upload_to=site_files_path, \
validators=[validate_file_extension])
file_name = models.CharField(max_length=200, verbose_name="File Name")
file_type = models.CharField(max_length=100, verbose_name='File Type', \
choices=settings.FILE_TYPE)
class Meta:
verbose_name = "Site Files"
verbose_name_plural = "Site Files"
def __str__(self):
return '%s | %s | %s ' % (self.site_data.location, self.site_data.location, self.file_name)
my forms.py
class FileForm(forms.ModelForm):
class Meta:
model = SiteFiles
fields = ['site_image', 'site_file', 'file_name','file_type']
def __init__(self, *args, **kwargs):
super(FileForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'file_form'
self.helper.form_method = 'POST'
self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary'))
self.helper.layout = Layout(
Div(
Div(
Div(
Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'),
Div(
Field('site_image', placeholder='Image'),
Field('site_file', placeholder='File'),
Field('file_name', placeholder='Display Name'),
Div('file_type', title="File Type"),
css_class='panel-body'
),
css_class='panel panel-default',
),
css_class='col-lg-3'
),
css_class='row'
),
)
my views.py
#login_required
#user_passes_test(lambda u: u.has_perm('sites.add_sitefile'))
def add_edit_file(request, site_id, item_id=None):
from sites.forms import FileForm
from sites.models import SiteFiles
site_data = get_object_or_404(SiteData, pk=site_id)
# set edit values
if item_id:
item_data = get_object_or_404(SiteFiles, pk=item_id)
form_type = 'Edit'
form = FileForm(instance=item_data)
else:
# set add values
form = FileForm()
form_type = 'Add'
item_data = SiteFiles()
# set posting
if request.method == 'POST':
form = FileForm(request.POST,instance=item_data)
if form.is_valid():
form.instance.site_data = site_data
form.save()
return redirect('sites:site_detail_files', site_id)
return render(request, 'sites/add_edit_file.html', {
'add_edit_file_form': form,
'SiteName' : site_data.location,
'SiteID' : site_id,
'ItemID' : item_id,
'FormType' : form_type
})
Error:
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in _resolve_lookup
882. current = current[bit]
During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/itapp/itapp/sites/views.py" in site_detail_files
311. 'active_files' : 'class="active"',
File "/usr/local/lib/python3.6/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/usr/local/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/usr/local/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
207. return self._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/usr/local/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
107. return self.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py" in render
72. result = block.nodelist.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/defaulttags.py" in render
216. nodelist.append(node.render_annotated(context))
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in render
202. resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in get_resolved_arguments
188. resolved_args = [var.resolve(context) for var in self.args]
File "/usr/local/lib/python3.6/site-packages/django/template/library.py" in <listcomp>
188. resolved_args = [var.resolve(context) for var in self.args]
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in resolve
708. obj = self.var.resolve(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in resolve
849. value = self._resolve_lookup(context)
File "/usr/local/lib/python3.6/site-packages/django/template/base.py" in _resolve_lookup
890. current = getattr(current, bit)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py" in url
69. self._require_file()
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/files.py" in _require_file
46. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
Exception Type: ValueError at /sites/site/files/7
Exception Value: The 'site_image' attribute has no file associated with it.
EDIT:
site_details_files:
#login_required
def site_detail_files(request, site_id):
files = SiteFiles.objects.filter(site_data__id=site_id)
try:
site = files[0].site_data
except:
site = get_object_or_404(SiteData, pk=site_id)
return render(request, 'sites/site_detail_files.html', {
'Files': files,
'SiteName' : site.location,
'SiteID' : site.id,
'PageType' : 'files',
'active_files' : 'class="active"',
})
template:
{% block content %}
<div class="col-lg-9">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-camera fa-fw"></i> Photos
</div>
<div class="panel-body">
{% get_file_type Files 'Cabinet Photo' as photos %}
{% for file in photos %}
<div class="img-item">
<div class="img">
<a class="image-float-left" id="" href="{% signed_url file.site_image.url %}" target="_blank">
<img src="{% signed_url file.site_image_thumbnail.url %}" alt="" />
</a>
</div>
<div class="img-text">
{{ file.file_name }}
<div class="img-edit" >
<a href="{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit"></i>
</a>
</div>
</div>
</div>
<!-- /.img-item-->
{% endfor %}
</div>
<!-- /.panel-body-->
</div>
<!-- /.panel-->
</div>
<!-- /.col-lg-9 -->
<div class="col-lg-3">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-file-text-o fa-fw"></i> Files
</div>
<div class="panel-body">
{% exclude_file_type Files 'Cabinet Photo' as site_files %}
{% for file in site_files %}
<ul>
{% if file.file_type != "Cabinet Photo" %}
{% if file.site_file %}
<li>
<a href="{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit fa-1x"></i>
</a>
{{ file.file_name }}
</li>
{% endif %}
{% if file.site_image %}
<li>
<a href="{{% url 'sites:edit_file' SiteID file.id %}" class="edit-icon">
<i class="fa fa-edit"></i>
</a>
{{ file.file_name }}
</li>
{% endif %}
{% endif %}
</ul>
{% endfor %}
</div>
<!-- /.panel-body-->
</div>
<!-- /.panel-->
</div>
<!-- /.col-lg-9 -->
{% endblock %}
You need to pass request.FILES to the form when uploading files.
form = FileForm(request.POST, request.FILES, instance=item_data)
Make sure that you set enctype="multipart/form-data" in the template as well.
See the docs on file uploads for more info.
However, these changes won't solve your error, since it is coming from a different view site_detail_files. It looks as if you are using file.site_image.url in the template without checking file.site_image first. You should add an extra if block:
{% for file in photos %}
...
{% if file.site_image %}
...
<a class="image-float-left" id="" href="{% signed_url file.site_image.url %}" target="_blank">
...
{% endif %}
{% endfor %}