AttributeError: 'tuple' object has no attribute 'get' in views.py - django

i want to create a registration form but i m getting an attribute error while running the application
from django.shortcuts import render
from basic_app.forms import UserForm,UserProfileInfoForm
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered=False
if request.method=="POST":
user_form=UserForm(data=request.POST)
profile_form=UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_from.is_valid():
user=user_form.save()
user.setpassword(user.password)
user.save()
profile=profile_form.save(commit=False)
profile.user=user
if 'profile_pic' in request.FILES:
profile.profile_pic=request.FILES['profile_pic']
profile.save()
registered=True
else:
print(user_form.errors,profile_form.errors)
else:
user_form=UserForm()
profile_form=UserProfileInfoForm()
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
output
Internal Server Error: /basic_app/register/
Traceback (most recent call last):
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\utils\deprecation.py", line 93, in call
response = self.process_response(request, response)
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'tuple' object has no attribute 'get'
[24/Dec/2018 15:34:51] "GET /basic_app/register/ HTTP/1.1" 500 61448

That is because of this line:
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
You've actually created a tuple here. Notice the the parenthesis around the three things that you're returning?
This is how you render a template in django:
from django.shortcuts import render
render(request, 'polls/index.html', context)
So in your case this will work:
render(request,'basic_app/registration.html', {
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
For more information on render check out its docs

Change this
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
to
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})

Related

How to fix TypeError: validate() got an unexpected keyword argument 'extra_validators'?

I've put together basic login/register forms in a flask app using WTForms. I included parts of code from two files that I thought might be relevant.
I am getting the error:
Traceback (most recent call last):
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 2548, in __call__
return self.wsgi_app(environ, start_response)
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 2528, in wsgi_app
response = self.handle_exception(e)
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions\[rule.endpoint\])(\*\*view_args)
File "/home/neon/flask-app/src/accounts/views.py", line 18, in register
if form.validate_on_submit():
File "/home/neon/flask-app/venv/lib/python3.8/site-packages/flask_wtf/form.py", line 86, in validate_on_submit
return self.is_submitted() and self.validate(extra_validators=extra_validators)
TypeError: validate() got an unexpected keyword argument 'extra_validators'
This is my code:
src/accounts/forms.py
from flask_wtf import FlaskForm
from wtforms import EmailField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo, Length
from src.accounts.models import User
class RegisterForm(FlaskForm):
email = EmailField(
"Email", validators=[DataRequired(), Email(message=None), Length(min=6, max=40)]
)
password = PasswordField(
"Password", validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
"Repeat password",
validators=[
DataRequired(),
EqualTo("password", message="Passwords must match."),
],
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
if self.password.data != self.confirm.data:
self.password.errors.append("Passwords must match")
return False
return True
src/accounts/views.py
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import login_required, login_user, logout_user, current_user
from src import bcrypt, db
from src.accounts.models import User
from .forms import LoginForm, RegisterForm
accounts_bp = Blueprint("accounts", __name__)
#accounts_bp.route("/register", methods=["GET", "POST"])
def register():
if current_user.is_authenticated:
flash("You are already registered.", "info")
return redirect(url_for("core.home"))
form = RegisterForm(request.form)
if form.validate_on_submit():
user = User(email=form.email.data, password=form.password.data)
db.session.add(user)
db.session.commit()
login_user(user)
flash("You registered and are now logged in. Welcome!", "success")
return redirect(url_for("core.home"))
return render_template("accounts/register.html", form=form)
It's throwing an error in the register function at the second conditional on form.validate_on_submit(). I looked at the WTForms documentation, and from what I could understand, the validate() function is supposed to take an argument extra_validators. So I don't understand why it would be throwing this error.
Full disclosure, I was following a tutorial, and did compare my code to their final code and it matched.
What am I missing here?
You ignore that validate takes additional parameters. If you add this in your implementation it should work.
def validate(self, extra_validators=None):
initial_validation = super(RegisterForm, self).validate(extra_validators)
# ...

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

no search results Django 2.1 Solr 6.5

I implemented solr 6.5 for django 2.1 with haystack 2.5 and i succesfully built index but theres still no search results
q*:* returns
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"on",
"wt":"json",
"_":"1543140724323"}},
"response":{"numFound":5,"start":0,"docs":[
{
"id":"blog.post.1",
"django_ct":["blog.post"],
"publish":["2019-05-26T04:46:00+00:00Z"],
"text":["Chwalmy wodza\nsanacja, wódz, historia, sumienie\nBo jeden jest wódz\n\n"],
"django_id":[1],
"_version_":1618099571920994304},
{
"id":"blog.post.3",
"django_ct":["blog.post"],
"publish":["2018-11-15T20:59:39+00:00Z"],
"text":["Trwoga Krzyk Gardłowy\nwódz\nsome\n\n"],
"django_id":[3],
"_version_":1618099571923091456},
{
"id":"blog.post.4",
"django_ct":["blog.post"],
"publish":["2018-11-15T21:24:01+00:00Z"],
"text":["Jeszcze jeden post\nsanacja, wódz\nChwalmy wodza\n\n"],
"django_id":[4],
"_version_":1618099571924140032},
{
"id":"blog.post.5",
"django_ct":["blog.post"],
"publish":["2018-11-21T14:41:25+00:00Z"],
"text":["Yep\nsanacja, wódz\nffff\n\n"],
"django_id":[5],
"_version_":1618099571925188608},
{
"id":"blog.post.7",
"django_ct":["blog.post"],
"publish":["2018-11-21T21:30:30+00:00Z"],
"text":["Markdown\nhistoria, sanacja, wódz\n*wyróżnienie* **pogrubienie**\nlistę:\n\n\n\n\nSometimes you want bullet points:\n\n* Start a line with a star\n* Profit!\n* Start a line with a star\n* Else\n\nTutaj jest [sabaton](https://www.youtube.com/watch?v=_HLNMfCBUb0)\n\n"],
"django_id":[7],
"_version_":1618099571925188609}]
So core is populated
My view:
def post_search(request):
form = SearchForm()
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
results = SearchQuerySet().models(Post)\
.filter(content=cd['query']).load_all()
# Obliczenie całkowitej liczby wyników.
total_results = results.count()
return render(request,
'blog/post/search.html',
{'form': form,
'cd': cd,
'results': results,
'total_results': total_results})
else:
return render(request,
'blog/post/search.html',
{'form': form})
And my form
class SearchForm(forms.Form):
query = forms.CharField()
I tried procedure proposed by haystack itself
>>> from haystack.query import SearchQuerySet
>>> sqs = SearchQuerySet().all()
>>> sqs.count()
But I only recived
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/query.py", line 522, in count
return len(self)
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/query.py", line 86, in __len__
self._result_count = self.query.get_count()
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/backends/__init__.py", line 619, in get_count
self.run()
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/backends/solr_backend.py", line 802, in run
results = self.backend.search(final_query, **search_kwargs)
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/backends/__init__.py", line 33, in wrapper
return func(obj, query_string, *args, **kwargs)
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/backends/solr_backend.py", line 149, in search
distance_point=kwargs.get('distance_point'))
File "/home/hesmeron/first_env/lib/python3.5/site-packages/haystack/backends/solr_backend.py", line 425, in _process_results
app_label, model_name = raw_result[DJANGO_CT].split('.')
AttributeError: 'list' object has no attribute 'split'
So here's the problem, posts are indexed but unable to search and I really run out of ideas at this point

Flask-Login: KeyError: 'security' when trying to call login_user

I have the following code that logs in a user on my Flask application:
#app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
db = get_db()
member = member_from_phone(request.form['phone_number'])
member_obj = Member(member)
if member is None:
g.result = json.dumps({'head' : 200, 'body' : "invalid phone" })
return 'no member...'
elif request.form['password'] == member['password']:
login_user(member_obj)
return 'login successful'
else:
return 'login failed'
return home_page()
However it throws a KeyError: 'security' when I try log in:
File "/Library/Python/2.7/site-packages/flask_security/utils.py", line 64, in login_user
if _security.trackable:
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Library/Python/2.7/site-packages/flask_security/utils.py", line 35, in <lambda>
_security = LocalProxy(lambda: current_app.extensions['security'])
KeyError: 'security' when trying to call login_user
I have no idea what's going on, I think I might need to fix my flask configuration but I don't know how.

django custom templatetag not getting request in context

I am using django 1.4 and trying to convert the code described at the end of this article into a customtag. This means I need access to the is_secure and site_name values from the request. Here is my CONTEXT_PROCESSORS in settings.py:
CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)
Here is my template tag code:
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def full_static_url(context, url):
request = context['request']
scheme = 'http'
if request.is_secure:
scheme += 's'
return scheme + '://' + request.site_name + context['STATIC_URL'] + url
In my view code I am using the new render shortcut like so:
return render(request, 'myapp/mytemplate.html', {'foo':bar})
And I am calling it like this in the template:
{% full_static_url "images/logo.gif" %}
The problem is, when it gets to the line request = context['request'] it throws a KeyError because 'request' is not in context.
What am I doing wrong here?
Full traceback is:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Projects\blah\blah\myapp\views\myview.py" in manifestcosts
44. return render(request, 'myapp/mytemplate.html', {'foo':bar})
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render
44. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
176. return t.render(context_instance)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
185. nodelist.append(node.render(context))
File "C:\Python27\lib\site-packages\django\template\base.py" in render
1107. return func(*resolved_args, **resolved_kwargs)
File "C:\Projects\blah\blah\myapp\templatetags\mytags.py" in full_static_url
25. request = context['request'] #TODO this fails with an KeyError, don't know why
File "C:\Python27\lib\site-packages\django\template\context.py" in __getitem__
54. raise KeyError(key)
Exception Type: KeyError at /myapp/myurl/110505081136179000/
Exception Value: 'request'
The right way to fix this issue is to add TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",) on your settings.py file.
Ensure to import TEMPLATE_CONTEXT_PROCESSORS first with from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS or it will not work.
Most likely the problem is you are rendering your template using regular context, that is something like this:
return render_to_response("myapp/template.html", {"some_var": a_value})
Remember that context processors are only applied to RequestContext instances. That means you have to either explicitly create a RequestContext in your render_to_response call:
return render_to_response("myapp/template.html", {"some_var": a_value},
context_instance=RequestContext(request))
or even better, use the new render shortcut:
return render(request, "myapp/template.html", {"some_var": a_value})
I solved it by changing
return render(request, 'myapp/mytemplate.html', {'foo':bar})
to
return render( RequestContext(request), 'myapp/mytemplate.html', {'foo':bar})
I hope this helps someone else, I wasted about 8 hours :p
I had this happen in a template.Node object in the render(). It turned out that sometimes the context had 'request' in it, other times it didn't.
Like someone else suggested, RequestContext(request) is the key. My guess is that sometimes the context is called without the request being initialized like that.
I changed my function from
def render(self, context):
request = context['request'] # Failing here
to
def render(self, context):
request = RequestContext(context)['request']['request']
and it all came right.
This will force a request object in case the context object wasn't initialized properly. For some reason I had to add ['request'] twice, but it seems to work fine
EDIT: I spoke too soon, seems a blank context can't be fixed. Instead you could try a workaround:
request = context.get('request')
if request is None:
return ''
My page still seems to work fine, so I'm not exactly sure where these bad contexts are coming from.