Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not resolve URL for hyperlinked relationship django
Tried the solutions provided in question asked by Daniel Costa. Here is my models.py file class Integrations(models.Model): integration_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) integration_type = models.CharField(primary_key=True, max_length=256) def __str__(self): return self.integration_type class Meta: ordering = ["integration_type"] verbose_name = "Integration" verbose_name_plural = "Integrations" def get_default_mqtt(): return Integrations.objects.get(integration_type="MQTT") class MQTTSubscription(models.Model): mqtt_subscription_name = models.CharField( max_length=256, verbose_name="Subscription Name" ) mqtt_url = models.CharField(max_length=256, verbose_name="Mqtt Host") integration_type = models.ForeignKey( Integrations, default=get_default_mqtt, on_delete=models.PROTECT ) def __str__(self): return self.mqtt_subscription_name class Meta: ordering = ["mqtt_subscription_name"] verbose_name = "MQTT Subscription" The urls.py integrations_list = IntegrationsViewSet.as_view({"get": "list", "post": "create"}) integrations_detail = IntegrationsViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) mqtt_list = MQTTSubscriptionViewSet.as_view({"get": "list", "post": "create"}) mqtt_detail = MQTTSubscriptionViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) urlpatterns = [ path("integrations/", integrations_list, name="integrations_list"), path("integrations/<str:integration_type>/", integrations_detail, name="integrations_detaial"), path("mqttsubscription/", mqtt_list, name="mqtt_list"), path("mqttsubscription/<str:mqtt_subscription_name>/", mqtt_detail, name="mqtt_detail"), ] Views.py class IntegrationsViewSet(viewsets.ModelViewSet): serializer_class = IntegrationsSerializer queryset = Integrations.objects.all() lookup_field = "integration_type" class MQTTSubscriptionViewSet(viewsets.ModelViewSet): serializer_class = MQTTSubscriptionSerializer queryset = MQTTSubscription.objects.all() lookup_field = "mqtt_subscription_name" serializers.py class IntegrationsSerializer(serializers.ModelSerializer): class Meta: model = Integrations fields = ["integration_type"] class MQTTSubscriptionSerializer(serializers.ModelSerializer): lookup_field = "integration_name" class Meta: model = MQTTSubscription fields = [ "mqtt_subscription_name", "mqtt_url", "integration_type", ] The issue here is if "integrations/" is removed from urls.py it does not interpret the mqttsubscription/. While I update the … -
django unit testing timezone
In my settings.py I have implemented timezone as TIME_ZONE = os.environ.get("TIMEZONE", "Europe/London") How would I test if this is working on my test_timezone.py file? -
Django URL in Templates with Apache ProxyPass
I have a Django project behind a ProxyPass server in Apache. The project has an app called 'home', with this url patterns: urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='index'), path('projects', views.HomeView.as_view(), name='dashboard'), path('projects/<int:pid>/members', views.ProjectMembersView.as_view(), name='project.members'), There are two URL that have the same View class (the first used for the root). In the HomeView class uses a template called 'dashboard.html' and get a list of projects to send to the template view class HomeView(LoginRequiredMixin, ListView): template_name = 'home/dashboard.html' context_object_name = 'projects' login_url = 'accounts.login' def get_queryset(self): ... # returns a list of projects The template renders a tablet with some information of the project and an URL to see the employess working on the project template <td class="align-middle text-center text-sm"> <a href="{% url 'project.members' pid=project.id %}">See employees</a> </td> In the case, the project behind the Apache ProxyServer, the URL generated in the template is the form: "https://example.com/4554/members", here, Django doesn't recognizes the URL The other situation, without Apache Proxypass the URL generated is like this: "http://127.0.0.1:8000/projects/4554/members", Django can recognize the URL and return the template when click in the link. The ProxyPass configuration in Apache is in file: "/etc/apache2/sites-enabled/the-projects.conf" proxypass <VirtualHost *:80> ServerName example.com ErrorLog /var/log/apache2/projects_perror.log CustomLog /var/log/apache2/projects_access.log combined RequestHeader … -
sqlite3 table is not updating when trying to add pandas dataframe
I am trying to add a Pandas data frame to a sqlite3 table in my Django project. However, when I try to add it to the table, nothing updates and no errors are printed in the console. For reference, the beginning of my code is correctly formatting the date in the csv file and then I am attempting to add it to an empty but existing table named 'daos_transaction' with the same attributes 'from_address', 'to_address', 'date_time', and 'amount'. import pandas as pd import sqlite3 # Reads data from csv file df = pd.read_csv("correct/path/to/csv/file") # Formats the date for dt in range(len(df['date_time'])): no_t_string = df['date_time'][dt].replace('T', ' ') clean_string = no_t_string.split('+')[0] df['date_time'][dt] = clean_string # Converts the column to a date time field df['date_time'] = df['date_time'].astype('datetime64[ns]') cnx = sqlite3.connect('correct/path/to/db') df.to_sql('daos_transaction', cnx, if_exists='append') -
Django Rest Framework With Djoser Jwt
I was looking into have more secure login and logout using JWT authentication and authorization .But in Djoser ,it has 3 endpoints /jwt/create/,/jwt/refresh/,/jwt/verify/. Here I want user login with jwt token and get verified token simultaneously and when logout refresh comes in to get access token.How could I do this? -
I am getting: TypeError: view must be a callable or a list/tuple in the case of include()
My root urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('webarticles.urls')), ] While I have seen this error answered on stackoverflow before, they don't seem to work for me. Specifically there are 2 components of the answers that confuse me: Why url is used instead of path If I am to import webarticles, how to do that given that my project and app are on the same level Thank you for any help you are able to provide! -
How to send html-styled password reset email with django
I created an html-styled version of a password reset email to be set with django located at 'registration/html_password_reset_email.html'. From other stackoverflows, I learned I needed to add the html_email_template_name parameter for the html version of the email to be sent. However, even with the below code, it is just the text version of the file that is being sent ('registration/password_reset_email.html'). Hints on what I'm doing wrong? from django.contrib import admin from django.urls import include, path from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from django.urls import reverse from . import views urlpatterns = [ path('', views.homeview, name="homeview"), path('dashboard/', include('dashboard.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("register/", views.register_request, name="register"), path('reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset_form.html', html_email_template_name='registration/html_password_reset_email.html', email_template_name='registration/password_reset_email.html', ), name="reset_password"), # Submit email form path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), # Email sent success message path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), # Link to password reset form in email path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), # Password successfully changed message ] -
Submitting a Django form using a One-To-Many relationship
I'm trying to implement a One-to-Many relationship between two models in Django, and have been doing so based on this answer. I have a very simple Projects model, and a ProjectNotes model, so one Project can have multiple Notes. My models.py: class Project(models.Model): project_name = models.CharField(max_length=500) project_type = models.CharField(max_length=500) project_leader = models.CharField(max_length=500) class ProjectNotes(models.Model): note_date = models.DateField(default=date.today) assigned_project = models.ForeignKey(Project, related_name='projectnotes', on_delete=models.CASCADE) note = models.TextField(max_length=500) My use case for this is to show a webpage showing the info for a given Project object, and show a textfield form where notes can be added (also showing any notes that may exist). To that end I have my forms.py: class AddProjectNoteForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddProjectNoteForm, self).__init__(*args, **kwargs) self.fields['note'].required = True class Meta: model = ProjectNotes fields = ['note'] My template displays the formfield correctly (and I believe would show any notes that existed correctly), however when attempting to submit a note I get an error complaining an id field is null: null value in column "attached_project_id" violates not-null constraint My understanding of this is that the project_id field cannot be blank, but as I don't define it, it is something django handles internally. If that is the case, why is it … -
How to use permissions added using django-rules library in Django App?
I am creating a Django App in which I am using django-rules library to define and add permissions. I have followed the documentation and created the predicates in a separate file called permissions.py. I have also added the permissions in the same file. My permissions.py looks like below: from .models import WorkspaceMembership import rules @rules.predicate def is_workspace_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_member return False @rules.predicate def is_workspace_admin(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_admin return False @rules.predicate def is_active_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_active return False rules.add_perm("accounts.view_workspace", is_workspace_member) rules.add_perm("accounts.view_workspace", is_workspace_admin) rules.add_perm("accounts.view_workspace", is_workspace_member | is_workspace_admin) Now, I want to use these permissions in my class-based views and programmatically like checking below: if user.has_permissions("any-permission") I am unable to figure out that how to use the permissions. Because the predicates will required two objects, one is User instance and another is Workspace instance, in order to work, which are not present in permissions.py file. So, how do I use the permissions, can anybody guide me? -
How do I successfully connect Django to Azure Cache for Redis?
I have a django application that I have just migrated to MS Azure from Digital Ocean, and the app runs perfectly on Azure. However, I'm struggling to implement a cache backend with an Azure Cache for Redis service. I have the following configuration in settings.py: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://<my_redis_service_name>.redis.cache.windows.net:6380,password={secrets.AZURE_REDIS_PASSWORD},ssl=True,abortConnect=False", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", }, } } I have replaced my redis service name with <my_redis_service_name>. With this setup and DEBUG=True, I receive the error: ValueError at /accounts/login/ Redis URL must specify one of the following schemes (redis://, rediss://, unix://) Strange since redis:// is in the url. I have verified the keys, and ensured the redis service firewall accepts my VM's IP4 address, as well as making sure port 6380 is open on the VM. I have also tried various permutations of the connection string, such as: "LOCATION": f'redis://:{secrets.AZURE_REDIS_PASSWORD}@<my_redis_service_name>.redis.cache.windows.net:6380,ssl=True,abortConnect=False', No luck. If it's relevant, I'm using Django 4.0.7, Python 3.8, django-cachalot, and jazzband's django-redis pacakge. Azure Cache for Redis states that it's using Redis version 6.0.14. For what it's worth, my development environment works fine with a local daemonized redis cache at "LOCATION": "redis://127.0.0.1:6379/1",. Any help appreciated. -
How Can I filter Django Models To Get Field Values From Different Tables
I am working on Django Ticketing Application where I have a Pin Status Check View. And I want to query the Pin Model to know whether the PIN is activated, and if Activated query the Guest, and Profile Models to get the guest profile information and display in template. I have been able to use Django Forms with search to display the PIN details but NOT able to figure out the logic code for getting the guest profile if PIN is ACTIVATED. Someone may wish to help. thanks. Models code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) phone = PhoneNumberField() image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) #Method to save Image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) #Check for Image Height and Width then resize it then save if img.height > 200 or img.width > 150: output_size = (150, 250) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return f'{self.user.username}-Profile' class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, … -
Django ValueError: Cannot assign * must be a * instance
I am getting this error but I don't know why. models.py class Year(models.Model): year = models.CharField(max_length=5, unique=True) class Meta: ordering = ['-year'] def __str__(self): return self.year class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/') thumbnail = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='thumbnails/') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE) views.py def photo_create_view(request): form = AddPhotoForm() if request.method == 'POST': image = request.FILES['image'] thumbnail = request.FILES['image'] title = request.POST.get('title') description = request.POST.get('description') year = request.POST.get('year') people = request.POST.get('people') tags = request.POST.get('tags') photo = Photo(image=image, thumbnail=thumbnail, title=title, description=description, year=year, people=people, tags=tags, submitter=request.user,) photo.save() return redirect('/photo/?page=1') return render(request, 'photoapp/create.html', context={'form':form}) Cannot assign "123": "Photo.year" must be a "Year" instance. I have checked the Year table and year.id 123 exists. What am I missing? -
Django update multiple objects with options
I want to update the same field for multiple objects with the same value giving the user the available choices for that given field in a view, all this accessible from a custom action. I'm stuck at getting the value selected by the user in the view. I don't want to use the mass_edit package. This would be the custom action in the modeladmin in admin.py: def edit_selected(self, request, queryset, extra_context=None): context = {} labels = models.Label.objects.all() crop_ids = [] for i in queryset.values(): crop_id = i.get('id') crop_ids.append(crop_id) context = { "labels": labels, "ids": crop_ids, } return render(request, template_name="bulk_edit.html",context=context ) my template in bulk_edit.html: {% extends 'admin/base.html' %} {% csrf_token %} {% load spex_template %} {% block content %} {# {% if user.is_autheticated %}#} <div class="row"> <div class="col-md-12"> <form method="get"> {{ filter.form.as_p1 }} <select style="width:100px" name="label" placeholder="Add new Label" id="id_label__id"> <option value="none" selected disabled hidden>New Label</option> {% for label in labels %} <option value="{{ label.id }}">{{ label.id }} - {{label.name}}</option> {% endfor %} </select> <button type="submit">Update</button> <br> </form> <div class="card card-body"> <div><h1>Crop Ids: {% for id in ids %} {{ id }}, {% endfor %} </h1></div> <table class="table table-sm"> <tr> </tr> <br> </table> </div> </div> </div> {# {% endif %}#} … -
Django widget tweaks and variable attributes
Trying to include variables as attributes and values into a form field in a Django app. There is a somewhat related thread but to my understanding it covers one side of the problem I am facing with django-widget-tweaks / custom tags. In my case I not only want to assign a dynamic value to a predefined attribute (which I can do with extra template tags as described for instance here) but to first dynamically create an attribute and assign a value to it for the purpose of htmx requests such as hx-post or hx-delete. Including partials behaves as expected if I specify the type of htmx request directly in render_field and pass the value (in this case URL) via include as well as when I add the attribute and hard code its value using |attr: like so: {% include "partials/input-text.html" with field=form.email|attr:"hx-post:/search/" %} I have tried to apply append_attr the newly created attribute but I'm seeing AttributeError: 'SafeString' object has no attribute 'as_widget' and also getting a sensation that I'm missing the point. Ideally I'm seeking to be able to pass attribute&value as variables (could be via custom template tags), along the lines of {% include "partials/input-text.html" with field|attr:"{{hxaction}}:{{hxurl}}" %} -
Unable to log to STDOUT in django
settings.py LOG_LEVEL = "DEBUG" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "level": LOG_LEVEL, "class": "logging.StreamHandler", "stream": sys.stdout, "formatter": "console", }, "rq_console": { "level": LOG_LEVEL, "class": "rq.utils.ColorizingStreamHandler", "formatter": "rq_console", "exclude": ["%(asctime)s"], }, }, "formatters": { "rq_console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, "console": { "format": "%(asctime)s | %(name)s | %(levelname)s | %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, "loggers": { "": { "handlers": ["console"], "level": LOG_LEVEL, "propagate": True, }, "django": { "handlers": ["console"], "level": "INFO", "propagate": True, }, "rq.worker": { "handlers": ["rq_console"], "level": LOG_LEVEL, }, }, "root": { "handlers": ["console"], "level": LOG_LEVEL, }, } some/api.py logger.info("Got some info") logger.debug("Got some debug") logger.warning("Got some warning") logger.error("Got some error") I'm running Django in debug mode using python manage.py runserver and none of the log statements are logging the console. The API is working just fine. And this is the code path it is taking, I ensured it by intentionally breaking the API using a break. However, I'm unable to get the logging working for some reason! At the start of the some/api.py file I've tried using all the below loggers, and none of them are printing the logs to the console logger = … -
Settting up virtual environment
i installed django on my virtual environment but when i deactivate the env and check my local machine, django is showing on my machine without installing django on it, please what can cause this? steps i used to installed django on my virtual environment i installed virtual env create virtual environment with "virtualenv env" 3 i activate the env by using source env/bin/activate then i installed django i used django-admin to create my first project so as i want to work on my second project i create new environment activate it but to my own suprise when i "pip freeze" to check whats inside the new Environment, it showing django and some other libraries i installed on the previous environment please guys is this normal? -
How to handle the user field in Django when making a Post request to a model that is accessed using an API key?
models.py: class Hosts (models.Model) : host_label = models.CharField (max_length=64, verbose_name = "Host Label" ) host_activation_request = models.CharField (max_length = 400, verbose_name = 'Activation Request', blank=True, null=True) host_developer_email = models.CharField (max_length = 400, verbose_name = 'Developer Email', blank=True, null=True) class Meta: verbose_name = "Available Host" unique_together = [['host_label', 'host_developer_email']] serializers.py: class HostSerializer(serializers.ModelSerializer): class Meta: model = Hosts fields = ('host_label','host_activation_request') views.py: class CreateHost(CreateAPIView): serializer_class = HostSerializer def generate_activation_request(self, feature, customer_ref="Isode"): config = get_active_config() #this function has been imported at the top command_list = [os.path.join(config.generate_activation_binary_directory, "generate_activation_request")] import subprocess proc = subprocess.run(command_list, universal_newlines=True, capture_output=True) self.result = proc.stdout def post(self, request, *args, **kwargs): print(request.data) self.generate_activation_request(feature=request.data["feature"]) request.data['host_activation_request'] = self.result return self.create(request, *args, **kwargs) A user can login to the website and make a Host in there and the host_developer_email field will be their email and the other two fields will be whatever they input in the form, as host_developer_email has been set to be a hidden field. Now, I have created an endpoint called /api/host which I can send a post request to in order to create a Host instance, but I have implemented the djangorestframework-api-key library. So my request from Insomnia (can use Postman too I guess) looks like this: The Header has the … -
docker-compose, reload server each time I make changes to code
I am dockerizing my Django app and I have the following docker-compose.yml file: version: '3' services: # other services as db etc. web: container_name: web build: context: . dockerfile: Dockerfile.web restart: 'always' env_file: - csgo.env ports: - '8000:8000' volumes: - web:/code depends_on: - db volumes: web: App logs: System check identified no issues (0 silenced). web | September 15, 2022 - 01:38:47 web | Django version 4.0.7, using settings 'csgo.settings' web | Starting development server at http://0.0.0.0:8000/ web | Quit the server with CONTROL-C. I want my container (or the app, idk) to reload whenever I let's say make changes to my models or functions etc. For now, I add some functionality to my app, edit some html views, but no changes appears and the app logs doesn't say that it's reloading. I have to rebuild and up my compose again to see my changes. How to do live-reload composing up? How to send changes to docker? Thanks! -
MUI with django framework
Is it possible to use mui with a django framework? I would like to keep it server-side using django. I know typically mui is built with client side rendering by using a react library. I did find a cdn library in muicss.com but i'm afraid this library is outdated. I would like to use the current version 5.0 and all of it's classes/components. Any ideas? -
How can I access my virtual environment created 1 week ago using ubuntu? I just know the name of the virtual environment but idk how access| PYTHON
I installed my first virtual environment using this commands below Commands used: apt-get update -y apt-get install -y python3-venv mkdir awesome_python_project cd awesome_python_project python3 -m venv awesome_venv source awesome_venv/bin/activate but I can't access it again, does anyone knows why? -
What's the real use of the management/commands directory in the Django Application?
In the documentation, it is written that it can be used for writing custom Django-admin commands. But my question is why do we need to write custom Django admin commands? The given example in the official documentation is a bit dry to me. I would be really grateful if someone give real-world examples from which I can connect its real-life use. Django doc on management/commands:https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/ -
Using Default UserCreationForm does not show error if the passwords do not match
Using Default UserCreationForm from django.contrib.auth.forms does not show error if the passwords do not match. I do not want to create a custom model. Here is the code from my views.py file from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render # Create your views here. def register(response): if response.method == "POST": print(response.POST) form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: print(form.errors) form = UserCreationForm() return render(response,"register/register.html",{"form":form}) register.html code <html> <head> <title>Register </title> </head> <body> <h1>This is the Registration page</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> </body> </html> I thought the message would be automatically displayed. Am I missing something? Edit: None of the error message are being displayed like password length < 8, all numeric passwords, etc. -
Can't access to public IP of django docker container
I can access the container with these curl commands: curl http://localhost:8000/api/health/ curl http://127.0.0.1:8000/api/health/ But I can't access it with public IP address: curl http://xx.xxx.xxx.xxx:8000/api/health/ curl: (7) Failed to connect to xx.xx.xxx.xxx port 8000 after 0 ms: Connection refused I used this command to run the container: docker container run -d --network=host -p 8000:8000 my-central-api Dockerfile has this line: CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000"] I am running this container on an EC2 instance. I set up the security group and NACL. So I think it is related to docker configuration. Why I can't access to port 8000 with public IP? -
When I make migrations I get this error, what could be the reason?
I cloned the repository. Then I added several fields to the model and wanted to add them to an existing database. I ran the makemigrations command and got this error -
Heroku adds whitespace characters to django template javascript code
I'm trying to combine python and javascript code in django template to update page after every keyup event (like in a browser). I have a list of teachers with name and surname which I want to display if it matches pattern given by the user. While everything is fine on localhost, after deploying on heroku there is a syntax error: Uncaught SyntaxError: Invalid or unexpected token Here is a fragment of my teacher.html file, where python teachers is QuerySet passed from views.py during rendering and str is a pattern taken from entry, earlier in javascript function get_names(str){ let teachers = []; {% for teacher in teachers %} var name = "{{teacher.name}}"; if (name.includes(str)) { teachers.push("{{teacher|safe}}"); } {% endfor %} return teachers; } Here is output of my localhost js code var name = "John"; if (name.includes(str)) { teachers.push("John Kowalski"); } And here is output of heroku server var name = "John"; if (name.includes(str)){ teachers.push("John Kowalski <-- Error occurs here "); } More interesting is the fact, that for some names it works, but mostly it doesn't. I needed to reset the database and uploaded the same data once again using heroku run python manage.py shell. Before that everything was fine, …