keyError in Django. During template rendering - python

Sorry if its a noob code or question. I am doing pagination using django-pagination and I am doing it like this.But this gives me keyError at on my page furthermore it mentions that its an error during template rendering. What I am doing wrong here.I have successfully installed pagination, modified the settings.py file. But i dont know what i need to do here. Any help would be highly appreciated.
<table class="active_table" summary="active_user">
<thead>
<tr><th>Name</th><th>Mobile Number</th><th>Count</th></tr>
</thead>
<tbody id="table_content">
{% load pagination_tags %}
{% block content %}
{% autopaginate response_data 5 %}
{% for b in response_data %}
<tr class="table_rows"><td>{{ b.name }}</td><td>{{ b.mobile_number }}</td><td>{{ b.count }}</td></tr>
{% endfor %}
{% paginate %}
{% endblock %}
</tbody>
</table>
The detailed traceback is pasted here http://dpaste.com/919526/
The viewcode is following
views.py
#csrf_exempt
def active_user_table(request, b):
if request.method != "GET":
raise Http404
if (b=='4'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name,mobile_number,COUNT(*) as count, created FROM core_user,core_useractivity WHERE core_user.id = core_useractivity.user_id GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data':response_data})
elif (b=='3'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND MONTH(CAST(created as date)) = MONTH(NOW()) AND YEAR(cast(created as date)) = YEAR(NOW()) GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='2'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATEDIFF(NOW(), created) <= 7 GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='1'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATE(created) = DATE(NOW())")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
else:
raise Http404
Sorry I am not using django ORM as of now but I will do so in future.

You must add context_instance in render_to_response call:
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data}, context_instance=RequestContext(request))
or you can use TEMPLATE_CONTEXT_PROCESSORS tuple in your settings.py. Add this string "django.core.context_processors.request" to context processors and every RequestContext will contain a variable request.

I solved it myself but thanks to ndpu for helping me atleast I got confident there were no other issue but some settings issue. In this question I have problems with setting up django-pagination. Alasdair had mentioned adding "django.contrib.auth.context_processors.auth", to TEMPLATE_CONTEXT_PROCESSORS . On just adding it I am getting the correct expected values.

For those who are using the render shortcut
and still facing this error, just add {'request': request } to the context variable
context = { ..., 'request':request}
return render(request, 'templatename.html', context)

I also face this error earlier. I was getting following error:
Internal Server Error: /cancel-email/
Internal Server Error: /cancel-email/
Traceback (most recent call last):
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 506, in parse
compile_func = self.tags[command]
KeyError: 'static'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/var/www/recruiter-new/recruiter/scheduler.py", line 803, in cancelEmail
return render(request,'scheduler/cancel-email-part.html',{"cancel_email" :EmailDetail})
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 96, in render_to_string
template = get_template(template_name, using=using)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 32, in get_template
return engine.get_template(template_name, dirs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 40, in get_template
return Template(self.engine.get_template(template_name, dirs), self)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 190, in get_template
template, origin = self.find_template(template_name, dirs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 157, in find_template
name, template_dirs=dirs, skip=skip,
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loaders/base.py", line 46, in get_template
contents, origin, origin.template_name, self.engine,
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 189, in __init__
self.nodelist = self.compile_nodelist()
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 230, in compile_nodelist
return parser.parse()
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 508, in parse
self.invalid_block_tag(token, command, parse_until)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 568, in invalid_block_tag
"or load this tag?" % (token.lineno, command)
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 74: 'static'. Did you forget to register or load this tag?
[07/Aug/2018 08:43:26] "POST /cancel-email/ HTTP/1.1" 500 20789
I tried some google solutions but couldn't resolved, then finally again check my code and found a silly mistake on template file.
Just add:
{% load static %}
on top of your template file.

Related

WTForms Field shows up when run, but has Unbound problems

I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
#app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_form, action='/appliance2', method='POST')
forms.py (I created that validator using the template from the wtForms docs)
class DBPresenceCheck(object):
def __init__(self, table, message="Field is invalid"):
self.table = table
self.message = message
def __call__(self, form, field):
presence = Connector().query('SELECT 1 FROM %(table)s WHERE %(col_name)s = %(data)s LIMIT 1;',
{'col_name': field.label, 'data': field.data, 'table': self.table})
if presence == 1:
raise ValidationError(self.message)
class EmailForm(FlaskForm):
title = "Enter Household Info"
subtitle = "Please enter your email address:"
email_input = StringField("email", validators=[email(),
DBPresenceCheck('Household', 'That email is already present in the database.')])
# print(email_input.data)
submit = SubmitField("Submit")
email-form.html
{% extends "base.html" %}
{% block content%}
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<h2 class="display-5 fw-bold">{{ template_form.title }}</h2>
<p class="col-md-8 fs-4">{{ template_form.subtitle }}</p>
<form action="{{ action }}" method="{{ method }}">
<div id="main_elements">
{{ template_form['email_input']() }}
</div>
<div id="submit_element">
<br>
{{ template_form["submit"](class_="btn btn-primary") }}
</div>
</form>
</div>
</div>
{%endblock%}
I first realized something was wrong when I was testing the validation, and neither validator ever threw. I added the print statement in forms, and now, when I use flask run, I get the following error.
Traceback (most recent call last):
File "C:\Languages\Python\3.9\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Languages\Python\3.9\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 1047, in main
cli.main()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\decorators.py", line 84, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 911, in run_command
raise e from None
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 897, in run_command
app = info.load_app()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 312, in load_app
app = locate_app(import_name, None, raise_if_not_found=False)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 218, in locate_app
__import__(module_name)
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\app.py", line 4, in <module>
from forms import *
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 33, in <module>
class EmailForm(AddForm):
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 37, in EmailForm
print(email_input.data)
AttributeError: 'UnboundField' object has no attribute 'data'
If the print statement is just print(email_input), then when I run it, the following output
<UnboundField(StringField, ('email',), {'validators': [<wtforms.validators.Email object at 0x0000024145A4F460>, <forms.DBPresenceCheck object at 0x0000024145A4F610>]})>
but no errors are thrown. It seems strange to me that the error is thrown before the field is even created.
In the validators list you need to pass in an instance of class Email. So you field should read:
from wtforms.validators import Email
email_input = StringField("email", validators=[Email(), ...
and don't forget to install the email package as Flask-WTF doesn't include anymore the Email in their validators.

AttributeError: type object 'Project' has no attribute '_meta'

I encountered the following in my Django files when I attempt to use the class based view CreateView.
AttributeError at /overview/new/
type object 'Project' has no attribute '_meta'
I have no idea why the _meta attribute is not there. I inherited my model from models.Model as usual, but I can't find any questions that have the same problem. I posted my files down below, can somebody help me fix this problem?
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
from django.views.generic import ListView, DetailView, CreateView
from projects.models import Project, Task
class CreateProject(CreateView):
model = Project
fields = ['title', 'description']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
models.py:
from django.db import models
from django.contrib.auth.models import User
from .CustomIDConstructor import ID
class Project(models.Model):
title = models.CharField(max_length=100, default='No title')
description = models.TextField(default='No description')
author = models.ForeignKey(User, on_delete=models.CASCADE)
customid = models.CharField(max_length=30, default=ID, editable=False, primary_key=True)
def __str__(self):
return self.title
urls.py:
from django.urls import path
from . import views
from projects.views import ProjectsOverview, Project, CreateProject
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', login_required(views.ProjectsOverview.as_view()), name='projects-projectsoverview'),
path('project/<pk>/', login_required(views.Project.as_view()), name='projects-project'),
path('new/', login_required(views.CreateProject.as_view()), name='projects-newproject')
]
Project_form.html:
{% extends "home/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-4">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<button style="background-color:rgb(130, 130, 130); color:white; border: none" class="btn btn-outline-info" type="submit">Create new project</button>
</form>
</div>
{% endblock content %}
Full traceback:
Internal Server Error: /overview/new/
Traceback (most recent call last):
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 32, in get_form
form_class = self.get_form_class()
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 551, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 256, in __new__
apply_limit_choices_to=False,
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 139, in fields_for_model
opts = model._meta
AttributeError: type object 'Project' has no attribute '_meta'
[05/Mar/2019 14:00:15] "GET /overview/new/ HTTP/1.1" 500 115370
From your URLs, it looks like you have a view Project which is clashing with the model Project.
path('project/<pk>/', login_required(views.Project.as_view()), name='projects-project'),
The simplest fix would be to rename that view, for example to ProjectDetail, and update the URL pattern.

Error while creating query_string in flask

I have written an flask app.
This app allow users to upload images, if i run this app locally this app uploads images and saves it to the path which i have designated
Now i want to create a query string for my app where i will create urls and send it to people to upload images.
but when i run my app i receive this error
werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?
Traceback (most recent call last)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\prince.bhatia\Desktop\python-projects\new\app.py", line 77, in index
return render_template('index.html', property_id= property_id)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "C:\Users\prince.bhatia\Desktop\python-projects\new\templates\index.html", line 14, in top-level template code
{{ dropzone.create(action_view='index') }}
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_dropzone\__init__.py", line 330, in create
action_url = url_for(action_view, **kwargs)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 356, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2061, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\helpers.py", line 345, in url_for
force_external=external)
File "C:\Users\prince.bhatia\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\routing.py", line 1776, in build
raise BuildError(endpoint, values, method, self)
werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you forget to specify values ['property_id']?
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.
You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:
dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
Below is my code:
from flask import Flask, redirect, render_template, request, session, url_for, send_file
from flask_dropzone import Dropzone
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask_sqlalchemy import SQLAlchemy
import os
import psycopg2
import csv
app = Flask(__name__)
db = SQLAlchemy(app)
dropzone = Dropzone(app)
#app.config["SQLALCHEMY_DATABASE_URI"]="postgres://qpnwgdxnihlitm:22e4f6cbdb773f69aa468b2b7ddcd692552cb4102367ffc14c62f19403636477#ec2-54-243-223-245.compute-1.amazonaws.com:5432/d1ssufnnr78nll?sslmode=require"
app.config["SQLALCHEMY_DATABASE_URI"]= "postgresql://postgres:prince#25#localhost/images"
#app.config["SQLALCHEMY_DATABASE_URI"]='postgres://mapvmydehdyncf:7500963c956e3d5556df4a5f4fdd1a9a40f023c922bfe93194fb13b9322c86ad#ec2-23-21-165-188.compute-1.amazonaws.com:5432/d6lmau9918afdq?sslmode=require'
app.config['SECRET_KEY'] = 'supersecretkeygoeshere'
# Dropzone settings
app.config['DROPZONE_UPLOAD_MULTIPLE'] = True
app.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True
app.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'
app.config['DROPZONE_REDIRECT_VIEW'] = 'results'
# Uploads settings
app.config['UPLOADED_PHOTOS_DEST'] = '/uploads'
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app) # set maximum file size, default is 16MB
class Data(db.Model):
__tablename__ = "image"
id=db.Column(db.Integer, primary_key=True)
link = db.Column(db.String(1000000), unique=True)
def __init__(self, link):
self.link = link
#app.route("/<string:property_id>", methods=['GET', 'POST'])
def index(property_id):
# set session for image results
if "file_urls" not in session:
session['file_urls'] = []
# list to hold our uploaded image urls
file_urls = session['file_urls']
# handle image upload from Dropszone
if request.method == 'POST':
file_obj = request.files
for f in file_obj:
file = request.files.get(f)
# save the file with to our photos folder
filename = photos.save(
file,
name=file.filename
)
# append image urls
file_urls.append(photos.url(filename))
d = file_urls.append(photos.url(filename))
for i in file_urls:
data = Data(i)
db.session.add(data)
db.session.commit()
session['file_urls'] = file_urls
return "uploading..."
# return dropzone template on GET request
return render_template('index.html', property_id= property_id)
#app.route('/results')
def results():
# redirect to home if no images to display
if "file_urls" not in session or session['file_urls'] == []:
return redirect(url_for('index'))
# set the file_urls and remove the session variable
file_urls = session['file_urls']
session.pop('file_urls', None)
dms = set(file_urls)
get_length = len(dms)
return render_template('results.html', dms=dms, get_length=get_length)
#app.route('/dashboard')
def dashboard():
conn = psycopg2.connect("dbname='images' user='postgres' password='prince#25' host='localhost' port='5432' ")
print(conn)
cur = conn.cursor()
data = cur.execute("SELECT DISTINCT link FROM image")
m_dict = cur.fetchall()
filename = "Productivity.csv"
with open("./"+filename,'w', encoding="utf-8") as csvfile:
csvfile = csv.writer(csvfile, m_dict)
csvfile.writerow(["Link"])
for i in range(0, len( m_dict )):
csvfile.writerow( m_dict[i] )
news = cur.execute("DELETE FROM image")
conn.commit()
return send_file(filename, attachment_filename="Data.csv", as_attachment=True)
if __name__=="__main__":
app.run(debug=True)
#app.run(debug=True)
this my index.html
<!DOCTYPE html>
<html>
<head>
<title>99Acres</title>
{{ dropzone.load() }}
{{ dropzone.style('border: 2px dashed #0087F7; margin: 10%; min-height: 400px;') }}
</head>
<body style="background-color:teal">
<!--<h1 style="color:white;">99Acres</h1>-->
<img align="right"src="https://img-d02.moneycontrol.co.in/news_image_files/2015/356x200/9/99acres_1902_356.jpg" width="80" height="80" alt="me">
<h1 align="center" style="color:white">Welcome to 99acres image upload website</h1>
<h3 align="center"style="color:white">Please Upload images in format[".JPG",".PNG",".JPEG"]</h3>
<h3 align="center" style="color:white">**Please Note:Maximum Total image size is 5MB</h3>
{{ dropzone.create(action_view='index') }}
<div class="list" align="center">
<strong>Our Partners:</strong> Naukri.com-
Jeevansathi Matrimonials- ICICIcommunities.org <br>
<br>
Home || About Us ||
Advertise with us || Terms and Conditions ||
Contact us || Reques1t info<br>
<br>
All rights reserved 2001 Info Edge India Ltd.
</div>
</body>
</html>
this is my results.html
<body style="background-color:teal">
<h1 align="center" style="color:white">Below Images Uploaded Successfully</h1>
Back<p>
<ul>
{% for file_url in dms %}
<img style="height: 150px" src="{{ file_url }}">
{% endfor %}
</ul>
<h1 align="center" style="color:white">You can close this page or upload more image</h1>
<h1 align="center" style="color:white">Total number of images are : {{get_length}}</h1> <br><br><br><br>
<div class="list" align="center">
<strong>Our Partners:</strong> Naukri.com-
Jeevansathi Matrimonials- ICICIcommunities.org <br>
<br>
Home || About Us ||
Advertise with us || Terms and Conditions ||
Contact us || Reques1t info<br>
<br>
All rights reserved 2001 Info Edge India Ltd.
</div>
</body>
I have read this posts:
werkzeug.routing.BuildError: Could not build url for endpoint 'success'. Did you forget to specify values ['name']?
How do you get a query string on Flask?
werkzeug.routing.BuildError: Could not build url for endpoint
render_template('index.html', property_id= property_id)
Your index.html does not use property_id. You can discard the property_id argument if index.html indeed do not need it
in index.html, line 14
dropzone.create(action_view='index')
action_url = url_for(action_view, **kwargs)
the later url_for would invoke index() method again, but missed the argument property_id, and moreover it seemed that you are making a recursive call!

How to make correct revert to specific version in django-reversion?

I have 2 question cause little bit comfused with django-reversion app. I have page where users can see list all of reversions. Every version has button to revert.
1 Question: How to show only some fields of changes. Right now it shows me all fields. I use version.field_dict.items.
2 Question: How to make correct revert to specific version?
Here below you can see code but it raise Error in views.py when I try to click to revert link. What I did wrong?
template.html
{% for version in versions %}
{% for field_name, field_value in version.field_dict.items %}
{{ field_name }}
{{ field_value }}
{% endfor %}
REVERT
{% endfor %}
urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_code>[0-9a-f-]+)/(?P<group_reversion_id>\d+)/$',
group_revert,
name='group_revert'),
views.py:
def group_revert(request, project_code, group_code, group_reversion_id):
project = get_object_or_404(Project, pk=project_code, status='open')
group = get_object_or_404(Group, pk=group_code)
versions = Version.objects.get_for_object(group)
versions[group_reversion_id].revision.revert()
return redirect('project:project_detail', project_code=project.code)
ERROR:
Internal Server Error: /ru/account/dashboard/projects/42442299-97dd-4d92-9ef1-880f9cdd1612/4d3d3422-2618-4d66-96f5-8f0a0b5d9bf3/21/
Traceback (most recent call last):
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
response = get_response(request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 198, in group_revert
versions[group_reversion_id].revision.revert()
File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 271, in __getitem__
raise TypeError
TypeError
I found the answer to this question: dhango-reversion

Flask application on google app engine - Showing database object

I'm trying to make a flask app on google app engine which shows database entries on their own page.
This is a bit of my views.py code:
#app.route('/posts/<int:id>')
def display_post(id):
post = Post.filter('id =', id)
return render_template('display_post.html', post=post)
Then my display_posts.html
{% extends "base.html" %}
{% block content %}
<ul>
<h1 id="">Post</h1>
<li>
{{ posts.title }}<br />
{{ posts.content }}
</li>
</ul>
{% endblock %}
Now when I have a post with ID 5700305828184064 and visit this page I should see the title and content:
www.url.com/posts/5700305828184064
However I get this traceback:
<type 'exceptions.AttributeError'>: type object 'Post' has no attribute 'filter'
Traceback (most recent call last):
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/main.py", line 4, in <module>
run_wsgi_app(app)
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 99, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 117, in run_bare_wsgi_app
result = application(env, _start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 874, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 864, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/blog/views.py", line 25, in display_post
post = Post.filter('id =', id)
How can I show the title and content of the entry for a given ID?
You need to create a query object first, then apply the filter to that.
q = Post.all()
post = q.filter("id =", id)
This is the first example in the GAE docs on queries.
Also, your template references the name posts, but you've passed in the name post. Change your template appropriately.

Categories