简体   繁体   中英

Trying to read a text file in django

Im unable to read the contents of a file from view.py

Below is my code:

def home_view (request, *args, **kwargs):
    ksh_test_result=AutomationTestResult.objects.values('tatr2tafmc__jobcommand', 'ksh_completion','ftp_log_abs_path','aftp_log_abs_path').distinct()
    ksh_drilldown_data=AutomationTestResult.objects.all()
    for ksh in ksh_test_result:
        ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read()
        aftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.aftp_log_abs_path, 'r').read()
    print(ftp_log_file)
    print(aftp_log_file)
    context={
        "ksh_list" : ksh_test_result,
        "ksh_drilldown" : ksh_drilldown_data,
        "ftp_log" : ftp_log_file,
        "aftp_log" : aftp_log_file
    }
    return render(request, "home.html", context)

I'm reading the path of the file from a database. When I run this code i get the following error code

Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/nmehta/Projects/GATI/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/nmehta/Projects/GATI/src/KTA/dashboard/views.py", line 11, in home_view
    ftp_log_file[ksh.tatr2tafmc__jobcommand]=open(ksh.ftp_log_abs_path, 'r').read()
AttributeError: 'dict' object has no attribute 'ftp_log_abs_path'
[20/Nov/2019 14:31:27] "GET / HTTP/1.1" 500 65923

Since you use values() method, you need to change ksh.ftp_log_abs_path to ksh['ftp_log_abs_path'] . values() returns a queryset with dictionaries not model instances.

If you check the docs for this method:

values()... Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

Another issue with the code is reading files in a for loop. If you only have one file, use either get_object_or_404() orget() Queryset method.

values returns a queryset of dict s, not model instances; in open(ksh.ftp_log_abs_path, 'r') , you're trying to access ftp_log_abs_path as an attribute of the dict ksh .

Change that to dict item access:

ksh['ftp_log_abs_path']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM