Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query for many to many relationship to find a user
this is my model: class Student(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) frist_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) father_name = models.CharField(max_length=250) national_code = models.CharField(max_length=12) date_of_birth = models.DateField() phone_regex = RegexValidator(regex=r'(\+98|0)?9\d{9}', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.",) phone_number = models.CharField(validators=[phone_regex], max_length=13, blank=True,help_text='Do like +98913.......') # validators should be a list CHOICES = ( ('male','Male'), ('female','Female') ) gender = models.CharField(choices=CHOICES,max_length=6) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return (self.frist_name) class Classes(models.Model): book = models.CharField(max_length=250) grade = models.CharField(max_length=250) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) student = models.ManyToManyField(Student,related_name='student') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.grade how can i make query to find a user book and grade for a specific student? like : the frist name is mohammad and last name is kavosi and username is 0605605605 i want to find the grade and book of this user is my model True or not? -
Serializers validation - TypeError... 'UniqueTogetherValidator' object is not iterable
I have a model called 'following' where one user can follow another, using the Django rest framework. I am trying to implement a validation so that you can't follow someone twice, and trying the built-in UniqueTogetherValidator. Here are the relevant parts of my models.py class Following(models.Model): user = models.ForeignKey('User', related_name='user', on_delete=models.CASCADE) follower = models.ForeignKey('User', related_name='follower', on_delete=models.CASCADE) And serializers.py: class FollowingSerializer(serializers.HyperlinkedModelSerializer): user = serializers.CharField(source='user.username') follower = serializers.CharField(source='follower.username') class Meta: model = Following fields = ['user', 'follower'] validators = UniqueTogetherValidator( queryset = Following.objects.all(), fields = ['user', 'follower'], message = "You are already following that person!" ) I have some existing data: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 2, "next": null, "previous": null, "results": [ { "user": "mike", "follower": "chelsea" }, { "user": "mike", "follower": "chloe" } ] } When I try to add any new following object using the API interface, I get this error: TypeError at /followings/ 'UniqueTogetherValidator' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/followings/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: 'UniqueTogetherValidator' object is not iterable ... Where did I go wrong? Thanks in advance! -
Filtering in Django ModelViewSet
I don't think I'm doing this correctly. What I'm trying to do is prevent data from being returned if it doesn't match my criteria. Here are the criteria: User should be able to see the project if: If the object is private and they are the owner -- OR -- The project is not private If the user is the owner, or they are a member of the assigned group As far as I can tell, it's not getting the data into the is_private and owner variables I set. Every tutorial I read online though seems to do it in this way. So I'm pretty lost right now. class ProjectListViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by('name') serializer_class = ProjectLightSerializer authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] def get_queryset(self): queryset = super().get_queryset() is_private = self.request.data.get('is_private') owner = self.request.data.get('owner') print(is_private) print(owner) if is_private: if owner == self.request.user.id: queryset = queryset.filter(owner__exact=self.request.user) else: if owner == self.request.user.id: queryset = queryset.filter(owner__exact=self.request.user) else: queryset = queryset.filter(groups__in=self.request.user.groups.all()) return queryset Any assistance would be greatly appreciated. Thanks in advance. -
How to work with external API from Django admin
I have a problem to solve with Django. I need in some way from the admin area to be able to use an external API to do some HTTP requests, GET and POST. I'm not sure how a good approach would be to solve this. I have only handled this on the frontend before. I should be able to get a list of orders from the API, update an order, get a specific order with details, post a new order etc. I'm thinking such as when you register a model and then registering it with ModelAdmin, would that be possible to use the API to load it in similar way there and handle the API? Should I store the API data in a model to a database? Should I create create a custom made Django admin page? Other ideas? -
Error during template rendering: 'ManyToOneRel' object has no attribute 'attname'
I try to render a form in html but I raise an error and I have got no idea about its trigger. Here is the traceback error: Template error: In template /Users/usr/Projets/your-query-master/src/core/templates/core/base.html, error at line 18 'ManyToOneRel' object has no attribute 'attname' 8 : 9 : <title>{% block title %} Your-Query {% endblock title %}</title> 10 : <!-- Latest compiled and minified CSS --> 11 : <link rel="stylesheet" href='{% static "css/base.css" %}'> 12 : <link rel="stylesheet" href='{% static "css/bootstrap.min.css" %}'> 13 : <link rel="stylesheet" href='{% static "css/bootstrap-theme.min.css" %}'> 14 : <link rel="stylesheet" href='{% static "css/contest.css" %}'> 15 : 16 : <script src="{% static 'contest_bet.js' %}"></script> 17 : 18 : <link rel="styleshee t" href="htt ps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 19 : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> 20 : </head> 21 : <body> 22 : {% include "core/navbar.html" %} 23 : <div class="container" style="padding-top: 80px;" > 24 : {% block content %} 25 : 26 : {% endblock content %} 27 : </div> 28 : {% include "core/footer.html" %} Traceback (most recent call last): File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Djoser return access and refresh token when registering user
I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint. I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows: { "mobile": "12345", "driving_id": "478161839", "full_name": "John Doe", } This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
Cannot query "": Must be "" instance
I am pretty new to django as well as python, in my app i have two models one is MyProfile and One is MyPost, users will have a profile and users can create a post, it's all working but i wanted to show posts created by a user in their profiles. for that i tried creating a get_context_data inside my generic Detailview. But it gives me this error Cannot query "ahmy": Must be "MyProfile" instance. ahmy is my logged in username. My models from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.core.validators import MinValueValidator, RegexValidator # Create your models here. class MyProfile(models.Model): name = models.CharField(max_length = 500) user = models.OneToOneField(to=User, on_delete=CASCADE) address = models.TextField(null=True, blank=True) gender = models.CharField(max_length=20, default="Male", choices=(("Male", 'Male'), ("Female", "Female"), ("LGBTQ", "LGBTQ"))) phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")], max_length=15, null=True, blank=True) description = models.CharField(max_length = 240, null=True, blank=True) pic = models.ImageField(upload_to = "image\\", null=True) def __str__(self): return "%s" % self.user class MyPost(models.Model): main_pic = models.ImageField(upload_to = "image\\", null=True) amount_spend = models.IntegerField(null=True, blank=True) total_donars = models.IntegerField(null=True, blank=True) title = models.CharField(max_length = 200) body = models.TextField(null=False, blank=False) cr_date = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True) def __str__(self): return "%s" % self.title My View @method_decorator(login_required, name="dispatch") class … -
How to insert a django user's username in the path via a view?
I am a naive Django user. I have implemented a sign-in functionality with the Django user model. Here's my project's urls.py file: from django.contrib import admin from django.urls import path,include from django.conf.urls import url from signin import views as viewsignin urlpatterns = [ path('',include('signin.urls')), path('dashboard/',include('dashboard.urls')), path('admin/', admin.site.urls), ] Here's my dashboard app's urls.py, which gives a path to the dashboard view once a user logs in. from django.urls import path from . import views urlpatterns = [ path('dashboard/',views.dashboard,name='dashboard'), ] Here's a snippet of views.py of my signin app: def signin(request): message={} if request.method=='POST': user =authenticate(username=request.POST['email'],password=request.POST['pwd']) print(user,request.POST['email'],request.POST['pwd']) if user: print("User exists") if user.is_active: login(request, user) USER = User.objects.get(email=request.POST['email']) return redirect('dashboard)#I HAVE A PROBLEM HERE else: message['cred_err']=True return render(request,'signin/signin.html',context=message) What I want is that when signing in is successful, the path of dashboard shows the username of the user who logged in. Please help! -
Amazon SNS topic,subscription and geo-localized push notifications management for mobile devices
I have one Django application with some REST-services. I store mobile devices geo-location and I have to send a push notification (the same push notification) to all devices that they are into a specific location (with a certain radius). I'm using AWS-SNS service and I already registered the mobile on SNS. I would like to not use some asynchronous architectures (for example Celery) to retrieve all devices, that they are into the location to send, for each of these, the push notification (one request to SNS for each device). For example, I'm searching for a way to register all retrieved devices on a topic-subscription in bulk and, after this, on request to send the push notification to all devices that they are registered to this topic. My goal (best case) can be: Retrieve all devices by geo-location; Create an SNS topic dedicated for this request; One request to store in bulk these devices for this topic; One request to send the push notification for this topic; This is a possible approach for example. I would like to reduce the request to SNS and I would like to not use (for example) Celery to create different async steps for this. Is … -
TypeError: create_superuser() missing 1 required positional argument: 'username' -- unable to create super, i hashed out the lines with the error
Non-interactive mode. if username is None: raise CommandError('You must use --%s with --noinput.' % self.UserModel.USERNAME_FIELD) else: error_msg = self._validate_username(username, verbose_field_name, database) if error_msg: raise CommandError(error_msg) user_data[self.UserModel.USERNAME_FIELD] = username for field_name in self.UserModel.REQUIRED_FIELDS: if options[field_name]: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(options[field_name], None) else: raise CommandError('You must use --%s with --noinput.' % field_name) ##### self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)###### if options['verbosity'] >= 1: self.stdout.write("Superuser created successfully.") except KeyboardInterrupt: self.stderr.write('\nOperation cancelled.') sys.exit(1) except exceptions.ValidationError as e: raise CommandError('; '.join(e.messages)) except NotRunningInTTYException: self.stdout.write( 'Superuser creation skipped due to not running in a TTY. ' 'You can run `manage.py createsuperuser` in your project ' 'to create one manually.' ) on the line that i hashed out I'm running into a typeError and its telling me i need to pass 'username' through 'create_superuser'. Ive tried it and i still get the error when making my super user. all 'username' are defined in my models.py folder for the project. has anyone else run into this error with django? -
How to change header/page title of User Add Page in Django admin
I'm working on Django.And I wanted to change the header in the User Add Page in the Django admin as marked with red color in the pic : admin.py file is : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So how to change the header of User Add page?? Thanks in advance!! -
Changing the default authentication message in django-rest-framework
In a simple TokenAuthentication system in Django Rest Framework, the default message when you fail to send a proper authorization token is this { "detail": "Authentication credentials were not provided." } I want all my API responses to follow a certain template e.g. { success, message, data } How can I overwrite this error message? What is the best practice when creating these API templates? P.S. I checked out other questions but couldn't find anyone with a similar problem. If it was already answered I'd be glad if you could point me to it. -
How can I read a dicctionary in template in Django
Hi I'm trying to read a dicctionary in a template in django, but I would like to separate the keys and the value, the key is what will be showed, and the value is the next url it has to go (I know that diccionary is a little bit strage but I think that's not a problem. Here is my code if anyone can help me. <ul> {% for i in respuestas %} <li><a href="/{{'respuestas.[i]'}}"><h2>{{i}}</h2></a></li> {% endfor %} </ul> That's the idea. Obviously it doesn't work because I'm asking here so, anyone know how can I do it?? Thank you!!!! -
DJANGO-User switch account issue
I noticed that when I am logged in as my profile (http://127.0.0.1:8000/user/admin/ ) and I go to my template where I have the list of all users ( http://127.0.0.1:8000/users/ ) and I click on another user(mattia_mibe) to see his/her profile it switched my account, so I don't see his/her profile but I see my profile (admin) with all my descriptions but at the same time the url is http://127.0.0.1:8000/user/mattia_mibe/ and it recognize @mattia_mibe as users, even what it displays is my profile's descriptions(admin). It's a bit complicated to explain, I post here some pictures in the case I did not explain the issue clearly. core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.homepage, name='homepage'), path("users/", views.UserList.as_view(), name='user_list'), path("user/<username>/", views.userProfileView, name='user_profile'), ] core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView # Create your views here. from quiz.models import Questions from jobs.models import post_job def homepage(request): return render(request, 'core/homepage.html') def userProfileView(request, username): user= get_object_or_404(User, username=username) jobs = post_job.objects.all() categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= request.user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores), 'jobs': jobs } … -
Trying to insert file into sql light using django
I am trying to do following to update record with file in sql light. This is function i am using to update record from django.db import connection def execute_query_2(query, data): with connection.cursor() as cursor: cursor.execute(query, data) rows = cursor.fetchall() return rows with open("test.text", "rb") as f: data = f.read() query = myquery execute_query_2(query, (str_date, file, id)) my query is as follows: UPDATE mytable SET str_date = ? and file_data = ? WHERE id = ? however, I am getting following error TypeError: not all arguments converted during string formatting Any idea how to fix it? -
why does date time function don't need migration when I set it to default?
In Django when I set my date/time to default default=datetime.now() It automatically migrated in models.py. Why I do not need to do migration for it? -
How to change button text onclick using django?
I'm working on a school project and I'm trying to change a button's innerHTML to a value I got from a dictionary in views.py. However, when I load the page with this code: <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; document.getElementById("klik").submit(); var id = this.getAttribute('id'); var novi = document.createElement('BUTTON'); novi.type = 'button'; //alert("This object's ID attribute is set to \"" + id + "\".") novi.value = id; novi.innerHTML = {{vrijednost}}; this.parentElement.replaceChild(novi,this); }; elem.innerHTML = elem.value; docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } </script> Nothing happens. The page is blank. When I change novi.innerHTML to something else, 'x' for example, the x appears for a very short time and then it disappears. Now, I think that every time I click on a button, I go to a an url named 'klik' from the form, but I don't know how to fix it. Any ideas? This is a part of my views.py code: def klik(request): ID = request.POST['ID'] print(ID) vr = r[ID] … -
Django 3. Send email with attachment file
I have a simple contact form on my Django 3 project. It's working fine and I have got masseges, but how can I make a function to the attachment file to my mail? I have FileField and some code in views.py, but its doesn't work. Any ideas? Versions: Python 3.6.5. Django 3.0.5. forms.py class ContactForm(forms.Form): name = forms.CharField(required=False, max_length=150, help_text="Name") email = forms.CharField(required=False, max_length=150, help_text="Email") file = forms.FileField(widget=forms.FileInput, required=False) message = forms.CharField(widget=forms.Textarea, help_text="Text area") views.py @csrf_exempt def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] sender_file = form.cleaned_data['file'] message = "{0} New massege:\n\n{1}\n\n{2}\n\n{3}".format(sender_name, sender_email, form.cleaned_data['message'], sender_file,) send_mail('Subject', message, sender_email, ['to.my.mail@gmail.com']) return render(request, 'pages/thank-you.html') else: form = ContactForm() return render(request, 'flatpages/report.html', {'form': form}) HTML. <div class="col-12 col-md-6"> <div class="report"> <h3 class="report-title">Ваші дані</h3> <form method="post" action="/pro-upravlinnya/report/"> <div style="display:none"> <input type="hidden" name="csrfmiddlewaretoken" value="$csrf_token"/> </div> <div class="report-control"> {{ form.name.help_text }} {{ form.name }} </div> <div class="report-control"> {{ form.email.help_text }} {{ form.email }} </div> {{ form.file }} <div class="report-control"> {{ form.message.help_text }} {{ form.message }} </div> <div class="report-btn-wrp"> <button type="submit" class="report-submit" >Send</button> </div> </form> </div> </div> Output to my email: subject, name, email, text, None -
How to add custom CSS properties like font-size to all the Django admin pages?
I'm working on Django.And I want to add custom CSS properties like font-size to all the Django admin pages like User change page, User add page,etc in one go so that I don't have to put different different CSS properties for each and every pages individually. So is there any way to do that?? Thanks in advance!! -
Firebase and Django API
I'm want to start coding web platform(and perhaps later also make a mobile app for iOS and Android) and I recently started considering using Firebase. I really want to use its auth system, database system, and file storage system. I'm not really good at DevOps and I feel like Firebase can really make my life better. I want to use Django to create API and React with Next.js for frontend. API will have to do a few things with data, manage user's access, and their possible actions. I'm confused after all I've read on the internet about Firebase. 1. My frontend and backend have to be hosted somewhere else or can I host them on Firebase. 2. Is it even possible to create a fully working API that uses Firebase systems? Would such a thing be efficient? And how could I do that? And the most important question: Is using Firebase like that expensive? Will I not overpay? Maybe some of you have actual commercial experience with Firebase. -
django: header drop down menu with language selection
I am trying to include a language selector in my website header but the structure of it is giving me hard time. I am a beginner in web development and I cannot figure out how to pass my django form into this drop down button in the header. Here is what I have been able to do on my own so far: html <form id= "#language" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input type="hidden" name="text" value="{{ redirect_to }}"> <select name="language" id=""> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %} > {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <button></button> {# <button> type="submit" value="Go">#} </form> </div> </div> <div class="nav-link dropdown"> <a class="nav-link dropdown" id="#language" href="" data-toggle="dropdown">LANGUAGE</a> <div class="dropdown-menu" aria-labelledby="language"> <a class="dropdown-item" href="">ENGLISH</a> <a class="dropdown-item" href="">FRENCH</a> </div> </div> the form only contains two languages and as you can see I don't know how to have the two choices inside of the language header dropdown button. Would anyone has a clue that could help me out? -
How to log in to Django with model class User
i am newbie in Django and DRF. I created object of User class(which is in models.py) and i want with THAT user log in to django. In a nutshell, create django user with model User class. How can i implement it? models.py class User(models.Model): username = models.CharField(max_length=20, unique=True) #login field in Angular password = models.CharField(max_length=30) first_name = models.CharField(max_length=30) # name field in Angular last_name = models.CharField(max_length=30) email = models.EmailField( unique=True, max_length=254, ) views.py class UserCreateAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] SerializerClass class UserSerializer(serializers.ModelSerializer): username = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = User fields = '__all__' -
how to get exact object in django rest framework using class based view?
i am trying to create comment for every single post from flutter front end but i dont know how to provide the exact post i wanted t comment django:2.2 models.py class Comment(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,editable=False) author = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='comments') post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_content = models.TextField(max_length=400) commented_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to=random_url,blank=True,null=True) parent = models.ForeignKey('self',null=True,blank=True,on_delete=models.CASCADE,related_name='replies') active = models.BooleanField(default=True) this is the serializers.py class CommentCreateSerialzier(ModelSerializer): class Meta: model = Comment fields = [ 'comment_content','image' ] and this is my views.py class CommentCreateSerializer(CreateAPIView): serializer_class = CommentCreateSerialzier message = 'you dont have permission to comment' permission_classes = [IsAuthenticated] def perform_create(self): serializer.save(author=self.request.user) how to add default post object in every single post ? and does it the same for replies as well thanks for replying -
How to get the data from database between the input dates in Django
I have two attributes in my database fromDate = models.CharField(max_length=100) toDate = models.CharField(max_length=100) By taking user input as <input type="date" name="fromDate"> <input type="date" name="toDate"> I want to get all the data from database between this two dates. -
How to do custom validation in my Django Modelform?
I have a ModelForm for this model, with this unique_together: class Registration(models.Model): student_name = models.CharField(max_length=50) selected_season = models.CharField(max_length=2) selected_subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student_address = models.TextField() student_phone = models.CharField(max_length=11) class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) The modelform is like this: class RegistrationForm(forms.ModelForm): student_address = forms.CharField(label='', widget=forms.Textarea(attrs={'class':'materialize-textarea'})) class Meta: model = Registration fields = '__all__' How do I raise a validation error if the unique_together requirement is not met?