Django Displaying Attribute Error - python

I want to send a mail to every user that fill a form on my django website. After writing a code for it, I'm getting the below error. I've been trying to find the cause of the error but no success. Below are my codes:
AttributeError at /meek/
'NoneType' object has no attribute 'e_mail'
Views
Subject='Welcome'
message=loader.get_template('letter.txt')
from_email='men#men.com'
def gent_me(request):
if request.method=='POST':
form=GentForm(request.POST)
if form.is_valid():
data=form.cleaned_data
newgent=Gent(
pub_date=datetime.datetime.now(),
full_name=data['full_name'],
company_name=data['company_name'],
services=data['services'],
e_mail=data['e_mail'],
address=data['address'],
city=data['city'],
state=data['state'],
phone_no=data['phone_no'])
invite=newgent.save()
send_mail(Subject, message.render(Context()),from_email,[invite.e_mail])
return HttpResponse('Thanks. Kindly check your mail.')
else:
return HttpResponse('Kindly fill form.')
else:
return render_to_response('ment.html',{'GentForm':GentForm},context_instance=RequestContext(request))
How can I fix this?

The Model.save method has a return value of 'None'. So 'invite' after invite=newgent.save() is None. Instead of
invite=newgent.save()
you should do
newgent.save()
and then
send_mail(Subject, message.render(Context()),from_email,[newgent.e_mail])

Related

Form object not iterable in Django

I want to assign the input of a form to a function in my view but I keep getting this error. Please help do I fix it.
Error
receiver = list(ToolsForm.declared_fields['receiver_mail'])
TypeError: 'CharField' object is not iterable
You can obtain the value associated with the receiver_mail field with:
receiver = form.cleaned_data['receiver_mail']
so without using list(…) part and with .cleaned_data [Django-doc], the form should be an instance of ToolForm, not a reference to the ToolForm class. Before you can retrieve the data, you will first need to validate the form, so:
form = ToolsForm(request.POST, request.FILES)
if form.is_valid():
receiver = form.cleaned_data['receiver_mail']

Django. Show error message on current page

Help me please! I'm trying to show error message:
In forms:
def clean_form(self):
url = self.cleaned_data['text']
if url == 'qwe':
raise ValidationError("Error")
return self.cleaned_data
In view:
def main_site(request):
if request.method == 'POST':
form = Form(request.POST or None)
if form.is_valid():
form.clean_form()
link = form.cleaned_data['text']
...
But when I send 'qwe' in form:
And press 'send'. Take:
But I want to see Error on same page. What's I should be do?
Thank you!
You are only checking the text field, therefore you should override the clean_text method.
def clean_text(self):
url = self.cleaned_data['text']
if url == 'qwe':
raise ValidationError("Error")
return url
Remove the clean_form() line from your code. Django will automatically call the clean_text method for you when you check if form.is_valid().
See the docs on cleaning a specific field for more info.
If you were checking multiple fields at the same time, then you would override clean. See the docs on cleaning fields that depend on each other for more information about that.

Django - login()-function seems broken

After being forced to leave PHP behind and work a bit with Python and Django I have hit a little problem.
What I'm trying to do is to use the built-in user-authentication that comes with Django. Problem is that when I'm trying to use the "login()" function it doesn't save the user in the session, or wherever it should be saved.
My code looks like this:
#csrf_exempt
def dologin(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
return render_to_response('bsys/profile.html', {'message': 'Success!', 'user': request.user.get_full_name()})
else:
# Return a 'disabled account' error message
return render_to_response('bsys/login.html', {'message': 'Disabled!'})
else:
# Return an 'invalid login' error message.
return render_to_response('bsys/login.html', {'message': 'Sumthin Wong!'})
So problem is when I run:
request.user.get_full_name()
It says:
Exception Type: AttributeError
Exception Value: 'AnonymousUser' object has no attribute 'get_full_name'
So apparently it doesn't log in the user.
When I do the same, but using:
user.get_full_name()
It works, then the authenticate-function apparently works well too. So there is something about login(), I guess.
What I also tried was to login via the admin-login as an admin, then using the same request.user.get_full_name() from another view and it works fine.
Any ideas to solve this? Maybe I just missed some essential part of the framework.
I think the way you check that the user is logged in is causing this.
instead of:
if user is not None:
try with:
if user.is_authenticated:
This was it will get round the AnonymousUser case.
(it may be, don't remember from the top of my head)
if user.is_authenticated():
Why are you rendering a template on successful login? Like with all POSTed HTTP requests, it's a good idea to redirect on success to reduce the chance of the user resubmitting the request.
More relevantly, I believe this will fix your problem because the templates, when they get their context populated with the auth context processor, will have their {{ user }} variable set to the value of request.user, which is an anonymous user at the beginning of the request. If you redirect, the new request will have a non-anonymous request.user, so the template's value should be populated properly.

Django query not working

Here's the thing. I have a model called User and an attribute counter that counts the number of page access. So, if a user already exists, I have to query up the db and for that user only to increase in counter. Otherwise, create a new user. I have an annoying error in the get method. How can I surpass it? if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
u = form.save()
try:
obj = User.objects.get(user=u.user)
obj.counter += 1
obj.ipaddress = request.META['REMOTE_ADDR']
obj.save()
except Statistic.DoesNotExist:
ip = request.META['REMOTE_ADDR']
obj = User(user=u.user, counter=1, ipaddress=ip)
obj.save()
return {'status': 'OK'}
else:
return {'errors': form.errors}
return {'status': 'NOT OK. GET method'} Here's the errorget() returned more than one User -- it returned 2! Lookup parameters were
Django has amazing documentation on their QuerySet API. https://docs.djangoproject.com/en/dev/ref/models/querysets/
get only returns exactly 1 queryset. If no queryset is found, or more then 1 queryset is returned, an error is raised.
To catch this particular error you have to specify except User.MultipleObjectsReturned,
This means there are multiple users matching the query in your database. get should be used to fetch only one. It seems you are already coding for this but I think you are catching the wrong exception type. Try changing
except Statistic.DoesNotExist:
To
from django.core.exceptions import DoesNotExist
except DoesNotExist:

'WSGIRequest' object is not subscriptable

I'm getting this error in this function in my views.py file. It's confusing because I don't know what 'WSGIRequest' is or why it's giving me problems. I know I have a variable called "newUser" because when I take out that one line the print(request.POST) line prints it out.
def AddNewUser(request):
a=AMI()
if(request.method == "POST"):
print(request.POST)
print(request["newUser"])
csrfContext = RequestContext(request)
return render_to_response("ac/AddNewUser.html", csrfContext)
`
Why am I getting this error?
It means that WSGIRequest does not implement __getitem__. You are trying to treat the HttpRequest object like a dictionary but it's not. If you want to access this newUser variable use the POST object, which implements a dictionary-like interface:
request.POST['newUser']
You'd do well to peruse the Django docs in situations like this.

Categories