Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Write and read video download progress into session
Outside of Django views, I have a function that downloads some YouTube video with pytube library. For tracking the download progress, I am leveraging the pytube's YouTube class on_progress_callback parameter: yt =YouTube(url, on_progress_callback=write_download_progress) write_download_progress is as follows: def write_download_progress(stream, chunk, file_handle, bytes_remaining): filesize = stream.filesize progress = (100*(filesize - bytes_remaining))/filesize progress = round(progress) url = 'http://127.0.0.1:8000/write_download_progress' params = {'progress': progress} try: response = requests.get(url, params) except: # ignore error caused by too frequent requests pass As you can see, as the download progresses, a request is being made to write_download_progress view, which purpose is to write the progress into session: def write_download_progress(request): progress = request.GET.get('progress', 'Error getting progress!') request.session['progress'] = progress print('WRITE ' + str(request.session['progress'])) return JsonResponse({'progress':'{}% downloaded...'.format(progress)}) I also have another view to read the progress from session, which is being called by the front end at two second interval just before the download starts: def read_download_progress(request): progress = str(request.session.get('progress', 0)) print('READ ' + progress) return JsonResponse({'progress': progress}) The print in the writing view will print correct progress values. However, the print in the reading view (and as a result - the view's JSON response) will always be zero. What might be the reason? Is there a better way … -
Bitcoin management with python
I'm going to create a website that will pay with Bitcoin and other currencies. And I want to do this with Python. please help me -
In Python, how do I force "datetime.strptim" to use a timezone?
I'm using Django and Python 3.7. I'm parsing some strings into dates using this logic ... created_on = datetime.strptime(created_on_txt, '%Y-%m-%dT%H:%M:%S+00:00') print(created_on.tzinfo) How do I incorporate the fact that the time zone I want to be interpreted for the string shoudl be UTC? When I print out the ".tzinfo," it reads "None." An example of something I'm parsing is 2019-04-08T17:03:00+00:00 -
Installing Django wagtail apps in ubuntu and conflict with version
I am using Ubuntu 18 and in my machine, installed both python3 and python2. when I install any python package with pip, it works nice! but the problem is, when i install django reuseable apps, it doesnt works fine. coz, it is installed in python2, why? For Example, i have install wagtail with pip and i tried to start project wagtail, write this command: wagtail start mysite and it troughs me an error message that This version of Wagtail requires Python 3.4 or above - you are running 2.7 Why? I have both python3.6 and python2.7, why it wagtail installed in python 2.7? even most of django reusable apps installing python 2.7. why not in 3.6???/ what is wrong with it? -
Filter an object with a many to many relation, checking if it contains at least one of the elements in a list
We're making an app that will be used to sell second-hand items. Inside of this app, we'll have an option to filter products based on a series of criteria: the user's geographical postion and a maximum distance, a minimum price, a maximum price, a minimum score, and a list of tags. My main problem is filtering the many to many relationship that a product has with a tag. What we want to do is get all the products which contain at least one of the tags selected by the user. Here's the code for the filter function: def FilterProduct(request, format=None): if request.method != 'POST': return Response(status=status.HTTP_400_BAD_REQUEST) token = request.POST.get('token', 'nothing') if token == 'nothing': return Response(status=status.HTTP_400_BAD_REQUEST) else: try: tags = request.POST.get('tags', '') tags_pk = [] for tag_search in tags: tag = Tag.objects.filter(nombre=tag_search) if tag != None: tags_pk.append(tag.pk) user_latitude = request.POST.get('latitud', '') user_longitude = request.POST.get('longitud', '') max_distance = request.POST.get('distancia_maxima', '') min_price = request.POST.get('precio_minimo', '') max_price = request.POST.get('precio_maximo', '') min_score = request.POST.get('calificacion_minima', '') if tags == '' or user_latitude == '' or user_longitude == '' or max_distance == '' or min_price == '' or max_price == '' or min_score == '': return Response(status=status.HTTP_400_BAD_REQUEST) products = Productos.objects.filter(precio__lte=max_price, precio__gte=min_price, vendido_por__media_valoraciones__gte=min_score, tiene_tags__in=tags_pk) For some reason, … -
Email verification from db
I am having a webapp in django . I tried using the tokengenerator for password reset to create a verification mail, it's not activating the email . coming to the problem , While the user provide email , it should check whether email is present in the db (db will be updated with user emails ) After verifying whether email is present in the db , user is prompted to create password 3.After creating password user can login to the respective page Is there any solution ? I tried and followed https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef Above post helped me to send the email , but the user is not activate after verifying the email , the post doesn't meet my requirement , though i tried to check whether email verification is possible. Is there any third party module for django or any solution for the requirements i have mentioned. -
Django - how to visualise signals and save overrides?
When project is getting bigger there are many dependencies and event chains. Especially in overriden save() methods and post_save and pre_save signals. Example: Like overriden A.save creates two related objects to A - B and C. When C is saved, post_save signal is invoked which do another thing etc... How to make these event chains clear? Is there a way to visualise (generate automatically) such chains/flows? I'm not looking for ERD nor Class diagram. I need to be sure when doing something, that it won't affect something on the other side of the project so simple visualisation would be the best. -
Django Apps aren't loaded yet - can't import model
I can't import my model into my celery.py file so I use it in a scheduled task - I always get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm tearing my hair out - a few people seem to have got the same error, but none in the same circumstances and I tried all the fixes and nothing works. My celery.py file in my main Django app: from __future__ import absolute_import, unicode_literals import requests import os from celery import Celery from WeatherData.models import LondonWeather os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Weather.settings') from .settings import OPEN_WEATHER_API_KEY, OPEN_WEATHER_API_URL # set the default Django settings module for the 'celery' program. app = Celery('Weather') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Gets London weather every hour. sender.add_periodic_task(10.0, get_weather_task.s(), name='london_weather_test') sender.add_periodic_task(3600.0, get_weather_task.s(), name='london_weather') @app.task() def get_weather_task(): querystring = {"q": "London,UK"} headers = { 'x-api-key': OPEN_WEATHER_API_KEY, } res = requests.get(OPEN_WEATHER_API_URL, headers=headers, params=querystring).json() LondonWeather.objects.create( longitude=res.get('coord', 0).get('lon', 0), latitude=res.get('coord', 0).get('lat', 0), main_weather=res.get('weather', {})[0].get('main', 'Rain'), description=res.get('weather', {})[0].get('description', 'No data'), temperature=res.get('main', {}).get('temp', 0), pressure=res.get('main', {}).get('pressure', 0), humidity=res.get('main', {}).get('humidity', 0), min_temp=res.get('main', {}).get('temp_min', 0), max_temp=res.get('main', {}).get('temp_max', 0), wind_speed=res.get('wind', {}).get('speed', 0), wind_direction=res.get('wind', {}).get('deg', 0), clouds=res.get('clouds', {}).get('all', 0), ) return res The init.py of my main app looks like this … -
Browser makes OPTIONS request to django for CORS request, but no POST
I'm trying to submit a form from a react application, via post, to a django server on a different origin. The browser sends an OPTIONS request, which the cors middleware on the server responds to with a 200, and the following information: HTTP/1.1 200 OK Date: Mon, 08 Apr 2019 16:34:38 GMT Server: WSGIServer/0.2 CPython/3.7.2 Content-Type: text/html; charset=utf-8 Content-Length: 0 Vary: Origin Access-Control-Allow-Origin: * Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Max-Age: 86400 Connection: keep-alive But the browser never subsequently makes a POST request. It shows no errors in the console... -
How to run external python scripts inside of Django view, only when required
So, I have an external python script to encrypt/decrypt a file in the media folder of my django project. This script does work, but when I import it into the Django views it automatically runs, can I prevent this from happening and only run functions from this piece of code when I want to? import os from . import keygen IMPORTED EXTERNAL SCRIPT #from not_g import en from django.contrib.auth.models import User, Group from django.shortcuts import render from django.http import HttpResponse, Http404 from django.contrib.auth.decorators import login_required from files.models import Document from django.conf import settings from django.shortcuts import redirect from django.views.generic import ListView, DetailView, View from cryptography.fernet import Fernet import pyAesCrypt from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from django.views import generic from django.urls import reverse_lazy from .templatetags import has_group class HomePageView(ListView): model = Document template_name = 'home.html' def download(request): key = Fernet.generate_key() f = Fernet(key) I WOULD LIKE TO CALL ENCRYPT INSIDE OF AN IF, DECRYPT IN AN ELSE keygen.encrypt(f) # keygen.decrypt(f) filename = os.path.basename(Document.document.name) response = HttpResponse(Document.document, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response -
How to create , update and delete objects in my API using django rest framework
i managed to list all the objects that i created with the admin side in Django . I'm now trying to create , update or delete objects with django rest framework . I already tried some code but it didn't succeed , i got plenty of Assertion errors . Here is my models.py : class Etudiant(models.Model): id=models.IntegerField(primary_key=True) nom=models.CharField(max_length=20) prenom=models.CharField(max_length=20) cne=models.CharField(max_length=10) email=models.EmailField() tel=models.CharField(max_length=10) def __str__(self): return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom) my views.py : class EtudiantList(APIView): def get(self,request): etudiants=Etudiant.objects.all() serializer=EtudiantSerializer(etudiants,many=True) return Response(serializer.data) my urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^etudiants/',views.EtudiantList.as_view()), ] my serializers.py : class EtudiantSerializer(serializers.ModelSerializer): class Meta : model=Etudiant fields='__all__' Any recommendations ? -
How to fix NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post/<int:pk>/']
I have tried everything i found on the internet which was simmilar to my problem, but it did not help. Please help if you know the answer. I get an ERROR while trying to set up my post_detail page of my blog. The ERROR MESSAGE: Reverse for 'post_detail' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post//'] My post_list.html {% extends "blog/base.html" %} {% load static %} <html> <head> <title>Code Reminder</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> </head> <body> <div class="page-header"> <h1><a href="/">Coder Reminder</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-4"> {% block content %} {% for post in posts %} <div class="post"> <div class="date"> {{ post.published_date }} </div> <h1><a href="{% url 'post_detail' pk=post.blog.pk %}">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} </div> </div> </div> </body> </html> My post_detail.html {% extends "blog/base.html" %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} My base.html {% load static %} <html> <head> <title>Code Reminder</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static … -
integrate multiple uploads of photos into my posts - django
integrate multiple uploads of photos into my posts - django Hi friends, as the title suggests I need to upload an undefined number of images within my posts, currently I can only upload one photo for post How can I upload multiple images in a single post? I am attaching the code of my app thank you so much # models.py class Casa(models.Model): nome_casa = models.CharField(max_length=80) descrizione = models.TextField() logo_casa = models.ImageField(blank=True, null=True) def __str__(self): return self.nome_casa def get_absolute_url(self): return reverse("visualizza_casa", kwargs={"pk" : self.pk}) class Meta: verbose_name = "Casa" verbose_name_plural = "Case" # views.py from django.shortcuts import render, get_object_or_404 from django.views.generic.edit import CreateView from .models import Casa from .mixins import StaffMixin class CreaCasa(StaffMixin, CreateView): model = Casa fields = '__all__' template_name = "inserzioni/crea_casa.html" success_url = "/" def visualizzaCasa(request, pk): casa = get_object_or_404(Casa, pk=pk) context = {"casa" : casa} return render(request, "inserzioni/visualizza_casa.html", context) -
Django Haystack SearchIndex limit size of queryset
I am using Django Haystack together with Whoosh as a search engine in my Django app. In my search_indexes.py file I define index_queryset as follows: def index_queryset(self, using=None): queryset = self.get_model().objects.all()[:10] return queryset This throws an error: AssertionError: Cannot reorder a query once a slice has been taken. Is there any other way to limit the number of results indexed by Haystack? I'm not really sure what is happening behind the scenes to cause this error. My model has a Meta field for ordering. What I want is the first 10 results that I'd get if I selected them all, with that ordering, and then just took the first 10. Help please? -
How do I write a Django query where the left side of my WHERE condition is a math expression?
I'm using Django, Python 3.7, and PostGres 9.5. I have a model with the following fields ... class DomainTrackerStat(models.Model): domain = models.CharField(max_length=255) ... num_negative_articles = models.IntegerField(default=0, null=False) num_positive_articles = models.IntegerField(default=0, null=False) I want to write a Django query that says give me all the objects whose condition match this PostGres WHERE clause WHERE num_negative_articles / (num_negative_articles + num_positive_articles) > .95 However I'm having trouble writing the Django query expression because normally it only allows for a single field, e.g. DomainTrackerStat.objects.filter(num_negative_articles__gt=.95) How do I write this more complex query? -
Database migration in django 1.0.4
I work on a very old version of django - 1.0.4. Yes, it is to be changed. My problem is migration in the database, after adding the field: is_member An error occurs: no such column: scopes_scope.is_member I've been trying to get a command: python manage.py syncdb That didn't help. Can somebody help me? -
Django Form saving
I would like to share with you my code in order to find a solution. I have a Django form. I would like to save data only if there is not another object with same data. In other words, objects should be unique. If the object doesn't exist, I save it, else I display the form with an error message 'The object already exists with this features'. This is my model: def guide_path(instance, filename): # file will be uploaded to MEDIA_ROOT/guides/<guide_id> new_filename = f'guides/{instance.site.id}' if instance.profile_type: new_filename += f'_{instance.profile_type}' if instance.profile_level: new_filename += f'_{instance.profile_level}' if instance.language: new_filename += f'_{instance.language}' name, ext = os.path.splitext(filename) if ext: new_filename += ext return new_filename class UserGuide(models.Model): """ A class for storing user guides depending on profiles """ objects = models.Manager() site = models.ForeignKey(WebApplication, on_delete=models.PROTECT, related_name='guides', verbose_name=_('application')) file = models.FileField(verbose_name='file', upload_to=guide_path) profile_type = models.CharField(verbose_name=_('profile type'), choices=UserProfile.USER_TYPES, max_length=2, null=True, blank=True) profile_level = models.CharField(verbose_name=_('profile level'), choices=UserProfile.USER_ROLES, max_length=2, null=True, blank=True) language = models.CharField(verbose_name=_('language'), choices=settings.LANGUAGES, max_length=2, default='en') class Meta: verbose_name = _('user guide') verbose_name_plural = _('user guides') unique_together = ('site', 'profile_type', 'profile_level', 'language') This is my form: class UserGuideForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = UserGuide fields = ['site', 'file', 'profile_type', 'profile_level', 'language'] widgets = … -
Problem in getting the initial value of FK field in django form?
This are my models: class Aggrement(models.Model): title = models.CharField(max_length=100, null=True, blank=True) act = models.CharField(max_length=100, null=True, blank=True) section = models.CharField(max_length=100, null=True, blank=True) category_ls = ( ('General','General'), ('Specific','Specific'), ) category = models.CharField(max_length=32,choices=category_ls,default='General') textbody = RichTextUploadingField(blank=True, null=True,config_name='special') guideline = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.act class User_aggrement(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="Users_aggrement",on_delete=models.CASCADE,null=True,blank=True) aggrement = models.ForeignKey(Aggrement,related_name="Users_aggrement",on_delete=models.CASCADE,null=True,blank=True) textbody = RichTextUploadingField(blank=True, null=True,config_name='special') def __str__(self): return str(self.id) I want to get the value of the field textbody of Aggrement model in textbody of User_aggrement model. i.e. when User will try to create an instance of User_aggrement model the textbody field should get the value of textbody in Aggrement model in the form field. Is this possible in django? Any idea? -
Differences between Q and exclude in Django filter
I am wondering what is the exact difference between these two kinds of Django filter from performance aspects. User.objects.filter(Q(first_name='R') & ~Q(last_name='Z') and User.objects.filter(first_name='R').exclude(last_name='Z') Is there any other differences except performance? Thanks in advance -
Django unable to get values from database in another table
I need to join tables in django. I am using cursor object to get all values from database. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'integration', 'USER': '****', 'PASSWORD': '***', 'HOST': '***', 'PORT': '3306', #my port is 3306 }, 'configuration': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'configuration', 'USER': '****', 'PASSWORD': '****', 'HOST': '****', 'PORT': '3306', #my port is 3306 } } views.py from django.db import connection def opdb(request): with connection['configuration'].cursor() as cursor: cursor = connection.cursor() cursor.execute("SELECT * from integrations") row = cursor.fetchone() print(row) Models.py class Integrations(models.Model): trail_userid = models.IntegerField() trail_username = models.CharField(max_length=255) client_tool_id = models.CharField(max_length=50) automation_tool_id = models.CharField(max_length=255) Project = models.CharField(max_length=255) environment = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) endpoint = models.TextField() username = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) auth_token = models.CharField(max_length=255, blank=True, null=True) connectivity_status = models.CharField(max_length=255) subscription_status = models.CharField(max_length=255) class Meta: managed = False db_table = 'integrations' integrations is a table in configuration database. Unable to get all values in integrations. ERROR: with connection['configuration'].cursor() as cursor: TypeError: 'DefaultConnectionProxy' object is not subscriptable -
I can't run tests
I'm trying to run my tests, on my virtual environment,so when I run the command: `python server/manage.py test --settings=skillcorner.settings_test api` I get the following Error: File "server/manage.py", line 8 print(f'Running with settings: {os.environ["DJANGO_SETTINGS_MODULE"]}') ^ SyntaxError: invalid syntax so I run (on my virtual environment) the command (I just used python3 instead of python: python3 server/manage.py test --settings=skillcorner.settings_test api I get the following error, which is the one I am stuck on: `Running with settings: skillcorner.settings_local Traceback (most recent call last): File "server/manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/yosra/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/yosra/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/yosra/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/yosra/.local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/yosra/.local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework'` I can't figure out how to fix this, I tried to install rest-framework using ppip install, but it doesn't work! -
error in activation of django web application
I created a virtual env that I named "f". he's working for the whole time until yesterday he gives me this error import _imp # Just the builtin component, NOT the full Python module import sys try: import _frozen_importlib as _bootstrap except ImportError: from . import _bootstrap _bootstrap._setup(sys, _imp) else: # importlib._bootstrap is the built-in import, ensure we don't create # a second copy of the module. _bootstrap.__name__ = 'importlib._bootstrap' _bootstrap.__package__ = 'importlib' try:python manage.py makemigrations _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py') except NameError: # __file__ is not guaranteed to be defined, e.g. if this code gets # frozen by a tool like cx_Freeze. pass sys.modules['importlib._bootstrap'] = _bootstrap the result of python manage.py run server is File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\f\lib\importlib__init__.py", line 25 try:python manage.py makemigrations ^ SyntaxError: invalid syntax -
Django "list_filter" based on the admin queryset
I am developing an application which has both admins and sub-admins. Sub-admins are created based on the group they belong to. So a sub-admin can see only data which is related to his group. This functionality is working perfectly. Now, I want to create a filter option based on users. For super-admin it works fine but when I see from sub-admin, I can see the complete list of users in the filter list. How can I limit this list based on sub-admins users. Suppose there is a total of 20 users, and sub-admin has only 3 users in his group. So I am able to see only 3 in the list view but in the filter option I can see all 20. Can I limit this filter to only those 3 users only? My admin model looks like below: class VideoDetailsAdmin(admin.ModelAdmin): list_display = ('video_id', 'user', 'status', 'description', 'video_name', 'upload_time', 'duration') list_filter = ('user', ) def get_queryset(self, request): # Get the groups of logged in user query_set = Group.objects.filter(user = request.user) group_list = [] for g in query_set: group_list.append(g.name) # Get the user ids of Users in those groups id_list = [] for user in list(User.objects.filter(groups__name__in=group_list)): id_list.append(user.id) # Create unique users … -
Django hangling multiple submitting
I have a comment form and a like button. Both are forms with POST method and in the same page. Problem is when I clicked like button it says "comment form is required". I mean I am trying to do different operations,liking or leaving a comment. -
Django: Ignore type of data of form field
I have a class which has an IntegerField attr. In its ModelForm, in the field of this attr, I need to send a String, which later will store an Integer once it is processed in the view. The problem is that Django doesn't allows this, and when I use form.cleaned_data.get('myattr') it's saying that it's wrong because it should be an Integer. class Student(models.Model): teacher = models.IntegerField(null=False) # I'm saving teacher's key here class Teacher(models.Model: name = models.CharField(max_length= 50, null=False) key = models.IntegerField(null=False) class StudentForm(forms.ModelForm): teacher = forms.ModelChoiceField(queryset=Teacher.objects.all(), label='Select the teacher') So, when the user is selecting the student's teacher, that select field will display the name of the teachers available. But in the model it will store their key, which I manage in view. views.py: teacher = form.cleaned_data.get('teacher') # it has the name teacher = Teacher.objects.get(name=teacher).key # getting the key in order to store an Integer, but Django is banning my code before anyway. How can I handle this without changing the data type of the model?