Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTTP request with Python : TypeError: an integer is required (got type dict)
I was scraping a secured website for my practice project but while doing so I faced this error: sock.settimeout(timeout) TypeError: an integer is required (got type dict) My code is- >> import urllib.request >>> import bs4 >>> from urllib.request import urlopen as uReq >>> from bs4 import BeautifulSoup as soup >>> headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} >>> my_url = uReq('https://www.justdial.com/Mumbai/311/B2b_fil', None, headers) The whole error I got is: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python\Python36-32\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Python\Python36-32\lib\urllib\request.py", line 526, in open response = self._open(req, data) File "C:\Python\Python36-32\lib\urllib\request.py", line 544, in _open '_open', req) File "C:\Python\Python36-32\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Python\Python36-32\lib\urllib\request.py", line 1361, in https_open context=self._context, check_hostname=self._check_hostname) File "C:\Python\Python36-32\lib\urllib\request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "C:\Users\Python\Python36-32\lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Python\Python36-32\lib\http\client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Python\Python36-32\lib\http\client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Python\Python36-32\lib\http\client.py", line 1026, in _send_output self.send(msg) File "C:\Python\Python36-32\lib\http\client.py", line 964, in send self.connect() File "C:\Python\Python36-32\lib\http\client.py", line 1392, in connect super().connect() File "C:\Python\Python36-32\lib\http\client.py", line 936, in connect (self.host,self.port), self.timeout, self.source_address) File … -
How to filter Django QuerySet?
So, I have 3 Django models in project: Item as parent, Book and Stationery as a child models. ItemImage model is attached by ForeignKey to Item. I need to get somekind of set or a list of images from Book and Stationery, then implement this sets in HTML. ` def home(request): # goods_images is OK, you can see them on the ExamplePage in "New Arivals Section" goods_images = ItemImage.objects.filter(is_active=True, is_main=True) books_images = # initialization stationery_images = # initialization for book in Book.objects.get_queryset(): books_images +=# or something book.itemimage_set.get_queryset().filter(is_active=True, is_main=True) for stationery in Stationery.objects.get_queryset(): stationery_images +=# or something stationery.itemimage_set.get_queryset().get(is_active=True, is_main=True) return render(request, 'landing/home.html', locals()) ` HTML examplePage example Notation : The set I need to get can't be a list() because I can't get any field of my model from HTML page. -
Django 1.1 context must be a dict rather than RequestContext
I am writing a login page with Django 1.1. and this is what I received: context must be a dict rather than RequestContext. Below is my code: from django.contrib import auth from django.template import RequestContext from django.shortcuts import render_to_response from django.http import HttpResponse def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render_to_response('login.html', RequestContext(request, locals())) And my template: <!doctype html> <body> <form action="" method="post"> <label for="username">用戶名稱:</label>{% csrf_token %} <input type="text" name="username" value="{{username}}" id="username"><br /> <label for="password">用戶密碼:</label> <input type="password" name="password" value="" id="password"><br /> <input type="submit" value="登入" /> </form> </body> -
NoReverseMatch at /polls/top/ Why can't I use <int:pk>?
I wrote in views.py from django.shortcuts import render from .models import Polls def top(request): data = Polls.objects.order_by('-created_at') return render(request,'index.html',{'data':data}) def detail(request): data = Polls.objects.order_by('-created_at') return render(request,'detail.html',{'data':data}) in urls.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns=[ url('top/', views.top, name='top'), url('detail/<int:pk>/', views.top,name='detail'), ] in index.html <main> {% for item in data %} <h2>{{ item.title }}</h2> <a href="{% url 'detail' item.pk %}">SHOW DETAIL </a> {% endfor %} </main> in models.py from django.db import models class Polls(models.Model): title = models.CharField(max_length=100) detail = models.TextField() When I access top method, NoReverseMatch at /app/top/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/detail//'] error happens.I think I can access object's number by item.pk,but is it wrong?I rewrote <a href="{% url 'detail' pk %}"> but same error happens.How should I fix this?What is wrong in my codes? -
Is Django Default Registration / Authentication is secure?
hi guys im new to django and i use default django registration method to authenticate users ( django.contrib.auth) and also im using The default User table in django ( django.contrib.auth.models). is this safe and secure ? or i must build a customized authentication service for my project . ( if i must , please Introduce a tutorial ) recently heard something about registration-redux and some other registrations. should I user one of these ? or the default method is OK ? thank you guys. -
Can big service work without non-blocking I/O?
I am learning django. And wanna know if it is important to have non-clocking I/O or use something like Celery. -
Filtering Content in Django using ajax
I'm working on a template that renders a list of product. I want the user to filter the content based on the properties of the product. Those are my models : """ Coutries, regions and cities tables """ class Country(models.Model): name = models.CharField(max_length=200) class Region(models.Model): name = models.CharField(max_length=200) country = models.ForeignKey( Country on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=200) region = models.ForeignKey( Region on_delete=models.CASCADE) """ Categories and their subcategories tables """ class Category(models.Model): name = models.CharField(max_length=200) class Subcategory(models.Model): name = models.CharField(max_length=200) Subcategory = models.ForeignKey( Region on_delete=models.CASCADE) """ Product Table """ class Product(models.Model): name = models.CharField(max_length=200) Description = models.TextField() """ Products Location tables """ class ProductLocation(models.Model): Address = models.CharField(max_length=200) country = models.ForeignKey( Country on_delete=models.CASCADE) region = models.ForeignKey( Region on_delete=models.CASCADE) city = models.ForeignKey( Region on_delete=models.CASCADE) product = models.ForeignKey( product on_delete=models.CASCADE) """ Products Classification """ class ProductClassification(models.Model): category = models.ForeignKey( Category on_delete=models.CASCADE) Subcategory = models.ForeignKey( Region on_delete=models.CASCADE) product = models.ForeignKey( product on_delete=models.CASCADE) In the page i will have 3 inputs for location : - Country, Region and City. I think I should implement a Dependent/Chained Dropdown I want to filter the products by country, region and city. In another 2 inputs (Checkbox to select multiple choice) the user can select the category and subcategory … -
Python Django How to get value of logged user in views.py?
I have CustomUser class for logging and another class coach where I have information about my users. Every user are linked to coach class. I would like to create template where my users if they have completed their profile will see their information and if they didn't completed their they will see a message. I'am learning Python Django and I don't know for example how to get Adresse of my logged users from class coach and check if it is empty or not. Any idea how to fix this? My views.py def Profile(request): user1 = coach.objects.get(Adresse=user.coach.Adresse) if len(user1)!=0: completed= "Completed Profile" return render(request, 'Profile.html',{'completed':completed}) else: notcompleted = "please complete you profile" return render(request, 'Profile.html', {'notcompleted': notcompleted}) My models.py class coach(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) Adresse = models.TextField(max_length=140, default='DEFAULT VALUE') Telephone = models.IntegerField(null=True, max_length=140, default='111') -
Try to understand how to set up the right Django architechture (admin,views,models)
I have a bot for facebook. And Django is on it. I have such model class User_of_bot(models.Model): """ Information about bot's user """ START = '1' TO_QUESTION = '2' TO_ORDER = '3' CHECKING_1 = '5' CHEKING_2 = '7' CHECKING_3 = '9' FINISH = '11' STEP_CHOICES = ( (START, '1'), (TO_QUESTION, '2'), (TO_ORDER, '3'), (CHECKING_1, '5'), (CHEKING_2, '7'), (CHECKING_3, '9'), (FINISH, '11'), ) name = models.CharField(max_length=100,db_index=True) phone_number = models.CharField(max_length=100) state = models.CharField(max_length=1, default=START, choices=STEP_CHOICES) def __str__(self): return self.fb_name When bot is initialized user get the first state. I send him a question with 2-3-4-n buttons. And each button move user on the different state and send him a new question which is binded with state # views.py if user.state == '1': # it's button if recevied_message == 'COMPLETE THE ORDER': full_name = information['first_name'] + ' ' + information['last_name'] message = 'I have your name as ' + full_name + ' is that correct?' bot.quick_replies(fbid, str(message), get_buttons('state1')) # MOVE TO STATE 3 user.state = '3' user.name = str(full_name) user.save() print('Move to 3') elif recevied_message == 'QUESTION': bot.quick_replies(fbid, 'Choose', get_buttons('state2')) user.state = '2' user.save() print('Move to 2') and this hardcore of code. I want to add opportunity to include question and choices and … -
How to return 404 page intentionally in django
I made custom 404 page in django. And I'm trying to get 404 error page intentionally. myproject/urls.py: from website.views import customhandler404, customhandler500, test urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^test/$', test, name='test'), ] handler404 = customhandler404 handler500 = customhandler500 website/views.py def customhandler404(request): response = render(request, '404.html',) response.status_code = 404 return response def customhandler500(request): response = render(request, '500.html',) response.status_code = 500 return response def test(request): raise Http404('hello') But when I go 127.0.0.1:8000/test/ , It seems to return 500.html And terminal says: [24/Mar/2018 22:32:17] "GET /test/ HTTP/1.1" 500 128 How can I intentionally get 404 page? -
Django/Python - can't get environment variable using os.environ.get
In my Django project, I need to have access to DJANGO_DEVELOPMENT environment variable which tells whether is it a development server or production (droplet on DigitalOcean). I want to set DJANGO_DEVELOPMENT to 1 on this droplet but it doesn't work. I've added to /etc/environment this line: DJANGO_DEVELOPMENT="1" And restarted whole Droplet. Then, I'm trying to log this variable inside settings.py: if os.environ.get('DJANGO_DEVELOPMENT') == '1': logger.info('DJANGO_DEVELOPMENT=="1"') from dev_settings import * else: logger.info('no DJANGO_DEVELOPMENT VAR') logger.info(os.environ.get('DJANGO_DEVELOPMENT')) logger.info(os.environ.items()) Which logs this: 2018-03-24 13:09:43,007 - MyProject.settings - INFO - no DJANGO_DEVELOPMENT VAR 2018-03-24 13:09:43,007 - MyProject.settings - INFO - None 2018-03-24 13:09:43,014 - MyProject.settings - INFO - [('LANG', 'en_US.UTF-8'), ('SUPERVISOR_SERVER_URL', 'unix:///var/run/supervisor.sock'), ('SUPERVISOR_ENABLED', '1'), ('SUPERVISOR_PROCESS_NAME', 'daphne'), ('DJANGO_SETTINGS_MODULE', 'MyProject.settings'), ('SUPERVISOR_GROUP_NAME', 'daphne'), ('PATH', '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'), ('LC_ALL', 'en_US.UTF-8')] But when I ssh to the droplet and check variable manually, it seems to be set: root@MyProject-v1:~# echo $DJANGO_DEVELOPMENT 1 root@MyProject-v1:~# su - futilestudio futilestudio@MyProject-v1:~$ echo $DJANGO_DEVELOPMENT 1 futilestudio@MyProject-v1:~$ Don't know where is the problem, isn't it a bug? -
Timezone It works locally but not in pythonanywhere (DJango)
I have a queryset to list today's sales from django.utils import timezone class VentaToday(ListView): queryset = Venta.objects.filter(fecha=timezone.now()).order_by('-id') template_name = 'venta/venta_today.html' In local, this works correctly but in production (Pythonanywhere) the sales of the previous day keep appearing. To fix it, I have to go to the pythonanywhere panel and click on the ** reload ** button to solve the problem. I changed the server time: Image of server time Configuration of the django project: LANGUAGE_CODE = 'es-pe' TIME_ZONE = 'America/Lima' USE_I18N = True USE_L10N = True USE_TZ = True Is it a server cache problem? or something am I doing wrong? -
Using Ngrok with Django throws Nginx 403 forbidden
accessing Django project on Homestead vagrant box using command: ngrok http -host-header=rewrite my-site.com:80 -config=path to file config ngrok.yml: web_addr: 0.0.0.0:40404 authtoken: *************************** The 192.168.10.10:4040 works fine. But url for http and https throws nginx 403 error ?? have mysite.com mapped on both host and homestead in Hosts file What am I missing ??? -
webpack: getting an error when trying to run yarn run build-assets
I'm trying to create a webb app using django for backend and Vue.js for frontend, and to make that happen I had to use the module bundler "webpack", but after I made all the nessessary configurations and run the django server it gives me this error "OSError at / Error reading project_path\webpack-stats.json. Are you sure webpack has generated the file and the path is correct?". found out tha the webpack-stats.json wasn't generated, so I made some research of how to generate a webpack-stats.json file, found that the command yarn run build-assets is supposed to generate that file automatically. but when I run it, it gives that error An unexpected error occurred: "Command \"build-assets\" not found." is there any other solution so I can generate webpack-stats.json file?? thank you. -
Django... static images for carousel
I am in the middle of a developing a website in my development environment and I am having issues getting the photos to show on my carousel... I don't know if python manage.py collectstatic will fix this issue but this is what I have.I tried to configure the static settings in the settings.py folder but nothing carousel this is my code right here <script type="text/javascript"> $(document).ready(function() { var carousel = $("#carousel").featureCarousel({ // include options like this: // (use quotes only for string values, and no trailing comma after last option) // option: value, // option: value }); $("#but_prev").click(function () { carousel.prev(); }); $("#but_pause").click(function () { carousel.pause(); }); $("#but_start").click(function () { carousel.start(); }); $("#but_next").click(function () { carousel.next(); }); }); </script> .carousel-container { position: relative; width: 960px; } #carousel { height: 280px; width: 960px; background-color: #CCC; position: relative; margin-bottom: 0.5em; font-size: 12px; font-family: Arial; } .carousel-image { border: 0; display: block; } .carousel-feature { position: absolute; top: -1000px; left: -1000px; border: 2px solid #5d5d5d; cursor: pointer; } .carousel-feature .carousel-caption { position: absolute; bottom: 0; width: 100%; background-color: #000; } .carousel-feature .carousel-caption p { margin: 0; padding: 5px; font-weight: bold; font-size: 12px; color: white; } .tracker-summation-container { position: absolute; color: white; right: 48px; … -
FileNotFoundError at /admin/Music/album/add/
here is model class : def album_upload_destination(instance, filename): return "{0}/{1}".format(instance.author+" album ", filename) class Album(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) picture = models.ImageField(upload_to=album_upload_destination) creation_year = models.IntegerField(default=-1) rate = models.IntegerField(default=0) timestamp = models.DateTimeField(auto_created=True, auto_now_add=True) def __str__(self): return self.name when i tried to add 'album model' in admin panel , i got this error : [Errno 2] No such file or directory: 'D:\Python Projects\exercise_project\media\Taylor swift album \Taylor_Swift_Red_Album_Art_Cover_1.jpg' i know what this error is , but django should create the folder itself if it doesnt exist . so whats the problem -
How to overide html_content editor in Django Post Office?
I've tried to override the widget used in Django Post OFfice (3.4.0) for the html_content field from the default plain text to CKEditor. I went about this by adding the follwing code into the admin.py of a new app that is loaded after post_office. However I can't get it to have any effect although the unregister method is called and CKEditor works elsewhere in the website. class EmailTemplateAdminFormX(EmailTemplateAdminForm): html_content = forms.CharField(widget=CKEditorWidget(config_name='short')) class EmailTemplateInlineX(EmailTemplateInline): form = EmailTemplateAdminFormX class EmailTemplateAdmin(EmailTemplateAdmin): inlines = (EmailTemplateInlineX,) admin.site.unregister(EmailTemplate) admin.site.register(EmailTemplate, EmailTemplateAdmin) Any help would be greatly appreciated Thank you -
Razorpay django integration
I am using razorpay in my django website. After any successful payment, it is redirecting to localhost/purchase, but I want to send it to my url. How to achieve that? -
Managing django powered websites
A while ago I decided to set up my own website that I could use for learning purposes. At the beginning I only needed to try out stuff that can be handled via terminal, but now when I want to get some actual html/js/django stuff going on, I need more efficient way to manage files and write code. I currently have droplet in Digitalocean with Ubuntu 16.04 image, Apache 2.4.18. and Django 1.11 for backend logic. So, my problem is that I don't know efficient way to deploy code that's in my machine, to the server. The ideal situation for me is that I could run, test and modify my django app locally, and then commit/push the changes to server if the code is ok. I tried to workaround the problem by downloading WinSCP and then just copying the project directory into my local machine. Not only did it take more than 20 minutes, but I wasn't able to make it run locally because of Django import error. To clarify, I have Django and all the other stuff installed inside avirtualenv. Any tips? -
Django URL regex for alphanumeric string
My current url pattern is: url(r'^(?P<category>\w+)/(?P<hash>\w+)/$', article, name='article'), hash is an alphanumeric string that can be uppercase or lowercase. example: gqaBittXW9hcyO What should my url pattern look like to operate for this? -
Django server won't run
I just tries to start django project on win7(x64), but i faced with following issue: $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 24, 2018 - 13:06:26 Django version 1.11.3, using settings 'superlists.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x035ED978> Traceback (most recent call last): File "C:\Users\alesya\.virtualenvs\superlists\lib\site-packages\django\utils\a utoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\alesya\.virtualenvs\superlists\lib\site-packages\django\core\ma nagement\commands\runserver.py", line 149, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\alesya\.virtualenvs\superlists\lib\site-packages\django\core\se rvers\basehttp.py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\alesya\.virtualenvs\superlists\lib\site-packages\django\core\se rvers\basehttp.py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "c:\users\alesya\appdata\local\programs\python\python36-32\Lib\socketserv er.py", line 453, in __init__ self.server_bind() File "c:\users\alesya\appdata\local\programs\python\python36-32\Lib\wsgiref\si mple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "c:\users\alesya\appdata\local\programs\python\python36-32\Lib\http\serve r.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "c:\users\alesya\appdata\local\programs\python\python36-32\Lib\socket.py" , line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbb in position 14: invalid start byte My computer has an ASCII name, so I even not realized, what happens. Did … -
Django - logger doesn't log anything in settings.py file
I can't figure out why there is nothing in my log. I'm trying to log some data inside settings.py LOGGING_DIR = os.path.join(BASE_DIR,'logs') if not os.path.exists(LOGGING_DIR): os.mkdir(LOGGING_DIR) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'google_api': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': BASE_DIR + '/logs/google_api.log', }, 'django': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR + '/logs/django.log', 'maxBytes': 1024 * 10, # 10 'backupCount': 1, }, }, 'loggers': { 'django': { 'handlers': ['django'], 'level': 'DEBUG', 'propagate': True, }, 'GAPI_requests': { 'handlers': ['google_api'], 'level': 'DEBUG', 'propagate': False, }, }, } And at the bottom of settings.py logger = logging.getLogger('django') logger.info('CHECKING DJANGO_DEVELOPMENT ENV VAR') if os.environ.get('DJANGO_DEVELOPMENT') == '1': logger.info('DJANGO_DEVELOPMENT=="1"') from dev_settings import * else: logger.info('no DJANGO_DEVELOPMENT VAR') But I can't see anything inside django.log (after restarting server), do you know what to do to make it work? -
Django M2M relationships: Use just one intermediary table or one per entity pair?
When creating many to many relationships we use an intermediary table. Lets say I use the following entities video, category, tag, and VideoCategory, VideoTag to create the relations. I'm assuming that many tags/categories can have many videos and vice-versa. And I do it with through keyword 'cause I want to be able to use extra fields in the future if I want. class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class Video(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category, through='VideoCategory') tags = models.ManyToManyField(Tag, through='VideoTag') def __str__(self): return self.title class VideoCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) class VideoTag(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) But I was wondering if would be possible to create a taxonomy entity and handle the relationships with categories and tags from just one site. class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class Video(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category, through='Taxonomy') tags = models.ManyToManyField(Tag, through='Taxonomy') def __str__(self): return self.title class Taxonomy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) Now the taxonomy entity would hold the … -
AttributeError: 'TreeQuerySet' object has no attribute 'get_family'
I am using django mptt and i want to get all whole family of one child. For example i filter object and call function get_family p = Platform.objects.filter(name__startswith='sig') s = p.get_family() print(s) but getting error AttributeError: 'TreeQuerySet' object has no attribute 'get_family' -
process Django NameForm data and use it as file name
could someone please help me solve the following problem? It is mainly about how to get the django form data to be used to create a txt file. For example, if the user enters "Alex", a file should be created as Alex.txt. I am trying to create a web app that an user can enter a name at the beginning(in a intro form) then make some choices (in an index form). At the end a file will be created to record the choices and the file should be named as the name entered(in a complete form). I am using the following code for defining the class in forms.py class NameForm(forms.Form): your_name = forms.CharField(label='Your Name', max_length=100) In the views.py I wrote def intro(request): . . . request.session['subjectname'] = [] if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): request.session['subjectname'] = form.cleaned_data['your_name'] else: form = NameForm() context = {'form': form} return render(request, 'polls/intro.html', context) def index(request): ... def complete(request): subjectname = eval(str(request.session['subjectname'])) filename = '{}.txt'.format(subjectname) ... At the moment the file can be created but with an empty name, i.e., [].txt.