Scaldiron
Scaldiron

Reputation: 11

Django OSError [Errno 22] Invalid Argument

I am getting the following error:

OSError at /index/
[Errno 22] Invalid argument: 'C:\\Users\\username\\PycharmProjects\\DjangoTestS\\templates\\<django.template.backends.django.Template object at 0x00000262E5F2F2B0>'

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') 

and my template dict is as follows:

'DIRS': [os.path.join(BASE_DIR, 'templates'),
             'C:\\Users\\username\\PycharmProjects\\DjangoTestS',],

Solutions from similar questions I have tried:

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

Upvotes: 1

Views: 11480

Answers (2)

MASBHA NOMAN
MASBHA NOMAN

Reputation: 198

I got the same error:

OSError at /url_path/
[Errno 22] Invalid argument:

And that was simply because of the argument order while rendering. This one throws the error:

def contact(request):
    context = locals()
    template = 'contact.html',
    return render(request, context, template)

This one is error-free:

def contact(request):
    context = locals()
    template = 'contact.html',
    return render(request, template, context)

Try to maintain the order in your project.

Upvotes: 0

whitespace
whitespace

Reputation: 821

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.

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.

Upvotes: 4

Related Questions