Django OSError [Errno 22]无效参数 [英] Django OSError [Errno 22] Invalid Argument
问题描述
我遇到以下错误:
OSError at /index/
[Errno 22] Invalid argument: 'C:\\Users\\username\\PycharmProjects\\DjangoTestS\\templates\\<django.template.backends.django.Template object at 0x00000262E5F2F2B0>'
我相信这是由于我的Django代码无法找到我的模板文件所致.在Django中获取模板的代码如下:
I believe this is due to my django code failing to find my template file. The code to get the template in django is as follows:
index_model = loader.get_template('index.html')
和我的模板字典如下:
'DIRS': [os.path.join(BASE_DIR, 'templates'),
'C:\\Users\\username\\PycharmProjects\\DjangoTestS',],
我尝试过的类似问题的解决方案:
Solutions from similar questions I have tried:
-
将项目位置硬编码到模板dict中.最初,这是一种通常应找到任何项目的template文件夹的方法,但是这种方法不起作用.硬编码方式也不起作用.
Hard coded the project location into the templates dict. Originally it was a way that should generally find the templates folder of any project, but that did not work. The hard coded way did not work either.
一个pycharm shell助手更改,该更改将一个路径元素硬编码到pycharm projects文件夹中.也不起作用.
A pycharm shell helper change that hard coded a path element to the pycharm projects folder. Did not work either.
根据请求,以下是导致错误的视图:def table_view(request):
As requested, here is the view that is causing the error: def table_view(request):
ip_address = get_client_ip(request)
browser = request.META['HTTP_USER_AGENT']
cur_visit = models.visit()
cur_visit.ip_address = ip_address
cur_visit.browser = browser
cur_visit.save()
index_model = loader.get_template('index.html')
all_visitors = models.visit.objects.all()
context = {'all_visitors': all_visitors}
return render(request, index_model, context)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
推荐答案
如果模板存储在名为 template_dir
的目录中,则可以将代码修改为'DIRS':[os.path.join(BASE_DIR,'template_dir')]
.在您的代码中,您已经使用 templates
加入了项目目录路径.哪个(目录)可能不存在.
if your template is stored in directory called template_dir
, then you can modify your code as 'DIRS':[os.path.join(BASE_DIR,'template_dir')]
. In your code you have joined project directory path with templates
. Which(directory) probably does not exist.
get_template
函数返回一个 Template
对象,该对象不适合 render
的功能模板,它( render
)直接采用模板名称 template.html
.
the get_template
function returns a Template
object, which does not fit the function template for render
, it(render
) takes the template nametemplate.html
directly.
这篇关于Django OSError [Errno 22]无效参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!