Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django manytomany postgresql
I am new to django and postgresql. Basically I want to display the players in a team. my database looks like this player table: enter image description here team table: enter image description here and a playteam table that links IDs together using foreign key: enter image description here I use inspectdb > models.py to create models in django and registered them in admin.py. Inside the django admin site, it looks like this: enter image description here When I click into teams, the two teams are shown and when i click into one of the team, only the name and id of the team are shown. enter image description here what I want is that there is a player field inside each team where all the players in this team can be shown. But I dont know how:( -
Create Unique Session URL in Django
I am currently working on building a web app in Django with the main purpose of providing a e-learning, tutoring style platform. The current problem I am facing is best practice on how to create a unique session URL for the participants to follow. Ideally this URL would be created via information from a schedule (e.g. Student A schedules to meet with Teacher A from 7:00PM to 8:00PM on Feb X, 201X). So far I have tried using a SQL database to store the information regarding the sessions (participants, date/time) and then use URL dispatcher to create these URLs from django.urls import path urlpatterns = [path('workspace/', views.workspace, {unique session id}), Each session will use the same underlying HTML/CSS/JS, and serving that is not the issue. The issue is how to easily create the URLs, possibly 1000s of unique URLs each day, and have those URLs be available within a set time parameters. -
how do you create new lines in a textfield?
I have a model with a TextField ("notes"), and I want to add strings to it using variables, but separate the variables with a new line (\n) aaa = "variable 1" bbb = "variable 2" ccc = "variable 3" model.objects.create(id=id, notes=aaa + '\n' + bbb + '\n' + ccc) However, when I render the field in the template as {{object.notes}}, the variables aren't separated at all. -
Doesn't Show the added field using SerializerMethodField
These are my models.py class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): name = models.CharField(max_length=255) grade = models.ForeignKey(grade, on_delete=models.CASCADE) rollno = models.BigIntegerField() What I am trying to do is make a serializer which gives me list(to implement get and delete method) of all students to a particular grade using the url: 'check/{str:pk}/'. In my serializer I am trying to combine the two models and display them together like below: class MySerializer(serializers.ModelSerializer): allStudents = serializers.SerializerMethodField() class Meta: model = Grade fields = ("grade", "allStudents") def get_allStudents(self, obj): s_list = [] fields = ['name', 'grade', 'rollno'] for stds in obj: s_list.append(model_to_dict(stds, fields=fields)) return s_list And my views.py for the same looks like following: class IndividualGrade(generics.RetrieveUpdateDestroyAPIView): ''' PUT check/{grade}/ GET check/{grade}/ DELETE check/{grade}/ ''' queryset = Grade.objects.all() serializer_class = MySerializer def get(self, request, *args, **kwargs): try: s1 = Grade.objects.get(grade=kwargs["pk"]) all_stds = Student.objects.filter(grade=s1) a_grade = Grade.objects.get(grade=s1) return Response(MySerializer(a_grade, all_stds ).data) except Grade.DoesNotExist: return Response( data={ "message": "Grade with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) def delete(self, request, *args, **kwargs): try: Grade.objects.get(grade=kwargs["pk"]).delete() return Response(status=status.HTTP_204_NO_CONTENT) except Grade.DoesNotExist: return Response( data={ "message": "Grade with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) This gives me the following error: "message": "Grade with id: grade9 does not … -
What is the modern approach for mobile specific templates?
I'm using Django 2.1 with python 3.5 and I'm looking to modify existing or provide mobile specific templates, mainly for rendering differences. Is it still a thing to support a mobile subdomain (m.mysite)? I've looked into a few solutions such as: Django-mobile and Django-subdomain but these packages seem to be out of date. There is also user_agents and amp_tools. What is the standard approach for this application these days? Thanks for your help. -
Django html to PDF not work with Japanese
I'm create a django application and want to create a PDF file using Japanese. I tried use django-easy-pdf with encoding=utf-8 but it doesn't work. The text turned out black box with japanese character. What should I do? -
Where would my datasource be? Django-Prometheus
I'm using Django Prometheus to get metrics about model creation & updating to see where data inconsistencies are. To give some context on my environment; I am in a corporate environment, so restricted by red tape. My company already uses Grafana & Prometheus elsewhere. The module is meant to act as a middleware. I have never used Prometheus or any similar concepts before. I am using Django 2.2 with Python 3.6 on a Redhat server on port 9001. Not knowing anything about Prometheus, its hard for me to translate how its interacting with Django and what changes due to it. I've tried going through "how-tos" for Prometheus, but this won't align with Django Prometheus because I have far less control over something already established. As well, on the DjangoProm Github, unfortunately the most in-depth context given is; Prometheus is quite easy to set up. An example prometheus.conf to scrape 127.0.0.1:8001 can be found in examples/prometheus. This is quite frustrating, but I'm sitting at Grafana trying to add a Datasource and I have absolutely no clue where this would be. The "drop in" nature that's implied of this module would lead me to believe it just rides off my current server, … -
What's the standard way of saving something only if its foreign key exists?
I'm using Python 3.7 and Django . I have the following model, with a foreign key to another model ... class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') ... def save(self, *args, **kwargs): if self.article.exists(): try: article_stat = ArticleStat.objects.get(article=self.article, elapsed_time_in_seconds=self.elapsed_time_in_seconds) self.id = article_stat.id super().save(*args, **kwargs, update_fields=["hits"]) except ObjectDoesNotExist: super().save(*args, **kwargs) I only want to save this if the related foreign key exists, otherwise, I've noticed errors result. What's the standard Django/Python way of doing something like this? I thought I read I could use ".exists()" (Check if an object exists), but instead I get an error AttributeError: 'Article' object has no attribute 'exists' -
drf mongoengine serializer imagefield none
I used Django restframework and mongoengine. Here is my model and serializer. [model.py] class Attachment(EmbeddedDocument): attachment_id = SequenceField() path = StringField() path_small = StringField() class Book(Document): book_id = SequenceField() user_id = LongField(required=True) attachments = ListField(EmbeddedDocumentField(Attachment)) created_at = DateTimeField(default=datetime.now().replace(microsecond=0)) updated_at = DateTimeField(default=datetime.now().replace(microsecond=0)) [serializer.py] from rest_framework_mongoengine.serializers import DocumentSerializer from rest_framework.serializers import ImageField from books.models.mongo import Book class BookSerializer(DocumentSerializer): image = ImageField() class Meta: model = Appeal fields = ( 'book_id', 'image', ) Work flow like this. Upload image to s3 Get s3 path Save s3 path to attachments field in models.py. So do not defined attachments to ImageField() in models.py. Just set image = ImageField() in serializer to validate it is correct image. But when I validate with serializer.is_valid(), image get None. [views.py] class BookList(GenericAPIView): serializer_class = BookSerializer queryset = '' def post(self, request: Request) -> Union[Response, NoReturn]: serializer = AppealSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) appeal = CreateAppealInteractor().execute(request=serializer.data) return Response(status=status.HTTP_200_OK) As you know that after serializer.is_valid(), I printed serializer.data. But it throw None like this -> {'book_id': 1, 'image': None} Is there any error in my code? Thanks. -
Django body encoding vs slack-api secret
I am following the instruction from this page. I am building a slack slash command handling server and I can't rebuild the signature to validate slash request authenticity. here is the code snippet from my django application: @property def x_slack_req_ts(self): if self.xsrts is not None: return self.xsrts self.xsrts = str(self.request.META['HTTP_X_SLACK_REQUEST_TIMESTAMP']) return self.xsrts @property def x_slack_signature(self): if self.xss is not None: return self.xss self.xss = self.request.META['HTTP_X_SLACK_SIGNATURE'] return self.xss @property def base_message(self): if self.bs is not None: return self.bs self.bs = ':'.join(["v0", self.x_slack_req_ts, self.raw.decode('utf-8')]) return self.bs @property def encoded_secret(self): return self.app.signing_secret.encode('utf-8') @property def signed(self): if self.non_base is not None: return self.non_base hashed = hmac.new(self.encoded_secret, self.base_message.encode('utf-8'), hashlib.sha256) self.non_base = "v0=" + hashed.hexdigest() return self.non_base This is within a class where self.raw = request.body the django request and self.app.signing_secret is a string with the appropriate slack secret string. It doesn't work as the self.non_base yield an innaccurate value. Now if I open an interactive python repl and do the following: >>> import hmac >>> import hashlib >>> secret = "8f742231b10e8888abcd99yyyzzz85a5" >>> ts = "1531420618" >>> msg = "token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c" >>> ref_signature = "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503" >>> base = ":".join(["v0", ts, msg]) >>> hashed = hmac.new(secret.encode(), base.encode(), hashlib.sha256) >>> hashed.hexdigest() >>> 'a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503' You will recognise the referenced link … -
ImproperlyConfigured while Using SerializerMethodField Django
These are my models.py class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): name = models.CharField(max_length=255) grade = models.ForeignKey(grade, on_delete=models.CASCADE) rollno = models.BigIntegerField() What I am trying to do is make a serializer which gives me list(to implement get and delete method) of all students to a particular grade using the url: 'check/{str:pk}/'. In my serializer I am trying to combine the two models and display them together like below: class MySerializer(serializers.ModelSerializer): class Meta: model = Grade fields = ("grade", "allStudents") allStudents = serializers.SerializerMethodField('devices') def get_allStudents(self, obj): d_list = [] fields = ['name', 'grade', 'rollno'] for stds in obj: s_list.append(model_to_dict(stds, fields=fields)) return s_list And my views.py for the same looks like following: class IndividualGrade(generics.RetrieveUpdateDestroyAPIView): ''' PUT check/{grade}/ GET check/{grade}/ DELETE check/{grade}/ ''' queryset = Grade.objects.all() serializer_class = MySerializer def get(self, request, *args, **kwargs): try: s1 = Site.objects.get(siteID=kwargs["pk"]) all_stds = Student.objects.filter(grade=s1) a_grade = Site.objects.get(siteID=s1) return Response(MySerializer(a_grade, all_stds ).data) except Site.DoesNotExist: return Response( data={ "message": "Site with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) def delete(self, request, *args, **kwargs): try: Grade.objects.get(grade=kwargs["pk"]).delete() return Response(status=status.HTTP_204_NO_CONTENT) except Site.DoesNotExist: return Response( data={ "message": "Song with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) This gives me the following error: ImproperlyConfigured at /check/grade1/ Field name `allStudents` is … -
Set $PYTHONHOME and $PYTHONPATH, but still cannot run unit tests
I'm using Django and Python 3.7 on Mac High Sierra. I'm having an issue when trying to run my unit tests. Following teh advice here -- Python (Windows) - ImportError: No module named site , I set my $PYTHONHOME and $PYTHONPATH localhost:mainpage_project davea$ echo $PYTHONHOME /usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7 localhost:mainpage_project davea$ echo $PYTHONPATH /usr/local/bin/python localhost:mainpage_project davea$ Not sure why I need to do this since I'm using a virtual environment. Nonetheless, when I run the tests, I get localhost:mainpage_project davea$ ./manage.py test ImportError: No module named site I'm at a loss for other variables I need to set in order to proceed. -
Django-background-tasks : tasks being randomly locked and never unlocked
I am using the django-background-tasks 1.2.0 on Ubuntu 18.04 and Im running it with a cronjob. Is it possible that my cronjob somehow starts the tasks right before it is refreshed and then it gets stuck ? It could be one or many stuck tasks at the same moment, depending on how many pending there are. Cronjob: * * * * * /project/manage.py process_tasks --duration=59 --sleep=2 settings.py BACKGROUND_TASK_RUN_ASYNC = True BACKGROUND_TASK_ASYNC_THREADS = 4 -
replacing dropdown lookup with related user field
In a form I have a drop down of usernames, this is referenced in the 'taken_by' field. I would like to display first_name and last_name, this is achieved through the __str__ but I can't seem to get it to function, the list of usernames are presented but not the firstname. Suggestions welcome. from django.contrib.auth.models import User from django.conf import settings class Sample(models.Model): sample_id = models.AutoField(primary_key=True) area_easting = models.IntegerField(choices = EASTING_CHOICES) area_northing = models.IntegerField(choices = NORTHING_CHOICES) context_number = models.IntegerField() sample_number = models.IntegerField() material_type = models.CharField(max_length=200, default='', blank=True, null=True, choices = MATERIALS) weight = models.DecimalField(max_digits=6, decimal_places=2) description = models.CharField(max_length=500, default='', blank=True, null=True) recovery_method = models.CharField(max_length=200, default='', blank=True, null=True, choices = RECOVERY_METHODS) taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete = models.PROTECT) comments = models.CharField(max_length=1000, default='', blank=True, null=True) def __str__(self): return self.taken_by.first_name # return str(self.sample_id) # return str(self.firstname)+ '-' +str(self.lastname) # return u'%s %s' % (self.first_name, self.last_name) -
Django model field name "check" raises SystemCheckError
The Django docs state there are only two restrictions on model field names A field name cannot be a Python reserved word A field name cannot contain more than one underscore in a row However, given the following example, it doesn't look like I can use the field name check as a ForeignKey. class Check(models.Model): name = models.CharField(max_length=100) class MyModel(models.Model): # this works fine #check = models.BooleanField() # this breaks check = models.ForeignKey(Check, on_delete=models.PROTECT, related_name='+') Here's the error: $ python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: myapp.MyModel: (models.E020) The 'MyModel.check()' class method is currently overridden by <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x03A818D0> Are the docs wrong, or am I doing something wrong? -
In Django DRF I always get the ValueError in my update method in my serializer
I am using Django DRF and I have successfully created the create method in my serializer but somehow the update method doesn't want to work as I want. I always get the same ValueError. My Model: class User(models.Model): gender = models.CharField(max_length=10, choices=GENDER, default='Male') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) position = models.CharField(max_length=50) birthday = models.DateField(auto_created=False, null=True) email = models.EmailField(max_length=50) phone = models.CharField(max_length=15) password = models.CharField(max_length=100, null=True) class Company(models.Model): company_name = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=50, blank=False) zip = models.IntegerField(blank=False) city = models.CharField(max_length=50, blank=False) email = models.EmailField(max_length=50, blank=False) class PartnerCompany(models.Model): partner = models.ForeignKey(Company, on_delete=models.PROTECT) contact_person = models.ForeignKey(User, on_delete=models.CASCADE) My Serializer class PartnerCompanySerializer(serializers.ModelSerializer): partner = CompanySerializer(many=False) contact_person = ClientUserSerializer(many=False) class Meta: model = PartnerCompany fields = '__all__' def create(self, validated_data): partner = validated_data.pop('partner') contact_person = validated_data.pop('contact_person') partner_instance = Company.objects.create(**partner) contact_person_instance = User.objects.create(**contact_person) return PartnerCompany.objects.create(partner=partner_instance, contact_person=contact_person_instance, **validated_data) def update(self, instance, validated_data): instance.partner = validated_data.get('partner', instance.partner) instance.contact_person = validated_data.get('contact_person', instance.contact_person) partner_instance = Company.objects.update(**instance.partner) instance.save(partner_instance) return instance My View: class PartnerCompanyUpdateByID(generics.RetrieveUpdateAPIView): lookup_field = 'id' queryset = PartnerCompany.objects.all() serializer_class = PartnerCompanySerializer I always get this ValueError: ValueError at /partner/update/id/6 Cannot assign "OrderedDict([('company_name', 'UBS Switzerland'), ('address', 'Mainstreet 1'), ('zip', 4102), ('city', 'Basel'), ('email', 'ubs@ubs.ch')])": "PartnerCompany.partner" must be a "Company" instance. -
When exactly cached_property reset?
Currently I'm using @cached_property for avoiding duplicate access to db. class MyModel(models.Model): ... @cached_property def my_opts(self): options = Option.objects.filter(...) return options ... I used this property front template. It work fine in shell & test. But when I tested in browser, I didn't know exactly when the cached property reset. Whenever I refresh my browser, the property reset. Then is it useful to use cached property in this scenario? And when exactly the cached_property value reset in the aspect of client side? Thanks in advance! -
How to add a class to the Django countries widget
Hi I am trying to use a Django plugin called django-countries to add a select with all the countries, sofar It's working but how can I add a html class to the select? -
How do I display a rounded version of a number in my Django/Python template?
I'm using Django and Python 3.7. In my template I have this {{ round(articlestat.votes) }} which results in teh error Could not parse the remainder: '(articlestat.votes)' from 'round(articlestat.votes)' Is there a way to display a rounded version of my number without creating an additional @property method in the model? It just seems like overkill to do a method every time I want the data formatted a little differently. -
Django: Can't use session vars in form
I have this session var: empresa=request.session['codEmp'] I have a form with a ModelChoiceField: class AuxiForm(forms.ModelForm): tipAux = forms.ModelChoiceField(queryset=TipoAux.objects.all(), empty_label=None, required=True, to_field_name='codigo') If you see the queryset for tipAux it's currently calling for all the TipoAux objects, but I really need to do a filter, calling only the TipoAux objects that have the same empresa attribute that the user has on his codEmp session var. I tried by doing: tipAux = forms.ModelChoiceField(queryset=TipoAux.objects.filter(empresa=request.session['codEmp']), empty_label=None, required=True, to_field_name='codigo') But it seems that Django doesn't allows request.session in forms. Any way to handle this? -
How to create an API with Django's REST Framework using Models Only with Pivot Tables?
Hi I am pretty new to python and Django's REST Framework. I am trying to build an API endpoint where I can provide the Watchlist info's and also all related Movies to it. I am using an existing DB with the following models: I guess you would normally have the Watchlist with a ManyToManyField pointing to the movies.. So I assume I could change the Models, but is there a way to create an endpoint with the given models? class Movie(models.Model): title = models.CharField(max_length=255) plot = models.TextField(blank=True, null=True) release_year = models.IntegerField(blank=True, null=True) release_month = models.IntegerField(blank=True, null=True) release_day = models.IntegerField(blank=True, null=True) duration = models.IntegerField(blank=True, null=True) poster_image_path = models.CharField(max_length=255) original_language = models.CharField(max_length=15, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class MovieWatchlist(models.Model): movie_id = models.IntegerField() watchlist_id = models.IntegerField() created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) display_order = models.IntegerField(blank=True, null=True) class Watchlist(models.Model): user_id = models.IntegerField() type_id = models.IntegerField() title = models.CharField(max_length=255) description = models.CharField(max_length=255) is_public = models.BooleanField() created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) cover = models.CharField(max_length=255, blank=True, null=True) slug = models.CharField(max_length=255, blank=True, null=True) -
Django - Ajax POST JS variables to initialize form without page refresh
I've gotten some excellent help so far, but wanted to post this question more clearly and specifically. My situation: Working in django, I have a django form within a modal window. The modal window opens after an api call to gather some geology data. I am hoping to populate this form with the geology data, without refreshing the page. I am using ajax to create a post that get's my data object over to views.py (I am able to print the data upon POST from views.py into the terminal) but the form is not initializing with the data. Instead, it is initializing with the "PRE_POST" values, even after the api call to gather the data and post via ajax. Any thoughts on what might be going on here, or how to resolve would be much appreciated! matMap.html (snippets) <!-- mineralForm Modal --> <div class="modal fade draggable" id="mineralFormModal" role="dialog" style="height: 100%;"> <!-- Modal content--> <div class="modal-header"> <button id ="mineralFormModalClose" type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title" align="center" style="font-family: Lobster">Add New Mineral</h4> </div> <div class="mineralFormModal_body" id="mineralFormModal_body" style="position:absolute; top:0"> <h3>loading before modal clears</h3> </div> <br> {{ form }} <br> <button id="modalSave" type="button" class="btn btn-default" data-dismiss="modal">Save</button> <div class="modal-footer red lighten-3"> <button id="modalClose" type="button" class="btn btn-default" data-dismiss="modal">Close</button> … -
Django no explicit app label in INSTALLED APPS
I am getting the runtime error Model class accounts.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. After spending hours searching the web for solutions, I still cannot figure out what I am doing wrong. (note: using Django 1.11) models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser verified = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email & Password are required by default. objects = UserManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): # __unicode__ on Python 2 return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" return self.staff @property def is_admin(self): "Is the user a admin member?" return self.admin @property def is_active(self): "Is the user active?" return self.active @property … -
Angular-Django full stack app in production mode giving run time errors
I am building a sample full stack app with Angular 6 on the front end and Django 2.02 on the backend. The entire code is here: https://github.com/shivkiyer/django-angular I got this working in dev mode with doing "ng serve" to start my Angular dev server and "python manage.py runserver --settings=django_angular.settings.development" on my Django. I access the Angular server on localhost:4200 which makes API calls to localhost:8080 When I do a "ng build --output-hashing none" on the Angular terminal, and continue with the Django dev server, all is well and I can access the app completely from my localhost:8080. When I do "ng build --prod --output-hashing none" on the Angular terminal and run the Django dev server, I don't get any compile errors on the ng build but I get run-time errors. To begin with my Bootstrap styling doesn't show up. And I get the errors in the console: GET http://localhost:8080/static/styles.js net::ERR_ABORTED GET http://localhost:8080/static/vendor.js net::ERR_ABORTED When I get to Django production mode. I set DEBUG=False, and added my local computer IP address along with 127.0.0.1 and localhost to ALLOWED_HOSTS. I did a "python manage.py collecstatic". When I run the server with "python manage.py runserver --settings=django_angular.settings.production", I get no page at all. I … -
string.isalpha() returning False under custom django validator whether string contains a number or not
I am trying to use custom validation on a Django CharField model field. I'm checking whether the name has number in it. If it does, raise a ValidationError. I use the line if name.isalpha() is False: raise ValidationError. For some reason this equates to False whether there is a number present in the string or not. I checked to make sure that name was the value I was expecting it to be and that it was indeed a string. Here is my code: models.py name = models.CharField(validators=[validate_name], max_length=100, default='', unique=True) validation.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_name(name): print(name.isalpha()) if name.isalpha is False: raise ValidationError( _('Name can only contain letters A-Z. Not numbers.'), params={'name': name}, )