How to pass json to render_to_response - python

I am trying to pass a json file through render_to_response to the front end. The front end is not a django template, its coded in JS, HTML etc. I am getting some weird error. Can anybody help me with that. I am attaching the code and the traceback.
return render_to_response('ModelView.html', json.dumps(newDict))
Traceback (most recent call last):
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonWorkspace\ScApp\ScApp2\views.py", line 78, in ScorecardApp20
return render_to_response('ModelView.html', json.dumps(newDict))
File "C:\Users\kxc89\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 27, in render_to_response
content = loader.render_to_string(template_name, context, using=using)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render
context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 274, in make_context
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than str.

Don’t use render_to_response, it’s obsolete. Use render instead.
return render(request, 'ModelView.html', {'new_dict': json.dumps(newDict)})
The third argument has to be a dictionary, so you can either add the json string to the dictionary as I have done above, or perhaps you don’t want to use json.dumps() at all and just use newDict.

Use the code below
import json
data = open('/static/JsonFile.json').read() #opens the json file and saves the raw contents
JsonData = json.dumps(data) #converts to a json structure
context = {'obj': JsonData}
return render(request, 'templates', context)
Hope it should work !

Related

Access cleaned data from django admin for pdf processing

As a newbie, I am currently trying to add a print button to every existing django admin view of a project.
The goal is to make it not depend on a single model I could resolve manually for printing but every existing model which contains foreign keys to other models an so on.
For simplicity I thought it would be the best to just get the cleaned_data of the form and process it for the pdf.
I alread added the print button, the path url and so on and it will create a pdf file for me.
What I am not able to do is to access the forms cleaned_data from my BaseAdmins (extends the ModelAdmin) class like this:
form = BaseForm(request.POST)
if form.is_valid():
data = form.cleaned_data
It will just give me random kinds of errors, like object has no attribute 'is_bound'
So I think that I am generally wrong with the context where I am trying to get the cleaned_data from the form. Every tutorial I found is just showing how to get the data but not fully resolved if it contains foreign keys and not in which context.
Could you please clear up for me where it would make sense to pass any kind of form data maybe as session data or post body to a print view where I can process it.
Thank you very much for reading, hope I was able to describe my problem, feel free to ask.
Edit
This is the BaseForm I changed variable names for internal reasons:
class BaseForm(ModelForm):
def clean_custom(self):
another_model = self.cleaned_data.get('AnotherModel')
custom_models = self.cleaned_data.get('CustomModel')
custom_models_allowed = CustomModel.objects.filter(AnotherModel=another_model)
custom_models_was_list = True
if not custom_models:
return
if not isinstance(custom_models, Iterable):
custom_models_was_list = False
custom_models = [custom_models]
for custom_model in custom_models:
if another_model and custom_model not in custom_models_allowed:
custom_models_allowed = [custom_model.titel for custom_model in custom_models_allowed]
custom_models_allowed = ', '.join(custom_models_allowed)
raise ValidationError(
f'{custom_model} is not part of {another_model}. For selection: {custom_models_allowed}'
)
if custom_models_was_list:
return custom_models
else:
return custom_models[0]
I'm trying to add cleaned_data in my BaseAdmin class where I have access to request and get the following trace:
AttributeError
AttributeError: type object 'CustomForm' has no attribute 'is_bound'
Traceback (most recent call last)
File ".../.env/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__
return self.application(environ, start_response)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 141, in __call__
response = self.get_response(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 75, in get_response
response = self._middleware_chain(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 36, in inner
response = response_for_exception(request, exc)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File ".../.env/lib/python3.9/site-packages/django_extensions/management/technical_response.py", line 40, in null_technical_500_response
raise exc_value.with_traceback(tb)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File ".../.env/lib/python3.9/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File ".../.env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 606, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File ".../.env/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 223, in inner
return view(request, *args, **kwargs)
File ".../admin/base_admin.py", line 203, in change_view
if self.form.is_valid(self.form):
File ".../.env/lib/python3.9/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
AttributeError: type object 'CustomForm' has no attribute 'is_bound'
This is not a standard question format, you are supposed to give us the code for the piece of code where the error occurs, (i.e. the base_admin.py file) but what you have provided is just 3 lines of it.
But so far I can see you are not checking whether the request is of the type of post or not. Pay attention to the if condition at the beginning of the method
def edit(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = PurposeForm(request.POST)
# check whether it's valid:
if form.is_valid():
for key, value in form.cleaned_data.items():
# etc

dictionary update sequence element #0 has length 0; 2 is required

I was working on my project and everthing worked fine. I tried to open the server in another browser and this error appeared. I stopped the project and start it agian and it stop working on my main browser aswell. I dont have any idea what this cause it.
Internal Server Error: /account/login/
Traceback (most recent call last):
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "A:\repos\topanime\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
response = response.render()
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 105, in render
self.content = self.rendered_content
File "A:\repos\topanime\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content
return template.render(context, self._request)
File "A:\repos\topanime\venv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "A:\repos\topanime\venv\lib\site-packages\django\template\base.py", line 168, in render
with context.bind_template(self):
File "C:\Python\Python391\lib\contextlib.py", line 117, in __enter__
return next(self.gen)
File "A:\repos\topanime\venv\lib\site-packages\django\template\context.py", line 244, in bind_template
updates.update(processor(self.request))
ValueError: dictionary update sequence element #0 has length 0; 2 is required
[18/Mar/2021 18:52:01] "GET /account/login/ HTTP/1.1" 500 86400
If there is any other information that you need tell me.
The problem was that I had a view in context_processors that required login #login_required. So I couldnt load any page because i wasnt logged in
If you use #login_required in context_processors:
The way I solved it was by replacing it with an if statment inside the context_processor.
def myCP(self, *args, **kwargs):
kontext = {}
if self.user.is_authenticated:
# The user is logged in
kontext['loggedIn'] = True
else:
# The user is logged out
kontext['loggedIn'] = False
return kontext

How to change letters in text to other letters | Python 2.7?

In my Django project I have form with field ("title"). In this field user need to write in Russian language but user can by mistake write some Latin letters. I want to change them. I use PYTHON 2.7. Next code raise error. How to fix this error?
from string import maketrans
eng = 'ETOPAHKXCBMetopahkxcbm' # English letters
rus = 'ЕТОРАНКХСВМеторанкхсвм' # Russian letters
def form_valid(self, form):
form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus))))
form.save()
ERROR:
Traceback (most recent call last):
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 217, in post
return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post
return self.form_valid(form)
File "/home/nurzhan/dashboard.kase.kz/static_pages/views.py", line 54, in form_valid
form.cleaned_data['title'].translate(maketrans(dict(zip(eng, rus))))
TypeError: maketrans() takes exactly 2 arguments (1 given)
When I use just form.cleaned_data['title'].translate(maketrans(eng, rus)) it raise error:
Internal Server Error: /static_page/create/
Traceback (most recent call last):
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/srv/envs/py27/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 217, in post
return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/srv/envs/py27/lib/python2.7/site-packages/django/views/generic/edit.py", line 183, in post
return self.form_valid(form)
File "/home/nurzhan/dashboard.kase.kz/static_pages/views.py", line 54, in form_valid
form.cleaned_data['title'].translate(maketrans(eng, rus))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-21: ordinal not in range(128)
It'll make things a bit easier if you use Unicode literals in your code as well, that way you have to worry less about str vs unicode type issues. This is the same as writing all your string literals as u'stuff' instead of just 'stuff'.
Next - the translate function of unicode and of string take different arguments - you need a dict for unicode mapping Unicode ordinals to ordinals or Unicode strings, not maketrans which is only for str translations.
You can use the ord built-in to get ordinals from your Unicode characters.
Try this:
from __future__ import unicode_literals # Put this at the top of your source
eng = 'ETOPAHKXCBMetopahkxcbm' # English letters
rus = 'ЕТОРАНКХСВМеторанкхсвм' # Russian letters
table = dict(zip(map(ord, eng), map(ord, rus)))
assert eng.translate(table) == rus # Verifying translation
You can do it manually like this:
a_string = u"abcdeFghijklmn" # Let say it is cyrillic with one latin letter represented here by 'F' (uppercase)
# To change it to cyrillic i.e. here to lower latin you would do:
l2c = {u"F": u"f"} # Map all latin to cyrillic for real
l2c_get = l2c.get # Faster access but not necessary
a_string = u"".join(
l2c_get(x, x) for x in a_string)
Of course, you can use unicode.translate() method which should do the same.
When your 'a_string' is processed then just push it back to django. All mapped latins to cyrillic will be substituted. Just pay attention that everything is unicode in the mapping. If putting the translated string to django raises the UnicodeDecode/Encode error, it means that you should before try:
a_string = a_string.encode("utf-8", "ignore")
UTF-8 in binary should be accepted.

Django, reading csv from form request throws: Error: line contains NULL byte

I have simple application written in django with one form that uploads CSVfile.
My CSV file has a lot of columns with cyrillic letters. Just for testing I made my view handle html form like this:
#login_required()
#require_http_methods(["POST"])
def upload_csv(request):
uploaded_file = request.FILES['csv'].read(200)
data = csv.reader(uploaded_file)
for row in data:
print(row)
return redirect('moderator:upload_view')
When I try to upload my CSV, I get this error:
Traceback (most recent call last):
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "D:\Python27\lib\site-packages\django\views\decorators\http.py", line 42, in inner
return func(request, *args, **kwargs)
File "D:\myapp\moderator\views\upload.py", line 32, in upload_csv
for row in data:
Error: line contains NULL byte
[08/Apr/2017 13:53:41] "POST /moderator/upload_csv/ HTTP/1.1" 500 87052
First I thought that my CSV is corrupted. Then why other CSV readers and Excel can open it?
You may want to take a look at this answer "Line contains NULL byte" in CSV reader (Python)
which utilizes the codecs library:
import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))
to open the file with different encodings (ex: utf-16)
Good luck :)

Serialize data in django restframework

I get this following data through a POST request in Django restframework.
I need to serialize this data and this data contains data for multiple models.
data={'admin-1':
{'first_name':'john'
,'last_name':'white'
,'job_title':'CEO'
,'email':'test1#gmail.com'
},
'admin-2':
{'first_name':'lisa'
,'last_name':'markel'
,'job_title':'CEO'
,'email':'test2#gmail.com'
},
'company-detail':{'description':'We are a renowned engineering company'
,'size':'1-10'
,'industry':'Engineering'
,'url':'http://try.com'
,'logo':''
,'addr1':'1280 wick ter'
,'addr2':'1600'
,'city':'rkville'
,'state':'md'
,'zip_cd':'12000'
,'phone_number_1':'408-393-254'
,'phone_number_2':'408-393-221'}
r = requests.post('http://127.0.0.1:8000/api/create-company-profile/',data=data)
print r.status_code
print r.text
Here is the CreateAPI view -
class CompanyCreateApiView(CreateAPIView):
def post(self, request, *args, **kwargs):
print 'request ==', request
print 'request.data == ', request.data['admin-2']
import json
print json.loads(request.data)
data=json.dumps({'status':'success'})
return Response(data, status=status.HTTP_200_OK)
I basically need to de-serialize the data but get this error.
request ==
request.data == job_title
Internal Server Error: /api/create-company-profile/
Traceback (most recent call last):
File "/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/django/core/handlers/base.py",
line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/django/views/decorators/csrf.py",
line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/django/views/generic/base.py",
line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/rest_framework/views.py",
line 452, in dispatch
response = self.handle_exception(exc)
File "/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/rest_framework/views.py",
line 449, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/prem/Documents/Ghost/positionmatch-new/menkes-server-master/menkesserver/human_resources/views.py",
line 81, in post
print json.loads(request.data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py",
line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py",
line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
There should be no need to manually decode the POST data in your view. As long as you are using the JSONParser, as described in the parsers documentation, request.data should already be fully parsed for you.
Additionally, it looks like the request you're sending to the view is probably not acting how you think. If you want to send JSON data with requests, you need to be a little more explicit. As shown in the example in the requests documentation:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))

Categories

Resources