Getting MultiValueDictKeyError application raise MultiValueDictKeyError(key)
Can any one please guide what is wrong in code. i am new in Django.
view.py
if request.method == "POST":
status = request.POST['Status']
remark = request.POST['Remark']
** AttachDoc = request.FILES['AttachDoc']**
try:
apptracking = Applicationtracking1.objects.create(application1=application1, Remark=remark, Status=status, AttachDoc = AttachDoc)
Can any one please guide what is wrong in code. i am new in Django.
Related
I am using Django 1.6. And I am experiencing the error
**Exception Type**: MultiValueDictKeyError
**Exception Value**:"'chat_room_id'"
in the mentioned part of the code. Can anyone help me out regarding this?
#login_required
def join(request):
'''
Expects the following POST parameters:
chat_room_id
message
'''
p = request.POST
r = Room.objects.get(id=int(p['chat_room_id']))
r.join(request.user)
return HttpResponse('')
Seems like chat_room_id is not in p. request.POST is a MultiValueDict. It has a .get() method to fetch the values. Use that with a default value so that if there is no value for the key, you can use a default value. E.g.
#login_required
def join(request):
'''
Expects the following POST parameters:
chat_room_id
message
'''
p = request.POST
room_id = p.get('chat_room_id', False)
# ------------------------------^ Returns False if `chat_room_id` is not in `p`
if room_id:
r = Room.objects.get(id=int(room_id))
r.join(request.user)
else:
# throw error
return HttpResponse('')
I just write a simple captcha for my login form.
I just add a simple session data.request.session['captcha'].
This is the login views function:
login (request):
if request.method =='GET':
form = LoginForm(auto_id=True)
a = random.randrange(1,10,1)
b = random.randrange(10,20.1)
request.session['captcha1']=a
request.session['captcha2']=b
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
if request.method =='POST':
form = LoginForm(data=request.POST)
if form.is_valid():
captcha= request.POST.get('captcha','')
result = request.session.get('captcha1') + request.session.get('captcha2')
if captcha==result:
data = form.clean()
user=authenticate(username= data['username'],password = data['password'])
if user is not None:
auth_login(request,user)
return HttpResponseRedirect('/')
else:
form = LoginForm(auto_id=True)
return render_to_response('login.html',locals(),context_instance=RequestContext(request))
This is the login form
class LoginForm (forms.Form):
username = forms.CharField(
label='username')
password =forms.CharField(
label='password',widget = forms.PasswordInput())
captcha = forms.CharField(label='spam chercker')
I get keyerror for captcha1, captcha2, and when I add print request.session['captcha1'], it shows None. That means, when POST, I do not get the django session data, there is no data captcha1 and captcha2
How can I store the data in django session, and pass it to the POST method, and in other views function?
thanks
Instead of taking this approach, you might also want to look at existing Django captcha packages:
https://www.djangopackages.com/grids/g/captcha/
If you're looking for something simple, Django-Simple-Captcha is a great option.
I got, following Error messages,
TypeError at /save/ int() argument must be a string or a number, not
'SimpleLazyObject'
While executing following form.
views.py
def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
# create or get link
link, dummy = Link.objects.get_or_create(
url = form.cleaned_data['url']
)
# create or get bookmark
bookmark, created = Bookmark.objects.get_or_create(
user=request.user,
link=link
)
# update bookmarks title
bookmarks.title = form.cleaned_data['title']
# if the bookmark is being updated, clear old tag list.
if not created:
bookmark.tag_set.clear()
# create new tag list
tag_names = form.cleaned_data['tags'].split()
for tag_name in tag_names:
tag, dummy = Tag.objects.get_or_create(name=tag_name)
bookmark.tag_set.add(tag)
# save bookmark to database.
bookmark.save()
return HttpResponseRedirect(
'/user/%s/' % request.user.username
)
else:
form = BookmarkSaveForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('bookmark_save.html', variables)
I thought I got error because I passed link at
bookmark, created = Bookmark.objects.get_or_create(
user=request.user,
link=link
)
But I can not figure out how to fix it.
How can I fix it?
The likely cause is that you're setting user = request.user, where request.user is not a real User object, but a SimpleLazyObject instance. See django: Purpose of django.utils.functional.SimpleLazyObject? for more details, but using request.user.id should fix your issue.
You have to login when running this piece of code on localhost. Otherwise the request.user will be a SimpleLazyObject, then the errors comes out.
Here you trying to create a Bookmark object based on request.user , but request.user is a SimpleLazyObject , so we can get a more secure user object by :
from django.contrib import auth
current_user = auth.get_user(request)
and further your query should be
bookmark, created = Bookmark.objects.get_or_create(
user=current_user,
link=link
)
Most likely the user who is loading the page is not authenticated. Therefor the error is thrown. If you want to save a request.user reference to the database, you obviously have to ensure that only authenticated users are able to call the function.
In your case there are two possibilities - add the "#login_required" decorator to the function or check if the user is authenticated inside the code. Here are the snippets:
With Decorator:
from django.contrib.auth.decorators import login_required
#login_required
def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
# Do something
OR - checking inside the code if the user is authenticated:
def bookmark_save_page(request):
if request.method == 'POST' and request.user.is_authenticated():
form = BookmarkSaveForm(request.POST)
if form.is_valid():
# Do something
Thats strange, I had the same problem and the same solution. After trying a bunch of alternatives I went back to user = request.user and it worked
if you want to set an addition request attr, based on user -> you need to use lazy Django function which is correctly handled by Field.get_prep_value
from django.utils.functional import lazy
request.impersonator = lazy(lambda: request.user.id, int)()
I'm having some trouble grokking Django forms and validation.
#views.py:
def create(request):
if request.method == 'POST':
form = CreateDocumentForm(request.POST)
if form.is_valid():
doc = Document.objects.create(name=form.cleaned_data['name'])
#snip
#forms.py:
class CreateDocumentForm(forms.ModelForm):
name = forms.CharField()
def clean_name(self):
cleaned_name = self.cleaned_data['name']
rgx = re.compile('^(\w|-|\.)+$')
if rgx.match(cleaned_name) == None:
raise ValidationError("invalidchars")
return cleaned_name
The logic is working properly, but I don't know how to tell which kind of VaidationError was raised. Also - This is handled by an Ajax request, so I won't be using templating in the repsonse. I need to get the status of what failed in this view.
thx
You generally won't see the ValidationErrors themselves. If you call form.is_valid, then the errors that occur during validation are all collected and returned to you as a dictionary, form.errors
You can check that dictionary for errors relating to any specific field. The result for any field with errors should be the string value of any ValidationErrors that were raised for that field.
In your view, then, if form.is_valid() returns False, then you can do this:
if 'name' in form.errors:
for err_message in form.errors['name']:
# do something with the error string
i have read a few of the examples regarding integrirty errors caused by appending _id to the end of an attribute but most of them regard user_id which is not the error i have - mine is dealing with a setting the initial value of a foreign key to another model (recipe has fk to cookbook)
so here is my trace
IntegrityError at /cookbook/createrecipe/
(1048, "Column 'original_cookbook_id' cannot be null")
Request Method: POST
Request URL: http://127.0.0.1:8000/cookbook/createrecipe/
Django Version: 1.3.1
Exception Type: IntegrityError
Exception Value:
(1048, "Column 'original_cookbook_id' cannot be null")
Exception Location: /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py in defaulterrorhandler, line 36
Python Executable: /usr/bin/python
Python Version: 2.6.1
def createrecipe(request):
form = RecipeForm(request.POST)
if request.method == 'POST':
if form.is_valid():
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe = form.save()//error
...
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'form': t.render(c),
as you can probably see i have a foreign_key named original_cookbook that i want to set initial to the cookbook of the user.
any idea what might be causing this i can send more code if needed
thanks
snackerfish
.....
form = RecipeForm(request.POST)
if request.method == 'POST':
if form.is_valid():
recipe = form.save(commit=False)
recipe.original_cookbook = request.user.cookbooks.all()[0]
recipe.save()