Django Add Edit Form - Field has no attribute assigned to it? - python

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 %}

Related

Fixing No Reverse Match in a Django Project

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
}
)

NoReverseMatch at /job_category/IT/

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})

How can I fix this searchbar error in django?

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.

How to establish a button function to my boolfield

''i want to add functionality to my Publish button in HTML. i have made a method under my Post(model) and made a view for that button with a url. i dont know why my button fuctn is not working.
''
My Post Model
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
description = models.TextField()
created_on = models.DateTimeField(default=timezone.now)
published = models.BooleanField(default=False)
def publish(self):
self.published=True
self.save()
def __str__(self):
return self.title
My Views.py
#login_required
def publish_button(request,pk):
post = get_object_or_404(Post,pk)
post.publish()
return redirect('blog_detail',pk=post.pk)
my urls.py
urlpatterns = [
path('comment/<int:pk>/', comment_post, name='comment_form'),
path('publish/',PublicList.as_view(),name='publish'),
path('publish/<int:pk>/',publish_button,name='p_button'),
path('', index, name='indexpage'),
]
My html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1>Blog Details:</h1>
<hr>
<div class="jumbotron">
<h3 align = 'center'>{{ detail.title }}</h3>
<hr>
<div class="mb-5">
<h4>{{ detail.description }}</h4>
</div>
<p>Posted By: {{ detail.user }}<span class="ml-5">{{ detail.created_on }} </span><br>
</div>
{{ detail.pk }}
Publish
<p></p>
<h6>Wanna add comment? <span class="ml-3">
<a href="{% url 'comment_form' pk=detail.pk %}">
<input class="btn btn-dark" type="button" name="" value="Comment">
</a></span>
</h6>
<hr>
<h4>Comments:-</h4>
<hr>
{% for comment in detail.comments.all %}
<h5>{{comment.text}}</h5>
<p>by: #{{comment.author}}<span class='ml-5'>{{comment.commented_on}} </span></p>
<hr>
{% endfor %}
</div>
{% endblock %}
TraceBack:
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv \lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\AngryBuLLz\Desktop\Django\prac_18\firstapp\views.py" in publish_button
71. post = get_object_or_404(Post,pk)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\shortcuts.py" in get_object_or_404
93. return queryset.get(*args, **kwargs)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\query.py" in get
390. clone = self.filter(*args, **kwargs)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\query.py" in filter
844. return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
862. clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\sql\query.py" in add_q
1263. clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\sql\query.py" in _add_q
1287. split_subq=split_subq,
File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\sql\query.py" in build_filter
1161. arg, value = filter_expr
Exception Type: TypeError at /publish/5/
Exception Value: cannot unpack non-iterable int object
get_object_or_404 takes a filter expression, exactly as if you were calling Products.objects.get()`. So it should be:
post = get_object_or_404(Post, pk=pk)

Getting Django Tables2 to work

I'm trying to get django_tables2 to work, but I keep getting an error. I already have it installed and it's already in my settings.
models.py
class Schedules(models.Model):
course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
frequency = models.CharField(max_length=128)
status = models.CharField(max_length=128, choices=STATUS_CHOICES)
interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
initiated_by = models.CharField(max_length=128, null=True)
schedule_id = models.IntegerField(default=0)
def save(self, flag=True, *args, **kwargs):
super(Schedules, self).save()
if flag:
self.schedule_id = self.id + 10000
self.save(flag=False, *args, **kwargs)
tables.py
import django_tables2 as tables
from schedule.models import Schedules
class ScheduleTable(tables.Table):
class Meta:
model = Schedules
views.py
from schedule.models import Schedules
from schedule.tables import ScheduleTable
def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
query = request.POST['course_name_search']
results = Schedules.objects.filter(course_name=query)
table = ScheduleTable(results)
if query:
context_dict['table'] = table
else:
context_dict['no_results'] = query
return render(request, "schedule/search_schedule.html", context_dict)
search_schedule.html
{% extends 'base.html' %}
{% load django_tables2 %}
{% block main_content %}
<form method="post" action="">
{% csrf_token %}
<label for="course_name_search">Course Name:</label>
<input type="text" name="course_name_search" id="course_name_search">
<input type="submit" name="submit">
</form>
<div id="result_panel">
{% if no_results %}
No results returned for <q>{{ no_results }}</q>
{% else %}
{% render_table table %}
{% endif %}
</div>
{% endblock %}
The error I'm getting is 'ValueError at /schedule/search_schedule/: Expected table or queryset, not str.' I'm pretty sure I followed the steps to the letter. What am I doing wrong?
Edit: Here's the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/schedule/search_schedule/
Django Version: 1.10
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'django_countries',
'localflavor',
'django_tables2',
'avtechpassport',
'students',
'billing',
'timesheet',
'wai_wdp',
'jobs',
'schedule']
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 /home/jerry22/PycharmProjects/avtechpassport_proj1/templates/schedule/search_schedule.html, error at line 38
Expected table or queryset, not str 28 : <form method="post" action="">
29 : {% csrf_token %}
30 : <label for="course_name_search">Course Name:</label>
31 : <input type="text" name="course_name_search" id="course_name_search">
32 : <input type="submit" name="submit">
33 : </form>
34 : <div id="result_panel">
35 : {% if no_results %}
36 : No results returned for <q>{{ no_results }}</q>
37 : {% else %}
38 : {% render_table table %}
39 : {% endif %}
40 : </div>
41 : {% endblock %}
Traceback:
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jerry22/PycharmProjects/avtechpassport_proj1/schedule/views.py" in search_Schedule
81. return render(request, "schedule/search_schedule.html", context_dict)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
208. return self._render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader_tags.py" in render
174. return compiled_parent._render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/loader_tags.py" in render
70. result = block.nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/defaulttags.py" in render
323. return nodelist.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render
994. bit = node.render_annotated(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django/template/base.py" in render_annotated
961. return self.render(context)
File "/home/jerry22/.virtualenvs/jerry_avtechpassport_project/lib/python3.6/site-packages/django_tables2/templatetags/django_tables2.py" in render
132. raise ValueError('Expected table or queryset, not {}'.format(klass))
Exception Type: ValueError at /schedule/search_schedule/
Exception Value: Expected table or queryset, not str
For a GET request, {% if no_results %} will evaluate to False, so Django tries to render a non-existent table in the {% else %} block.
You could do something like this instead.
{% if table %}
{% render_table table %}
{% else %}
{% if no_results %}
No results returned for <q>{{ no_results }}</q>
{% else %}
Please enter a search
{% endif %}
{% endif %}

Categories

Resources