Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing variable from HTML to Python file with Django
I am trying to have a user input their information in the HTML form and then send it to my Python app that is located in the root of the directory and then run the python program. Below is my code for views.py and my html form. How do I pass a variable from the HTML to my Python app and then execute the program? views.py def shopbotView(request): context = {} if request.method == 'POST': user_first_name = request.POST.get('user_first_name') user_last_name = request.POST.get('user_last_name') user_email = request.POST.get('user_email') user_phone = request.POST.get('user_phone') user_address = request.POST.get('user_address') user_zipcode = request.POST.get('user_zipcode') user_city = request.POST.get('user_city') return render(request, "index.html", context) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Flatbush Zombies Shop Bot</h1> <p class="lead">This is a bot written in Python that will shop <a href="https://thegloriousdead.com/">this</a> website for you. This website sells out of its products right away when they are released so this bot can purchase your desired items in an instant!</p> </div> </div> <div class="form"> <form action="#" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default">First name</span> </div> <input id="first_name" type="text" name="user_first_name" value="{{ user_first_name }}"> </div> <div class="input-group mb-3"> <div … -
Django - Class Based View for a specific item
Building a Django app where I have a view that displays a list of distinct case. When you click on a case, I'd like it to take you to a list of items related to the case (in this case it's a list of devices). The issue I am facing I don't know how to make the view display only the items related to that case (right now it displays every item in every case). Views: class MdeListView(LoginRequiredMixin, ListView): model = Mde template_name = 'mde/mde.html' ordering = [F('date').desc()] def get_queryset(self): return Mde.objects.distinct('case_number') class MdeCaseListView(LoginRequiredMixin, ListView): model = Mde template_name = 'mde/mde_case_list.html' urls.py from django.urls import path from .views import MdeListView, MdeCreateView, MdeCaseListView urlpatterns = [ path('<int:pk>/list', MdeCaseListView.as_view(), name='mde_case_list'), path('new', MdeCreateView.as_view(), name='mde_new'), path('', MdeListView.as_view(), name='mde'), ] The url goes to the right record based on the primary key, but from there I want only the items that use the same case_number as that primary key. -
sending notification/message to chosen users in Django
I am working on a part of a project that when I create a group for a project and once I submit the form (where I can pick certain users to be in the group in the form), the users who I selected in the form will receive any type of notification. The idea I am having now is when the selected users log in, their web pages will receive the notification that they are selected to the group. I have looked at Django's message frameworks however, it seems like they don't have the information that I am looking for. Can anyone please give me suggestion on where to start and what should I look at? -
How to import data from django.models, to use in javascript?
I am trying to import a python dictionary from moodels and manipulate/print it's properties in Javascript. However nothing seems to print out and I don't receive any error warnings. Views.py from chesssite.models import Chess_board import json def chess(request): board = Chess_board() data = json.dumps(board.rep) return render(request, 'home.html', {'board': data}) Here board.rep is a python dictionary {"0a":0, "0b":0, "0c":"K0"} - basically a chess board home.html <html> <body> {% block content %} <script> for (x in {{board}}) { document.write(x) } </script> {% endblock %} </body> </html> I also would very much appreciate some debugging tips! Thanks in advance, Alex -
Calling two views in third Django view
i have a little scraping script which i try transfer to django. My problem is i want call two views (which should return something) in third view but it is not working. Here are my views: def create_request(url): req = Request( url, data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) return req def get_request(req): return urlopen(req).read() def scraping(request): link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' data = request.POST.get("textfield") if data is None: return '' else: search = link + data + '&x=0&y=0' eleven = urllib.urlopen(search) soup = BeautifulSoup( get_request(create_request(eleven)), #here i got stuck features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) #here appears rest of code where i scrap some data Now i got stuck on the line when i define soup variable. In this line of code i use two earlier views: 'get_request' and 'create_request' but i am probably doing it wrong. I search for some directions but i didn't find anything and i have no idea how to implement it. How should i use that views to make this third view working good? -
Image is not uploading to the existing directory by Django model- ImageField(upload_to='')
I'm using Django 3. My Django model has an ImageField() as shown below: item_image = models.ImageField(upload_to='static/ims/images') The directory to which I want to save my image is already existing but still, it creates another file same as the mentioned location. Like so, static |__ims |___images |___**saved images** But, I want the image to save in the mentioned location which already exists (see below) static | |__ims | |__images | |___**images to be saved** |___style.css Can anyone help save my images to the pre-existent static directory? -
Error in loading two different pickle model in Django
I have a Django APP where in view.py I have included two different pickle model load as following: model = pickle.load(open(os.path.join(settings.STATIC_ROOT,'randomforest.sav'),"rb")) model2 = pickle.load(open(os.path.join(settings.STATIC_ROOT,'svm.sav'),"rb")) and then I set the two model as following: classification = model.predict(X_test) classification2 = model2.predict(X_test2) But now when I print the result of the prediction, the two classifier returns: 'from model 1' [1. 0.] 'from model 2' [1. 0.] even if SVM classifier should return just the classification as: [2] it seems that the second model (i.e., model2) doesn't be loaded or properly called. How may I do to solve that issue? Just to be clear: While using the same logic, for instance, in colab I obtain the following, correct, results: [[1. 0.]] [2] -
Where to make API call with Vue/Django project
I have a Vue project and have previously used Django as a backend API only to access a database, but I have a project now where I reach out to the Yelp API. This API doesn't allow client-side(JS) API access because of CORS. Does it make sense that I would have to make an API call from Vue to Django to pass user input and then another API call from Django to Yelp. This sounds like bad practice, but is there a better way to do this other than integrating a Django form to the page? -
Comments on Django Post won't save
I am trying to post comments to a post in Django, but my form is never valid. I have discovered that this is because my request.method is always a GET and not a POST. I would like to allow a user to add a new comment and have it automatically save to the database and display on my post's detail view. views.py def add_comment_to_post(request, pk): print("REQUEST METHOD", request.method) post = get_object_or_404(Post, pk=pk) if request.method == "POST": print("POST") print(request.POST) form = CommentForm(request.POST) if form.is_valid(): print("HREE") comment = form.save(commit=False) comment.author = request.user comment.date_posted = timezone.now() comment.post = post comment.save() return redirect('post_detail', pk=comment.post.pk) else: print("ELSE") form = CommentForm() # Note the indentation (this code will be executed both if NOT POST # and if form is not valid. return render(request, 'main/add_comment_to_post.html', {'form': form, 'post':post}) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['author', 'content'] models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') comment_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() class Meta: ordering = ['date_posted'] def __str__(self): return 'Comment {} by {}'.format(self.content, self.author.first_name) class Post(models.Model): run_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.TextField(max_length=100, blank=False, … -
login authentication in django
I want to use the authenticaton for custom user model in django. i just created the authentication for custom user model. but it's not validating the username and password. anyone help for that where i was mistaken the code. Here it is my views.py file : from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] post = User.objects.filter(username=username, password=password) user = authenticate(post) if user is not None: if user.is_active: login(request, user) if post and user: username = request.POST['username'] password = request.POST['password'] request.session['username'] = username request.session['username'] = password return redirect("profile") else: return render(request, 'login.html', {}) return render(request, 'login.html', {}) -
docker network not connecting my services together
I am having an issue with docker network not connecting my services together, I have a postgres image and a python image that need them to connect but at the moment when I call to connect to postgres service from python service my connection is denied. I have tried to open port 5432 and all host to see if I could get any connection but the same error would occur, tried using the service name to connect to it and the same issue continues to happen. anyone have any ideas why ? =========================================Django settings.py============================================== DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } ...... ALLOWED_HOSTS = ['*'] ========================================Error========================================================== ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1 Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: No address associated with hostname The above exception was the direct cause of the … -
How to request a filtered viewset in django restframwork
I need to retrieve a filtered set of data by calling an HTTP request using Django rest framework. here are my API codes: urls.py urlpatterns = [ path('api/get_products/', views.get_products), ] Views.py @api_view(["GET", ]) def get_products(request): category_name = request.data['category_name'] category_obj = Category.objects.get(name=category_name) products_list = Product.objects.filter(category=category_obj) serializer = ProductSerializers(products_list) return Response(serializer.data) and finally the serialierz.py class CategorySerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ['name', 'id'] class ProductSerializers(serializers.HyperlinkedModelSerializer): category = CategorySerializers() class Meta: model = Product fields = '__all__' and am trying to call it using a get request with the argument: {'category_name':'the_name_of_the_category' } and it returns this error: KeyError at /categories/api/api/get_products/ 'category_name' -
Django TypeError/ in views.py (expected str, bytes or os.PathLike object, not list)
following this youtube tutorial: https://www.youtube.com/watch?v=psvU4zwO3Ao . Which builds a template on Django server. Pretty confident I followed it precisely, however receiving this error in views.py which is based in the app directory. Code in Views.py in app directory: from django.shortcuts import render def home(requests): return render(requests, 'home/welcome.html') Traceback (most recent call last): File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\Users\popec\PycharmProjects\djangoproject\mysite\home\views.py", line 5, in home return render(requests, 'home/welcome.html') File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\ntpath.py", line 78, in join path = os.fspath(path) Exception Type: TypeError at / Exception Value: expected str, bytes or … -
PPT view on Website By Using Django Framework
How to view PPT files on the website using Django Framework? Please share the code on how to do it by using the Django Framework. Sorry, I don't have any examples of what I am looking for. -
React JS render the element to the Dom of only one html page in my Django app
I have a Django app with frontend in ReactJS.. In which I have two html files and one App.js with two classes.. My Issues is that React executes in the App.js only the first render line segment , and didn't render the element in the second line to the other html page?! It only renders two elements if i have the two id`s in the same html file! how to solve this ?! first html page: index.html {% extends 'base.html' %} {% block content %} <div id='app'></div> {% endblock %} second html page: arabic_home.html {% extends 'base.html' %} {% block content %} <div id='app_arabic'></div> {% endblock %} The App.js: ReactDOM.render(<App />, document.getElementById('app')); {/* it only executes the first line */} ReactDOM.render(<App_arabic />, document.getElementById('app_arabic')); -
Permissions to edit certain fields in Django
I have two different groups who are allowed to access Django-Admin. They are allowed to view all Fields in a Model, but shall not edit all Field. For example G1 is allowed to edit "price" and "ean" whilst G2 is allowed to edit "ean" and "detail". I tried the version given here, but I also want to restrict the editability in the detail view of a model object. -
Nextjs or Gatsby, what is the need for e-commerce single site web application?
I want to make a Single Site Application which is an e-commerce application. For this I want use Django, Django Rest for API endpoints as backend. And for frontend I want to use React, Redux, Axios, React-Router, Antd. So for professionally deploy this app, what is need of Nextjs or Gatsby? I want to scale my application for million users. Please help & Thanks. -
How to filter one filed using multiple values in ListAPIView?
How to filter one filed using multiple values in ListAPIView? URL: /api/items/?status=active&status=pending I need to get results that have both active and pending status. What filter_backends will be good for my case? -
Django Admin - Cancel other select fields when selecting one
I'm writting an app on Django. On a model, let's admit we have this : Class MyModel(models.Model): A=models.ForeignKey(A, null=True, on_delete=models.SET_NULL) B=models.ForeignKey(B, null=True, on_delete=models.SET_NULL) C=models.ForeignKey(C, null=True, on_delete=models.SET_NULL) In the django administration, it will create select fields to choose options. And i'd like that when we select an option in a field, it resets the other ones. So in the end, it would be an OR condition between the select fields.. In javascript/jquery, it would be quite easy to do so, but do you think it can be done from django (inside the model..) ? Thank you very much for your replies and ideas -
updating data from another app in django rest framework
I have two apps named requisition and inventory. Now I want update Inventory according to requisition approval. When requisition will approve for a particular Item, then Inventory will increase for that item. how can I solve this problem? Here is my requisition app's model: class Requisition(models.Model): item_name = models.CharField(max_length = 255 ) ammount = models.IntegerField() status = models.IntegerField() class RequisitionSerializer(serializers.ModelSerializer): class Meta: model = Item_One fields = ['item_name', 'ammount', 'status'] and my Inventory app's model is: class Inventory(models.Model): item_name = models.ForeignKey(Requisition, on_delete=models.CASCADE) balance = models.IntegerField() class InventorySerializer(serializers.ModelSerializer): class Meta: model = Item_One fields = ['item_name', 'balance'] If we set status=1 in Requisition class, then balance in the Inventory class will be increase for this Item. I am using function based view for this project. -
Django Compute the average per Grading Categories
I had created my table inside my views.py, I just want to compute the average Per Grading Categories (please see the image of admin Site), This is my data in admin Site studentsgrade = studentsEnrolledSubjectsGrade.objects.filter( Teacher__in=teacher.values('Subjects')).distinct('Grading_Categories').order_by('Grading_Categories') gradingcategories = gradingCategories.objects.filter( id__in=studentsgrade.values_list('Grading_Categories')).distinct().order_by('id') print("gradingcategories",gradingcategories) gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories') print("gradepercategory",gradepercategory) count_id = studentsEnrolledSubjectsGrade.objects.filter( Grading_Categories__in=cate.values_list('id')).filter( grading_Period__in=period.values_list('id')).order_by( 'id').filter(Students_Enrollment_Records__in = studentenrolledsubject.values_list('id', flat=True)).count() this is the result of print("gradingcategories",gradingcategories) and print("gradepercategory",gradepercategory) gradingcategories <QuerySet [<gradingCategories: Quiz>, <gradingCategories: Homework>]> gradepercategory <QuerySet [<studentsEnrolledSubjectsGrade: Mary M Burabod>, <studentsEnrolledSubjectsGrade: Mary M Burabod>]> when i tried this to my gradepercategory gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories').aggregate(Sum('Grade'))['Grade__sum'] i get this error error This is how i create my table students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter( Grading_Categories__in=cate.values_list('id')).filter( GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial','Grading_Categories', 'Grade').distinct() teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values_list('CategoryName', flat=True))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = """Result of average per grading perion""" table.append(table_row) … -
Filter in Django having multiple categories
All I want do is filter Product on the basis of list shown in photo. In woman category there should be 12 main category as mentioned down in photo. Now every sub category also have sub category. I have no clue about how to do it. Please suggest how I can do it for my project. If possible explain in details.enter image description here -
Celery Task Worker Refresh
I've got a pretty basic task configuration. The problem I have, however, is I have a variable that is being updated every hour. This variable is an auth_token for an API. If the auth_token is expired the task errors because it can't connect to the API. If I attempt to process records just after the auth_token has been refreshed, the task errors out stating that my auth_token is expired. But then if I restart the worker, the task works as designed using the new auth_token. I've been scouring Celery documentation looking for some configuration I can add to my task that would force it to clear it's cache after it processes refresh_access_token task, but can't find anything. Any help would be much appreciated! serializer.py # List Create View class LedgerAPIView(generics.ListCreateAPIView): queryset = Ledger.objects.all() serializer_class = LedgerSerializer permission_classes = [IsAdminUser] authentication_classes = [TokenAuthentication, SessionAuthentication] pagination_class = PageNumberPagination def perform_create(self, serializer): """ Posting to the API requires that a user have an auth_token and be classified as an active_user. """ serializer.save() # Create ProcessRecord Object ledger_object = Ledger.objects.get(id=serializer.instance.id) record = ProcessedRecords(payment_allocation_name=ledger_object) try: record.save() except Exception as exc: formatted = "Cannot update ProcessedRecords Table! ERROR --> {}".format( repr(exc)) raise Exception(formatted) # Start Celery … -
Saving ManyToMany data in Django 3
I'm trying to save data in django with ManyToMany fields via django-bootstrap-modal-forms package for modal forms with no success. I tried overriding the save method but kwargs['instance'] always return an empty dict of the ManyToMany field ('suppliers'): {'name': 'product_1', 'all_suppliers': <QuerySet []>, 'suppliers': <QuerySet []>} What I'm trying to achieve is updating the suppliers for a product and/or updating products from a supplier Totally new to Django so please excuse the bad programming style Could you please help me. Thanks! Here is my code: models.py # models.py class Product(models.Model): name = models.CharField(unique=True, max_length=100) active = models.BooleanField(default=True) def __str__(self): return self.name class Supplier(models.Model): name = models.CharField(unique=True, max_length=100) supplier_products = models.ManyToManyField(Product) def __str__(self): return self.name views.py # views.py class ProductUpdateView(BSModalUpdateView): model = Product template_name = 'product/product_update.html' form_class = ProductForm success_url = reverse_lazy('product_list_view') class SupplierUpdateView(BSModalUpdateView): model = Supplier template_name = 'product/supplier_update.html' form_class = ProductForm success_url = reverse_lazy('supplier_list_view') forms.py # forms.py class ProductForm(BSModalForm): all_suppliers = forms.ModelMultipleChoiceField(queryset=Supplier.objects.all(),required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance'): suppliers = kwargs['instance'].supplier_set.all() print(type(kwargs['instance'])) self.fields['suppliers'] = forms.ModelMultipleChoiceField(required=False, queryset=suppliers) class Meta: model = Product fields = ['name', 'notes'] fields.append('all_suppliers') -
How to use validators in django
from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_subject(value): if value.isalnum(): raise ValidationError(_('%(value)s is not valid. Please use alphanumneric characters as subject names'), params={'value': value},) class Exam(models.Model): #Exam can have many questions subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject]) #make it to reject a string of length 0 def __str__(self): return self.subject I want this code to raise an error when I keyed the following from my_app.models import Exam exam = Exam() exam.subject = "" exam.save() Why Iam not getting an error?