attribute error 'function' object has no attribute 'has_header' - python

i have been encountered by this error
'function' object has no attribute 'has_header'
my url file contans
url(r'^HighDefs/$', list_HighDefs),
and i have a view defined with the name
list_HighDefs
in views file. I dont know whats wrong.
the view contains
def list_HighDefs(request):
user_logger = Logger()
user_logger.log_stack()
if user_object:
email = user_object.email
uname = user_object.first_name+' '+user_object.last_name
try:
row = allapps_models.highdef.objects.filter(user_email=email, show_status=1)
except Exception:
return error_page(request)
highdefs = []
for m in row:
order_product = int(m.m_id)
state = m.state
try:
category = checkout_models.state.objects.get(pk=product).premature.category.all()
category = category[0].pk
except:
category = 0
if int(category) == 2:
if state != 's':
highdefs.append(m)
return render_to_response('main/HighDefs.html',{'request': request, 'highdefs': highdefs, 'uname' :uname, 'email': email}, context_instance=RequestContext(request))
else:
return(login)

Your view must return an HttpResponse object.
It does this for one branch of your if statement:
return render_to_response(...)
But not in the else branch.
return(login)
If login is a view function that returns an HttpResponse object, then you can change your return statement to
return login(request)
However, I suspect you want to redirect the user to your login page instead. In that case, change your code to:
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/login/')
where /login/ is the url of your login page.

The last line of your view is return login (don't know why you're wrapping your returns in parentheses, it's unnecessary). But presumably login is a function, and you're not calling it. I expect you mean to do return login() or return login(request).

Related

'NoneType' object is not subscriptable. Where is the error? Used Django App with Pipeline

TypeError: 'NoneType' object is not subscriptable if
request['user_type']=='driver' and not Driver.objects.filter(user_id =
user.id): TypeError: 'NoneType' object is not subscriptable ```
def create_user_by_type(backend , user , request, response , *args, **kwargs):
if backend.name == 'facebook':
avatar = 'http://graph.facebook.com/%s/picture?type=large' % response['id']
if request['user_type'] == 'driver' and not Driver.objects.filter(user_id = user.id):
Driver.objects.create(user_id=user.id,avatar=avatar)
elif not Customer.objects.filter(user_id=user.id):
Customer.objects.create(user_id=user.id, avatar=avatar)
The error is most likely in request ['user_type'] == 'driver' as it works if I remove this from the code.
I am sending the request from POSTMAN
I check by parameter user_type
Used Pipeline from https://python-social-auth.readthedocs.io/en/latest/pipeline.html
If everything is correct, where can there be a mistake?
update create_user_by_type:
def create_user_by_type(backend, user, response, *args, **kwargs):
request = backend.strategy.request_data()
if backend.name == 'facebook':
avatar = 'http://graph.facebook.com/%s/picture?type=large' % response['id']
if request['user_type'] == 'driver' and not Driver.objects.filter(user_id = user.id):
Driver.objects.create(user_id=user.id,avatar=avatar)
elif not Customer.objects.filter(user_id=user.id):
Customer.objects.create(user_id=user.id, avatar=avatar)
The problem must lie in the object stored in variable request.
You get the value for request in a function which should return a complex object, which is subscriptable and has a field called 'user type'. Obviously, it did not return this object but just returned None, probably because of an i/o-error or an invalid argument.
Whatever function you use to get the request, I suggest checking, whether it works and what exactly it returns.

ValueError: The view create.views.CheckoutView didn't return an HttpResponse object. It returned None instead

I am getting a ValueError that the class below didn't return any httpresponse when i try to redirect to a template. the redirect is supposed to go to the stripe payment view.
here is an entire class that has the redirect call
class CheckoutView(View):
def get(self, *args, **kwargs):
form = forms.CheckoutForm()
context = {
'form': form
}
return render(self.request, "checkout.html", context)
def post(self, *args, **kwargs):
form = forms.CheckoutForm(self.request.POST or None)
try:
equipment_order = models.EquipmentOrder.objects.get(user=self.request.user, ordered=False)
if form.is_valid():
street_address = form.cleaned_data.get('street_address')
apartment_address = form.cleaned_data.get('apartment_address')
country = form.cleaned_data.get('country')
zip = form.cleaned_data.get('zip')
'''
TODO: add functionality to these fields
same_shipping_address = form.cleaned_data.get('same_shipping_address')
save_info = form.cleaned_data.get('save_info')
'''
payment_option = form.cleaned_data.get('payment_option')
billing_address = models.BillingAddress(
user=self.request.user,
street_address=street_address,
apartment_address=apartment_address,
country=country,
zip=zip
)
billing_address.save()
equipment_order.billing_address = billing_address
equipment_order.save()
if payment_option == 'S':
return redirect('create:payment', payment_option='stripe')
elif payment_option == 'P':
return redirect('create:payment', payment_option='paypal')
else:
messages.warning(self.request, "Invalid payment option")
return redirect('create:checkout')
except ObjectDoesNotExist:
messages.error(self.request, "You do not have an active order")
return redirect("create:order_summary")
1) Remove the try/except i think its better
2) I think you have a problem on 'payement_option' , maybe it doesnt give any value of expected , try to print it first to see what does it give
3) remove the ' or None ' from CheckoutForm
4) you can avoid using 'self' by importing form in that way :
from .forms import CheckoutForm
...
form = CheckoutForm(request.POST)
The above answer may work fine but as I tried your code it throws the same error as you described whenever you leave the form field empty or no payment method is selected.
After trying your code the best possible solution I figure out is this. I know this is not a perfect solution but it worked 😅
Suggestion: Try to move your else statement under if instead of nesting it after elif statement. And change your else to given below.
Old:
else:
messages.warning(self.request, "Invalid payment option select")
return redirect('core:checkout')
New:
else :
messages = 'Invalid payment option select'
return HttpResponse(messages)
Proof: Invalid payment option select

method reverse django error

I'm calling a method using reverse but I have problem argument that I am not able to understand.
My error :
Reverse for 'shopping.views.payment_confirmation' with arguments '(35,)' and keyword arguments '{}' not found.
My url:
url(r'^payment_confirmation/(?P<id>\d+\d{2\})/$', 'payment_confirmation', name='payment_confirmation'),
My view:
def show(request):
...
...
payment.submit(settings.SITE_URL + reverse("shopping.views.payment_confirmation", args=[payment.id]))
My model Payment:
class Payment(models.Model):
...
...
def submit(self, redirect_url):
'''
Sends self as a Payment through PagSeguro API.
Payment instance MUST BE SAVED before calling this method.
'''
if not self.id:
#Temporary to identify which problem caused the crash.
raise ValidationError
#creating a reference if its None
if self.reference is None:
self.reference = configs.PAGSEGURO_REFERENCE_PREFIX + str(self.id)
document = Document()
document.appendChild(self.to_element(document, redirect_url))
response = document2dict(api.submit_payment(document))
try:
self.code = response['checkout']['code']
self.answered_on = datetime.datetime.now()
self.save()
except:
error_str = ""
if type(response["errors"]["error"]) != list:
response["errors"]["error"] = [response["errors"]["error"]]
for error in response["errors"]["error"]:
error_payment = ErrorPayment()
error_payment.code = int(error['code'])
error_payment.payment = self
error_payment.save()
error_str += "[%s: %s]" % (error_payment.code,
error_payment.get_code_display())
raise Exception(error_str)
the error is here payment.submit (settings.SITE_URL + reverse ("shopping.views.payment_confirmation", args = [payment.id]))
I', using this api https://bitbucket.org/leonardosantos/django-pagseguro2/
This line: reverse("shopping.views.payment_confirmation", args=[payment.id]) tells Django to find a url that matches a method called payment_confirmation in the views.py file in the shopping app that will accept a payment ID parameter.
In the error that you shared, the payment.id was 35. The error is saying that either there is no method called payment_confirmation in your shopping.views or the method does not accept a single int as a parameter.
You didn't share a payment_confirmation method in your views file so it seems that that is the issue. You need to add:
def payment_confirmation(payment_id):
#do stuff
to your views.

Python return function error

While running this function to validate captcha key and value i am not able to return
it show error like this
"AttributeError: 'bool' object has no attribute 'status_code'"
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
if captchavalue == key:
return True
else:
return False
By reading the code and the error, I assume that validate is a view. A view must always return a HttpResponse. So if you want to return a response indicating a boolean value, indicating if captchavalue == key, do:
from django.http import HttpResponse
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
return HttpResponse(captchavalue == key)
I'm not 100% sure about the import line, but it's something very similar.
I don't know much Django, but it seems it expects you to return a response object instead of a bool value (True / False).
Maybe your code should like more like this:
if captchvalue == key:
return HttpResponse('HTML Page saying OK')
else:
return HttpResponse('HTML Page saying Error')

Context processors, passing a session which doesn't exist

Hay All, I've got a simple context processor which looks within a session and if a 'user' key exists. If it does i want to return it to the template.
Here's my context Processor
def get_user_details(request):
user = request.session['user']
data = {
'user':user
}
return data
and here is a sample view
def render_home(request):
return render_to_response("home", context_instance=RequestContext(request))
If the session['user'] doesn't exists, i want it to silently fail, or return False or Null.
Because the key doesnt exist within the session, i get a KeyError.
Any idea's how to fix this?
You can get a default value like None this way: request.session.get('user', None). Just like in normal Python dicts.
user = request.session.get('user', None)
or,
user = None
if 'user' in request.session:
user = request.session['user']
def get_user_details(request):
try:
user = request.session['user']
except KeyError:
return
data = {
'user':user
}
return data
Or if you want to catch it further away, do this instead:
def render_home(request):
try:
return render_to_response("home", context_instance=RequestContext(request))
except KeyError:
return

Categories