Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception in thread django-main-thread: TypeError:__init__() got an unexpected keyword argument 'fileno'
I am trying to perform load tests on a django application with locust. However, when I try to perform these with multiple simulated users, I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 213, in run httpd.serve_forever() File "/usr/lib/python3.6/socketserver.py", line 241, in serve_forever self._handle_request_noblock() File "/usr/lib/python3.6/socketserver.py", line 315, in _handle_request_noblock request, client_address = self.get_request() File "/usr/lib/python3.6/socketserver.py", line 503, in get_request return self.socket.accept() File "/usr/lib/python3.6/socket.py", line 210, in accept sock = socket(self.family, type, self.proto, fileno=fd) TypeError: __init__() got an unexpected keyword argument 'fileno' This error seems very weird to me, because the socket __init__() function is part of a default library in which this error shouldn't occur. I suspect that the error I see here is a red herring, and that the real error is hidden, but I thought that I might as well ask here in case someone knows why this occurs. Some additional information: When I did the load test on django's built-in development server (wsgi) (i.e. started the … -
How to avoid the error This field is required without changing the model field?
How to avoid the error This field is required in modellformset without changing the model fields and allowing to call the form_valid method instead of form_invalid. That is, if the model is created, all fields are required, if the fields are empty, then it simply does not save the model, but validation passes. Now I get that all the forms must be filled in, but the user can only memorize what he needs, and leave the rest empty. Is there a solution? views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs)) context['formset_framework'] = SkillFrameworkFormSet(queryset=Skill.objects.none()) context['formset_planguage'] = SkillPLanguageFormSet(queryset=Skill.objects.none()) context['tech_group'] = Techgroup.objects.all() return context def post(self, request, *args, **kwargs): if 'framework' in request.POST: form = SkillFrameworkFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) elif 'language' in request.POST: form = SkillPLanguageFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) else: return self.form_invalid(request) def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" for form in form: self.object = form.save(commit=False) self.object.employee =Employee.objects.get(pk=self.kwargs['pk']) employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) if self.object.technology not in employee_current_technology: self.object.save() return redirect("profile", pk=self.kwargs['pk']) def form_invalid(self, request): return render(request, 'skill_create.html', {'formset_framework': SkillFrameworkFormSet(queryset=Skill.objects.none()), 'formset_planguage': SkillPLanguageFormSet(queryset=Skill.objects.none())}) Is the behavior in which I need … -
django templates index of array does not work
Index in templates of django is like this: {{somearray.i}} for my code this is not working!! this is views.py def fadakpage(request): tours = tour.objects.order_by('tourleader') travelers = traveler.objects.order_by('touri') j=0 for i in tours: j+=1 args={'tours':tours,'travelers':travelers,'range':range(j)} return render(request,'zudipay/fadakpage.html',args) this is fadakpage.html / template (it shows empty): {% for i in range %} {{tours.i.tourleader}} {% endfor %} but if i change {{tours.i.tourleader}} to {{tours.0.tourleader}} it works!! i also checked i values and it was true !! -
Improve the calculation of distances between objects in queryset
I have next models in my Django project: class Area(models.Model): name = models.CharField(_('name'), max_length=100, unique=True) ... class Zone(models.Model): name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) area = models.ForeignKey(Area, verbose_name=_('area'), db_index=True) polygon = PolygonField(srid=4326, verbose_name=_('Polygon'),) ... Area is like city, and zone is like a district. So, I want to cache for every zone what is the order with others zones of its area. Something like this: def get_zone_info(zone): return { "name": zone.name, ... } def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs: by_distance = Zone.objects.filter(area=zone.area_id).distance(zone.polygon.centroid).order_by('distance') zones[zone.id] = [get_zone_info(z) for z in by_distance] cache.set("zones_by_distance", zones, timeout=None) But the problem is that it is not efficient and it is not scalable. We have 382 zones, and this function get 383 queries to DB, and it is very slow (3.80 seconds in SQL time and 4.20 seconds in global time). is there any way efficient and scalable to get it. I had thought in something like this: def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs.prefetch_related(Prefetch('area__zone_set', queryset=Zone.objects.all().distance(F('polygon__centroid')).order_by('distance'))): by_distance = zone.area.zone_set.all() zones[zone.id] = [z.name for z in by_distance] This obviously does not work, but something like this, caching in SQL (prefetch related) the zones ordered (area__zone_set). -
django static files (including bootstrap and javascript) problem
The javascript and CSS files are not properly working in dJango. I have tried all the possible ways to i could have. I have attached Index.html and settings.py files code below. // Index.html {% load static %} <title>Careers &mdash; Website Template by Colorlib</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'css/custom-bs.css' %}"> <link rel="stylesheet" href="{% static 'css/jquery.fancybox.min.css'%}"> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css'%}"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css'%}"> <link rel="stylesheet" href="{% static 'fonts/line-icons/style.css'%}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css'%}"> <link rel="stylesheet" href="{% static 'css/animate.min.css'%}"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> <!-- SCRIPTS --> <script src="{% static 'js/jquery.min.js'%}"></script> <script src="{% static 'js/bootstrap.bundle.min.js'%}"></script> <script src="{% static 'js/isotope.pkgd.min.js'%}"></script> <script src="{% static 'js/stickyfill.min.js'%}"></script> <script src="{% static 'js/jquery.fancybox.min.js'%}"></script> <script src="{% static 'js/jquery.easing.1.3.js'%}"></script> <script src="{% static 'js/jquery.waypoints.min.js'%}"></script> <script src="{% static 'js/jquery.animateNumber.min.js'%}"></script> <script src="{% static 'js/owl.carousel.min.js'%}"></script> <script src="{% static 'js/custom.js'%}"></script> // Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', ] -
How to make a model in django without predefined attributes?
I am little bit confused with the django model as the title said. I also cannot find any posts in google. Let's say in the normal way, we will have a model like this: class something(models.Model): fName = models.TextField() lName = models.TextField() ...... lastThings = models.TextField() However, I don't want to have a model like this. I want to have a model with no predefined attributes. In order words, I can put anythings into this model. My thought is like can I use a loop or some other things to create such model? class someModel(models.Model): for i in numberOfModelField: field[j] = i j+=1 Therefore, I can have a model that fit in any cases. I am not sure is it clear enough to let you understand my confuse. Thank you -
Daemonization celery in production
i'M trying to run celery as service in Ubuntu 18.04 , using djngo 2.1.1 and celery 4.1.1 that is install in env and celery 4.1.0 install in system wide . i'm going forward with this tutorial to run celery as service.here is my django's project tree: hamclassy-backend ├── apps ├── env │ └── bin │ └── celery ├── hamclassy │ ├── celery.py │ ├── __init__.py │ ├── settings-dev.py │ ├── settings.py │ └── urls.py ├── wsgi.py ├── manage.py └── media here is celery.py : from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() here is /etc/systemd/system/celery.service: [Unit] Description=Celery Service After=network.target [Service] Type=forking User=classgram Group=www-data EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/home/classgram/www/classgram-backend/hamclassy/celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target and /etc/conf.d/celery: CELERYD_NODES="w1" CELERY_BIN="/home/classgram/www/env/bin/celery" CELERY_APP="hamclassy.celery:app" CELERYD_CHDIR="/home/classgram/www/classgram-backend/" CELERYD_MULTI="multi" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_LEVEL="INFO" when i run service with systemctl start celery.service the error appear: Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for detail when i … -
Most Pythonic/Django way to dynamically load client libraries at runtime
I'm writing a Django application in which we will have multiple client libraries that make calls to third party APIs. We want to be able to determine which client library to load at runtime when calling different endpoints. I'm trying to determine the most Django/Pythonic way to do this The current idea is to store class name in a model field, query the model in the View, and pass the class name to a service factory that instantiates the relevant service and makes the query. I've also considered writing a model method that uses reflection to query the class name For example lets say we have a model called Exchange that has an id, a name, and stores the client name. class Exchange(models.Model): exchange_name = models.CharField(max_length=255) client_name = models.CharField(max_length=255) def __str__(self): return self.exchange_name Then in the View we might have something like: from rest_framework.views import APIView from MyProject.trades.models import Exchange from django.http import Http404 from MyProject.services import * class GetLatestPrice(APIView): def get_object(self, pk): try: exchange = Exchange.objects.get(pk=pk) except Exchange.DoesNotExist: raise Http404 def get(self, request, pk, format=None): exchange = self.get_objectt(pk) service = service_factory.get_service(exchange.client_name) latest_price = service.get_latest_price() serializer = PriceSerializer(latest_price) return Response(serializer.data) This syntax may not be perfect but it hasn't been … -
Django - Can not upload file using my form
Here's the situation: I'm quite new to Django and I'm trying to upload some files using a form I created. When I click on the submit button, a new line is created in my database but the file I selected using the FileField is not uploaded.But I can upload files via the admin page without any trouble. I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem I would be really thankful. Here you can find some code related to my form: forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(View): template_name = 'phyto/phyto_admin_fichiers.html' form = forms.PhytoFileForm() def get(self, request): return render(request, self.template_name, {'form': self.form}) def post(self, request): form = forms.PhytoFileForm(request.POST, request.FILES) form.save() return render(request, self.template_name, {'form': self.form}) phyto_admin_fichiers.html {% block forms … -
Throttles connection in day using Djang REST Framework
I want to limit the amount of connection to the web in a day. I have searched on Internet that using Djano REST Throttling, but I don't know how to use Django REST API. I wish I had a sample code to solve the problem. Thanks. -
Setting cache in nginx does not delete files for inactivity
I have an S3 bucket and AWS RDS Postgres database attached to my EC2 instance. I want to reduce S3 egress by setting up a linux server that caches data. For that reason I have attached the uWSGI of my django app to a nginx server. Although I have specified the inactive time for the proxy_cache_path, the cached files do not get deleted from my folder. Please help. I have set up the nginx.conf file in sites-available and created a symlink in sites-enabled and reload my nginx server. This is my conf file: ` proxy_cache_path /home/clyde/Downloads/new/automatic_annotator_tool/queried_data keys_zone=mycache:10m inactive=2m use_temp_path=off max_size=1m; upstream django { server local_ip; } server { listen 8000; server_name public_ip; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/clyde/Downloads/new/automatic_annotator_tool/django_app/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/uwsgi/sites/uwsgi_params; proxy_cache mycache; } location /images { alias /home/clyde/Downloads/new/automatic_annotator_tool/queried_data; proxy_cache mycache; expires 2m; proxy_cache_valid any 2m; } location /nginx_status { stub_status; allow public_ip; deny all; } } This is the uwsgi command i run for starting the webserver: uwsgi --socket :8001 --module uvlearn.wsgi -p 2 --master` … -
How include location when upload photo?
I'm using IstangramApi this is my py: from InstagramAPI import InstagramAPI InstagramAPI = InstagramAPI("username", "password") InstagramAPI.login() # login photo_path = '/home/user/image/index.jpeg' caption = "Sample photo" location = "Rome" InstagramAPI.uploadPhoto(photo_path, caption=caption, location=location) without location it work... how can i post with location? It seems not official documentation.... Please Help -
How to add new input text in admin page in django?
Whenever I try to add new user in django admin page, it gives me username, password and new password input text but I have added Id_payment also in registration page but it is not showing. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id_number = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id_number'] -
Django form hidden field but previously load with value
I have a form with 6 field where 2 of then need to be preloaded with a specific values. Then I need those 2 fields to be hidden since the user doesn't need to deal this those. I found plenty of ask here in stackoverflow, most of the are applicable to my problem using HiddenInput() method, but when I preload the field, the HiddenInput() method doesn't work any more. here is my forms.py code class SurveyCreateForm(BSModalForm): def __init__(self, *args, **kwargs): self.wellbore = kwargs.pop('wellbore', None) self.profile = kwargs.pop('profile', None) super(SurveyCreateForm, self).__init__(*args, **kwargs) self.fields['wellbore'] = forms.ModelChoiceField(queryset=Wellbore.objects.filter(pk=self.wellbore), empty_label=None) self.fields['profile'] = forms.ModelChoiceField(queryset=SurveyProfile.objects.filter(pk=self.profile), empty_label=None) class Meta: model = Survey fields = ['wellbore', 'profile','md','inc','azm','time_stamp'] # Django Form : 2 : Model Forms @2:45 labels = {'wellbore':'Wellbore', 'profile':'Profile','md':'MD','inc':'Inclination','azm':'Azimuth','time_stamp':'Date Time'} widgets = {'wellbore':forms.HiddenInput(), 'profile':forms.HiddenInput() } and here the html template <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Add New Survey</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div style="margin: 10px 10px 10px 10px;"> <table> {{ form.as_table }} </table> </div> <div class="modal-footer"> <p> <button type="button" class="submit-btn btn btn-primary">Save</button> </p> </div> </form> I need those fields to be populated but at the same time hidden from the user. Thanks in advance. -
How to render two form fields as one field in Django forms?
I'm working on Django application where I need to render a form differently. The form contains multiple fields related to a person. Firstname Lastname email address city country Phone Pincode There are two flows in my application. In the first flow I can render all the form fields and save them when the user enters some data and submit. But in the second flow, I need to display only three fields as below. Name - Combination of Firstname and Lastname Email Phone The data entered in the name field should be split and saved as Firstname and Lastname. And for other remaining mandatory fields in the form that are not rendered, I can fill empty values and save the model in Backend. What is the best way to render the forms differently for each flow? Python: 3.7.3 Django: 2.1.5 -
when I deploy my project to heroku, it is not sending a confirmation email on signup but when I signup in my local computer I get the mail
django app gaierror at / [Errno -2] Name or service not known Request Method: POST Request URL: https://mangoinstagram2.herokuapp.com/ Django Version: 1.11 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /app/.heroku/python/lib/python3.6/socket.py in getaddrinfo, line 745 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Tue, 30 Jul 2019 09:07:58 +0300 -
Dynamic choices model
I'm working on my first commerce website. I have various products with totally different choices.(models,colors,quality,etc) So I want each of my products to have different choices. I'm confused what kind of Field should I add to my product Model. And how to I manage to add choices to each product. Thank you very much class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=5,decimal_places=2) category = models.ForeignKey('Category', null=True, blank=True,on_delete=models.DO_NOTHING) slug = models.SlugField(default='hello') image = models.ImageField(null=True, blank=True) available = models.BooleanField(default=True) -
How to set the time for AXES_LOCK_OUT_AT_FAILURE in django?
I am trying to lockout the users if the user attempt too many failed login attempts.And after 5 minutes I want to give access to login user again and I tried like this.I followed this documentation and write this settings in my settings.py file.However i failed to set the times for AXES_COOLOFF_TIME.I got this error : Exception Type: TypeError Exception Value: can't subtract offset-naive and offset-aware datetimes settings.py INSTALLED_APPS = [...., 'axes',] AUTHENTICATION_BACKENDS = ['axes.backends.AxesBackend',] MIDDLEWARE = [..............., 'axes.middleware.AxesMiddleware', ] from django.utils import timezone now = timezone.now() AXES_COOLOFF_TIME = now + timezone.timedelta(minutes=5) -
Use Django Permission in Pure Javascript
I used Django Permission in Django Template before like {% if perms.assets.change_log %} and it works. I want to this to render a server-side datatable in JavaScript but it failed, like <script> console.log(perm.assets.change_log) </script> There is nothing output on the console. Could you please help me with this? Thanks a lot. -
How to filter through textfield in models in django
I am trying to create a small search feature within my django project and i need to filter through my data My models are all in textfield formats, and when i try to use .filter() to search for what i want, i get an error saying that an instance of textfield has no filter. is there any way to work around this? #My Model class api_data(models.Model): data_source = models.TextField() brief_description_of_data = models.TextField() datasets_available = models.TextField() brief_description_of_datasets = models.TextField() country = models.TextField() api_documentation = models.TextField() #what I'm trying to do def index(request): query = request.Get.get('q') if query: queryset_list = api_data.datasets_available.filter(Q(title__icontains=query)) -
Is there a way to save form input to class self in django?
I have a form class where I ask for a username and password. I created my own authenticate function. I simply want to pass the username and password input to the authenticate function. I've tried saving it as self.user/self.pw or passing it directly. Thanks in advance! I am using Django lockdown. I don't need to save the username and password to a database because I'm using my own authentication function. class loginform(forms.Form): username = forms.CharField ... password = forms.CharField... def authenticate(self, request, username, password): print("this actually prints") '''authenticate with passed username and password''' -
Django - Not able to add ForeignKey or OneToOneField to User model
I have a Profile model in which I am creating a OneToOneField to User Model. Code: user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user', null=True) I am able to run makemigrations but on running migrate, I get the following error. ValueError: invalid literal for int() with base 10: 'user' -
How to solve the problem of 'auth', '0011_update_proxy_permissions'?
I am trying to load the page of django. I downgraded django to version 2.1.3 but it gave me error message. Whenever django version is 2.2.8 and I add user in admin page, it gives me another error. I also equaled uses_savepoints = True, which is by default False Error after downgrading django django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_auto_20190724_1222 dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') Error in 2.2.8 django version NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s10368_x1" -
Image not closing correctly?
I am overwriting my save model function to resize profile pictures before saving them. My function looks like this: def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) if self.avatar: with Image.open(self.avatar) as image: image_path = self.avatar.path image_name = self.avatar.path[:-4] image_ext = self.avatar.path[-4:] resize_images(image, image_path, image_name, image_ext) image.close() My resize_images function looks like this: def resize_images(image, image_path, image_name, image_ext): image = image.resize((400, 400), Image.ANTIALIAS) image.save(image_path, optimize=True, quality=95) medium_image = image.resize((250, 250), Image.ANTIALIAS) image.close() medium_path = image_name + "_medium" + image_ext medium_image.save(medium_path, optimize=True, quality=95) small_image = medium_image.resize((100, 100), Image.ANTIALIAS) small_path = image_name + "_small" + image_ext small_image.save(small_path, optimize=True, quality=95) medium_image.close() mini_image = small_image.resize((50, 50), Image.ANTIALIAS) mini_path = image_name + "_mini" + image_ext mini_image.save(mini_path, optimize=True, quality=95) small_image.close() mini_image.close() When I save an image, it works perfectly, however, when I try to upload another image just a few seconds later, I get this error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\samal\PycharmProjects\youchoices\media\users\179\avatars \179312.jpg' The culprit of this is the resize_images function because when I comment that out, this error goes away after reuploading every few seconds. However, I don't understand what I'm doing wrong. I'm closing the images, but why is it still complaining? -
Can not access imported module from inside Python function
I have a Django web app and app trying to make a script in the project directory that will create some random instances of a model (Person). For some reason, I can't access any of my import statements. I can't even use the simple 'Random' module that is built in. I keep getting an error saying 'NameError: name 'random' is not defined'. I am running this script inside of my Django project, so I am running the script by the following command: python manage.py shell < insert_into_database.py I have the following code: import io import random import string import pycountry import names domains = ["hotmail.com", "gmail.com", "aol.com", "mail.com", "yahoo.com"] letters = string.ascii_lowercase[:12] def get_random_email(domains, letters): # length of each email address length = 10 random_domain = random.choice(domains) random_name = ''.join(random.choice(letters) for i in range(length)) random_email = [random_name + '@' + random_domain for i in range(1)] # Create 1000 random records for i in range(1000): email = get_random_email(domains, letters)