Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking if values are in JSON received via API (Python / Django)
I am trying to check if certain values are within data sent by stripe to a webhook in my Django application. The data received looks like this within a WebHookEventTrigger model in a field called 'body' (removed some irrelevant fields): Body= { "id": "evt_1IX2nQHiJcStEaySS5pgOO4l", "object": "event", "api_version": "2020-03-02", "created": 1616239004, "data": { "object": { "id": "cs_test_a1ZHPGoSfEreDQhdioGxpWgYc1y5lhnwuo5qdeOsBqpio764yk0caFIBwg", "object": "checkout.session", "amount_subtotal": 1000, "amount_total": 1000, "currency": "gbp", "customer": "cus_1234", "customer_details": { "email": "abc@gmail.com", }, "customer_email": null, "mode": "payment", "payment_intent": "pi_1234", "payment_method_types": [ "card" ], "payment_status": "paid", "total_details": { "amount_discount": 0, "amount_tax": 0 } } }, "type": "checkout.session.completed" } I'm trying to see if certain values are in the json data as follows, although I receive errors with this code such as 'Unsupported lookup 'data' for TextField or join on the field not permitted': Values I am checking: chargeamount = 1000 chargecustomer = cus_1234 chargetimestamp = str(1616239004) chargetimestamp = chargetimestamp[:-3] #cut last 3 digits of timestamp as seconds will vary Code to check if values exist: checkoutsession = WebhookEventTrigger.objects.get(body__data__object__customer=chargecustomer, body__data__object__amount_total=chargeamount, body__created__icontains=chargetimestamp) checkoutsessionid = checkoutsession.body['data']['object']['id'] -
Authenticate a user login based on face encodings stored on database?
I am working on a face-login project where a user can submit his images using a webcam during the registration and login to the website using a live camera feed. The problem I am facing currently is submitting the snapshot stored on the HTML canvas a form "response" and storing the face-encoding or the entire image for now to the database associated with this user. I have successfully created a Registration / Login page that authenticates based on the Username and the Password for now. I made this using the 'User' model imported from django.contrib.auth.models. I read a bit about OneToOne models but it says not to be used for Authorization and I specifically need it for Authorizing the login. On the Registration page, I have added a section where a user can click a button and take a snapshot. The problem is How do I submit this image as a part of the form? Store this base64 image to the Database which I will retrieve later for Authentication. Any hints on how to proceed would be great! I tried modyfing the User model to have an extra face_data field but it doesn't work. Views.py from django.shortcuts import render, HttpResponse, … -
Django Admin Page show model referencing to another model as choose list
I already created a new database instance called StatusList: class StatusList(models.Model): status_text = models.CharField(max_length=300) color = ColorField(default='#ff0000') def __str__(self): return self.status_text I also created some entries like: "Shop closed; red color", "Shop open; green color", etc... This is supposed to show up, when calling the Homepage and show the status with the associated color. Therefore, I would like to choose (drop-down list in Admin Page) one entry provided by StatusList. I thought about a second model called "StatusChoosen", but does it make sense? It is an instance with just one entry representiong the one choosen by an admin. Even in this case I don't know how to show all entries from StatusList and return the active one. I would appreciate your help. -
Problem with CKEDITOR attachments integrated in Django contact mail form
I integrated ckeditor in my contacts form-email following the instructions provided by the official documentation and it works correctly. My problem is the following (both locally and in production): when I attach an image or an attachment (via ckeditor uploader) and send the email from the form, I receive an email in which the image is not visible and the attachment is not downloadable. By copying the link of the image or attachment, the path is shown and not the url .. I think this is the problem. Don't know how to fix it? Anyone have any ideas? Thank you in advance!!! Below is the code I used: settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'core/static'), os.path.join(BASE_DIR, 'appForum/static'), os.path.join(BASE_DIR, 'appEventi/static') ] STATIC_URL = '/static/' STATIC_ROOT = "/home/django/static-serve" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media-serve') MEDIA_URL = '/media/' CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'ckeditor_uploads' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_BROWSE_SHOW_DIRS = True CKEDITOR_CONFIGS = { 'toolbar_custom': { 'toolbar': 'Custom', 'skin': 'moono-lisa', 'width': 'auto', 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source',], {'name': 'insert', 'items': ['Image', 'Update', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar']}, {'name': 'extra', 'items': ['CodeSnippet']}, ], }, } models.py from ckeditor_uploader.fields import RichTextUploadingField # Create your … -
How to write save Postgresql query in Django
In my Django project I have SQL query like this: `..." WHERE column1 LIKE %s", query + " OR column2 LIKE %s", query...` I read that using the %s" is good practice because it prevents SQL injection, but when i run this I get an error like `can only concatenate tuple (not "str") to tuple`. How to write this query properly and avoid SQL injection? (Disclaimer: I know that ORM is fantastic, but I HAVE TO use raw query) -
Comparing list coming from form-field with database field of multiple values and filter out the objects [django]
I have postgresql database setup with django framework. straight to the problem I am facing, let's say in one of the database fields contains country data like "US,India,UK" (for this I have use django multiselectfield package to store data in database) and data coming from frontend is like "India,US" something like that. Now I have to filter object based on this. I can't use __in filter of django because it compare single value store in database to the list. any solution ? -
Django ./manage.py test is failing
I've created a migration file with 3 RunSQL operations. First operation is to drop a column and other two operations are to delete table data and the migration file is working fine. But ./manage.py test is failing with the below error. django.db.utils.ProgrammingError: column xxx does not exist. I can see the column is dropped in test_##app## db, but it is trying to drop column again. I can also see the migration file entry in django_migrations. Is there a way to check if the column is available or not before executing the ALTER operation in migration file? -
Trying to override djoser serializer getting AttributeError: Got AttributeError when attempting to get a value for field error
I am new to djoser I am user to authenicate a user. I then wanted patient information to be displayed when user/me is accessed but i overrode it to also show patient details as well but I go this error Error AttributeError: Got AttributeError when attempting to get a value for field `blood_sugar_level` on serializer `PatientInfoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the UserProfile instance. Original exception text was: 'UserProfile' object has no attribute 'blood_sugar_level'. Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.conf import settings # used to retreive AUTH_USER_MODEL from settings.py file # These two imports allow for the default user model to be customized or overrided from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin # Default model manager from django.contrib.auth.models import BaseUserManager class UserProfileManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, name, password=None): """Create a new user profile""" if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name,) user.set_password(password) #This hashes the user password so we do not have plain text passwordfs in our db user.save(using=self._db) return user def create_superuser(self, email, name, password): … -
saving image in a create/update view in django
In the model i have ImageField: image = models.ImageField(null=True, blank=True, upload_to='post_images') The problem is when i am trying to add a picture in create/update view. It does not work. It looks like it is working, there is no erros, but the image is not being saved. The only way I can do this is by django admin panel. create view: class PostCreateView(generic.CreateView): model = Post template_name = 'posts/create.html' form_class = PostModelForm def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post.save() return super(PostCreateView, self).form_valid(form) def get_success_url(self): return reverse('posts:home') urls: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) form: class PostModelForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'text', 'image', ) settings: MEDIA_URL = '/media/' MEDIA_ROOT = 'media_root' What can be the problem? -
How to make a sampling to get rid of duplicates in the GeneriсForeignKey model?
I'm already broken. I want to get rid of the duplicates that seem to come from files and articles. I am displaying comments, specifically the comment block in the sidebar. @register.simple_tag() def get_last_comments(): article_comments = Comment.objects.filter(content_type=ContentType.objects.get_for_model(Article)).select_related('author') files_comments = Comment.objects.filter(content_type=ContentType.objects.get_for_model(File)).select_related('author') result_list = sorted(chain(article_comments, files_comments), key=attrgetter('time_create'), reverse=True)[:5] return result_list I want to add a prefetch_related in order to get rid of duplicates from materials. In models class File(models.Model): ...some fields... author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey('Category', on_delete=models.PROTECT) comments = GenericRelation(Comment, related_query_name='file', related_name='file_comments_related') class Article(models.Model): ...some fields... category = models.ForeignKey('Category', on_delete=models.PROTECT) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) type = models.ManyToManyField('Type', blank=True) comments = GenericRelation(Comment, related_query_name='article', related_name='article_comments_related') How can I enter prefetch_related correctly? I looked through other topics, but it does not work for me as it should. It is necessary that the type, categories, author do not make duplicates. -
How to create front end for a chat bot made with python, json, react?
I've learnt basic HTML, CSS but have no idea how I'd link a pre-existing backend created by someone else as a web app. I've heard Django and Flask, but no idea how to get started. Trying to learn fast for now - just to connect the dots. Later I can look more into theory/practice (it's for my first hackathon and we're all beginners and I don't know what I'm doing - but if anyone can save you it's stackoverflow!) -
Write UniqueConstraint (migrations fail)
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Migration class Migration(migrations.Migration): initial = True dependencies = [ ('clients', '0001_initial'), ('semantics', '0001_initial'), ] operations = [ migrations.CreateModel( name='BranchSemanticsTemplate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('archived', models.BooleanField(db_index=True, default=False, verbose_name='Archived')), ('flag', models.BooleanField(default=False, verbose_name='Flag')), ('branch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='clients.branch', verbose_name='Branch')), ('semantics_level_two', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='semantics.semanticsleveltwo', verbose_name='Level 2')), ], options={ 'verbose_name': 'Branch template - branch- semantics - semantics template', 'verbose_name_plural': 'Branch template - branch- semantics - semantics template', }, ), migrations.AddConstraint( model_name='branchsemanticstemplate', constraint=models.UniqueConstraint(fields=('branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt'), name='semantics_branch_template'), ), ] migrate (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, sessions, staticassets, tmplts, toponyms Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK … -
How to get selected value in clean form?
I want to validate a field based on a seleted field. However when I put the prints on the form the select field appears as None (but in the view I can get the value without problems). models.py class NyModel1(models.Model): field1 = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return self.field1 class MyModel2(models.Model): f_field = models.ForeignKey(NyModel1, on_delete=models.PROTECT) my template <select id ="id_fild" class="select" name="f_fild" required=True> {% for value, field in Form.fields.f_field.choices %} <option value="{{value}}"> {{field}} </option> {% endfor %} </select> forms.py class Form(forms.ModelForm): document = forms.CharField() class Meta: model = MyModel2 fields = ['f_field', 'document'] def clean_document(self): doc = self.cleaned_data.get('document') f= self.cleaned_data.get('f_field') print("Document: ",doc) print("f Field : ",f) if f == "something one": #validate document else: #other action return doc In the print appear: Document: 12345 f Field : None How can I get the value of select on the form? -
How to display images from api in nextjs
I am building an ecommerce store with django rest framework and nextjs as the frontend. Thee api has the product data and i want to show product data in nextjs. SO far i can only show the string characters but cannot show the images. Here's my index.js file.What am i doing wrong?: import react from 'react'; import axios from 'axios'; import 'bootstrap/dist/css/bootstrap.min.css'; import Button from 'react-bootstrap/Button'; import Container from 'react-bootstrap/Container'; import Col from 'react-bootstrap/Col'; import Card from 'react-bootstrap/Card'; import Image from 'next/image'; //images from the api in variables const image1 = 'http://localhost:8000/media/media/3_Tiny-glass-cup-of-espresso-coffee.jpg' const image2 = 'http://localhost:8000/media/media/americano.jpeg' const image3 = 'http://localhost:8000/media/media/banana.jpeg' const image4 = 'http://localhost:8000/media/media/bigbfast.jpeg' const image5 = 'http://localhost:8000/media/media/caffe_latte.jpeg' const image6 = 'http://localhost:8000/media/media/cappuccino.jpg' const image7 = 'http://localhost:8000/media/media/caramel-latte-image-square.jpg' const image8 = 'http://localhost:8000/media/media/choco_lava.jpeg' const image9 = 'http://localhost:8000/media/media/hot_tea.jpeg' function Page({stars}) { return ( <div> {stars.map((post) => ( <Card style={{ width: '18rem',float:'right' }} key={post.id}> <img src={post.image} width='70' height='70'/> <Card.Body> <Card.Title>{post.title}</Card.Title> <Card.Text> {post.description} </Card.Text> <Button variant="primary">Add to cart</Button> </Card.Body> </Card> ))} </div> ) } Page.getInitialProps = async (ctx) => { const res = await fetch('http://localhost:8000/api/products') const json = await res.json() return { stars: json } } export default Page -
django filter and pagination
Actually I have two inquiries. I looked a lot for answers, but I could not find. 1 _ How to add multiple pagination to same view ? 2 _ How to add options to the filter, such as dropdown ? this is my view.py: def Multimedia_Software(requset): category = Categorie.objects.all() Multimedia_Software = Apps.objects.filter(category=category[6]).order_by('App_title') myFilter = AppsFilter (requset.GET,queryset = Multimedia_Software) Multimedia_Software = myFilter.qs paginator = Paginator(Multimedia_Software,15) page = requset.GET.get('page') try: Multimedia_Software=paginator.page(page) except PageNotAnInteger: Multimedia_Software=paginator.page(1) except EmptyPage: Multimedia_Software=paginator.page(paginator.num_pages) context = { 'page':page, 'Multimedia_Software':Multimedia_Software, 'myFilter':myFilter, } return render( requset , 'windows/Multimedia_Software.html' , context ) this my filter.py: import django_filters from .models import Apps class AppsFilter (django_filters.FilterSet): App_license = django_filters.CharFilter(label='Filter the license' ) class Meta: model = Apps fields = ['App_license'] this is my model.py: App_license = models.CharField(max_length=100 , null=True) I used pagination with first queryset and I want to use it too with filter.How is this done? and How can I add options to the filter like freeware , trail , demo ? -
Django 2.1: Template structure
I am having trouble with Django routing to find templates located at the app-level. That is, templates at the app-level directory are not rendered unless I put them in the root project-level directory. But the problem with this architecture for me is that, if I have two or more apps all having a file named index.html how do I resolve that from the templates folder at the project-level so that they won't be confliction -
No module named 'django' when trying to import Django into Scrapy
This is my folder structure: root: |--Django_project |--|-- db_app |--|-- Django_project |--|-- manage.py |--Scrapy_project |--|--Scrapy_project |--|--|--spiders |--|--|--settings.py |--|--|--pipelines.py |--|--|--items.py |--|--|--middlewares.py |--|--scrapy.cfg In settings.py I have this: import sys import os sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'Django_project.settings' import django django.setup() I've tried every possible path, including an absolute path to the project root, to the Django project, to the Django app - nothing works and I get this: ModuleNotFoundError: No module named 'django' Thanks for the help! -
server is running but page not accessing?
while working in a Django latest version, I got a error like Page not found (404) Request Method:GETRequest URL:http://127.0.0.1:8000/ Using the URLconf defined in now.urls , Django tried these URL patterns, in this order: admin/ home [name='home'] The empty path didn't match any of these. for creating a simple webpage with more than 3 HTML pages.why..? -
Where do I place the password validators? (django)
I'am working on a website for a school project where members are supposed to log in. I know of the built-in password validators in Django and I have added them to my settings.py. This is what I have so far in the serializers.py: def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance I have imported the validators like this: import django.contrib.auth.password_validation as validators Can I add the validators to this code and do something like this: def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) try: validators(password, self.instance) except forms.ValidationError as error: self.add_error('password', error) return password instance.save() return instance -
Django app data deployed to Heroku reverts back to normal after a certain period of time
I've deployed an app I made with Django to Heroku, but after a certain period of time after saving new data, it reverts to the state it was in when I deployed it. I am using the initial sqlite3 for the database, is this the cause? I would appreciate it if you could tell me more about it. -
BranchSemanticsTemplate has no field named 'semantics_tmplt'
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Migration # Generated by Django 3.1.7 on 2021-03-20 10:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('clients', '0001_initial'), ('semantics', '0001_initial'), ] operations = [ migrations.CreateModel( name='BranchSemanticsTemplate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('archived', models.BooleanField(db_index=True, default=False, verbose_name='Archived')), ('flag', models.BooleanField(default=False, verbose_name='Flag')), ('branch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='clients.branch', verbose_name='Branch')), ('semantics_level_two', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='semantics.semanticsleveltwo', verbose_name='Level 2')), ], options={ 'verbose_name': 'Branch template - branch- semantics - semantics template', 'verbose_name_plural': 'Branch template - branch- semantics - semantics template', }, ), migrations.AddConstraint( model_name='branchsemanticstemplate', constraint=models.UniqueConstraint(fields=('branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt'), name='semantics_branch_template'), ), ] Traceback (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, … -
How to add placeholder for search field in admin.py
How can I add placeholder in django for a search field I am using in admin.py with Django3.1 as: class MyAdmin(admin.ModelAdmin): list_display = ['community'] search_fields = ['community'] Is there any way to do something like this? class MyAdmin(admin.ModelAdmin): search_fields = ['community'] search_input_placeholder = 'Please input community id' -
Finding correlation in Django
I am working on a practice Django prooject. I have a small data frame with three columns Price, Sale, Reviews. I need to calculate correlation between all columns. User will see a Bootstrap form with select menu with three options Price, Sale, Reviews. If user selects Price it will calculate correlation with other two variables. here is my code Templates: <form action="/home/corelation/" method=post> {% csrf_token %} <div class="form-group"> <label for="variable">Voucher</label> <select name="variable" id="variable" class="form-control"> <option>Price</option> <option>Sale</option> <option>Reviews</option> </select> </div> <button type="submit" class="btn btn-success">Submit</button> </form> Views.py def corelation(request): if request.method == "POST": data = {'Price':[40, 50], 'Sale':[33, 27], 'Reviews':[25, 11]} df = pd.DataFrame(data) var_input = request.POST.get('variable') corr = df.corr() var_corr = corr['var_input'].sort_values(ascending = False) print(var_corr) Error Exception Type: KeyError Exception Value: 'var_input' -
django-cte leading zeros in query
How can I add leading zeros to an integer field in a Django query? I want to add an extra field in the Django query below with leading zeros add to the id. something like idwithzeros = str(id).zfill(6), but this is not working Example: Here I use django-cte (https://github.com/dimagi/django-cte): def ProjectTree(ProjectID): def get_tree(childs): return Project.objects.filter( # start with root nodes id = ProjectID ).values( "id", "parent", path=F("id"), depth=Value(0, output_field=IntegerField()), ).union( # recursive union: get descendants childs.join(Project, parent=childs.col.id).values( "id", "parent", path=Concat( childs.col.path, Value(";",output_field=TextField()) ,F("id"), output_field=TextField(), ), depth=childs.col.depth - Value(1, output_field=IntegerField()), ), all=True, ) childs = With.recursive(get_tree) return (childs.join(Project, id=childs.col.id) .with_cte(childs) .annotate( path=childs.col.path, depth=childs.col.depth, ) .order_by("path") ) -
'choices' must be an iterable containing (actual value, human readable name) tuples django 3.1
whene i want to makemigration it show me this error user.User.allowd_to_take_appointement: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. user.User.type_of_user: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. this is my models.py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class AllowdToTakeAppointement(models.TextChoices): YES = ('yes', 'Yes') NO = ('no', 'No') class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement, default=AllowdToTakeAppointement.YES) def is_doctor(self): return self.type_of_user == TypeOfUser.DOCTOR def can_add_appointment(self): return self.type_of_user == AllowdToTakeAppointement.YES i'm using django 3.1