Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest - @pytest.mark.parametrize() how to use when changes in one field in post request
I'm really sorry but i dont know how to describe my problem in one line so please change if its wrong. so the problem is i'm using unit test in my drf test cases and there are two test cases such as def test_with_blank_addressstate(self): # view = order_list, method = POST # user = Normal # Country = IN, state = "" self.client.login( username=self.order.owner.username, password="normal" ) url = reverse("order_list") self.order["addressstate"] = "" response = self.client.post(url, self.order, format="json") self.assertIn( "{'addressstate': [ErrorDetail(string='This field is required.'", response.data["error"]["description"], ) def test_with_incorrect_addressstate(self): # view = order_list, method = POST # user = Normal # Country = IN, state = GJJ(Incorrect) self.client.login( username=self.order.owner.username, password="normal" ) url = reverse("order_list") self.order["addressstate"] = "SRJ" response = self.client.post(url, self.order, format="json") self.assertIn( "{'addressstate': [ErrorDetail(string='This field is required.'", response.data["error"]["description"], ) both test cases i perfectly fine. but my test cases are increasing, i want to test every field for different-different data. for the above test cases if i want to create only one test case and only want to change the field addressstate every time in post request so i can test it different-different data. i never used pytest only know the basic.but i think i can do this using pytest. can … -
Django Unique Constraint Specific Field
I have a A model which uses model B and C as ForeignKeys. In A model, I want to create a constraint that lets saving only if model B and 'xyz' field in C model are unique. When I do it as follows, it did not work. How can I achieve this? class A(models.Model):: B = models.ForeignKey("B", on_delete=models.CASCADE) C = models.ForeignKey("C", on_delete=models.CASCADE) class Meta: unique_together = [ ('B' , 'C.xyz') ] -
An exception is being raised when testing websocket with POSTMAN
I am implementing web sockets in my Django Project with channels library. When an object is created, name of that object should be sent to a consumer with group name test_consumer_group_1. class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is the code of my consumer: class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") print(event) But it gives following error when testing the websocket API with POSTMAN: raise TypeError(self.invalid_name_error.format("Group", name)) TypeError: Group name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not specific.be2251de4bb647c1988845bd460d6971!564c92a792634237bcdba63290554557 WebSocket DISCONNECT /ws/test/ [127.0.0.1:35480] How to fix it? -
How to pass request field into Django test?
I have a function: def test_function(request): return request.device.id which connected to endpoint /test_end/ I need to write a unittest but not working -> request.device is None Test looks like this: from django.test import TestCase from django.test.client import Client class Device: def __int__(self, _id): self.id = _id class MyTest(TestCase): def test_device(self): client = Client() response = client.get("/test_end", device=Device(42)) How to fix it? I need to pass device to function into request -
django Sitemap class alternates not rendering sitemap.xml
I have a problem with adding alternates attribute to my sitemaps.py sitemaps.py class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'weekly' protocol = 'https' i18n = True alternates = True def alternate_hreflangs(self, obj): return [('en-us', obj.alternative_object_url), ] def items(self): return ['index','about', 'contact', 'why', 'product', 'tender-management', 'e-sourcing', 'network', 'faq'] def location(self, item): return reverse(item) when I set the alternates = True my sitemap.xml file broke and show a string file https://example.com/en/weekly0.5https://example.com/en/about/weekly0.5https://example.com/en/contact/weekly0.5 Instead of <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.com/en/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://example.com/en/about/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://example.com/en/contact/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> I get this problem only when adding the alternates = True my sitemap.xml -
How to check Django Form Submission Against Value in Database Table
I am trying to create a function in my views.py that checks a users date submission against values already submitted to the database: def make_booking(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): new_date = form.cleaned_data.get("date_of_booking") existing_booking = Booking.objects.get('date_of_booking').items() for booking in existing_booking: if booking == new_date: messages.success(request, "THIS DATE IS ALREADY TAKEN") else: form.save() print('form saved') if request.user.is_authenticated: return redirect(get_bookings) if not request.user.is_authenticated: return redirect(get_bookings_guest) If the date already exists in the database then I want it to show a message saying the date already exists. I have written the above which seems correct to me but I get this error: "Exception Value: too many values to unpack (expected 2)". Please could someone help me? -
Filter a Django table with multiple entries for each user and get the latest one
I have this model: class UserStatus(models.Model): """ This model builds the user status model. """ user = models.ForeignKey(MyUser, on_delete=SET_NULL, null=True) rest_mode = models.BooleanField(default=False) tags = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) How can get the latest entry for each user, then get only the ones with rest_mode == True? -
Access Model attribute depending on URL parameter in Django
Is it possible to dinamically change a variable name in template? In the view below I am sending to the template an url parameter called sl. is it possible to pass that sl to the {{ devize.sl{{sl}} }} so that it changes dinamicaly ? thank you @login_required def slList(request,centrudecost,SL): queryset = Deviz.objects.filter(centrudecost_id=centrudecost) sl = SL print(centrudecost) return render(request, "proiecte/sl_list.html", {"queryset": queryset,"sl":sl}) {% for devize in queryset %} <td>{{ devize.sl{{sl}} }}</td> {% endfor %} -
Building own SIEM system on django
I am currently working on own siem system, where windows logs(in csv format) automatically collecting every hour and displaying in a Highcharts. The backend is Django. But ran into problems: There's too many data that GPU of browser is load. I set auto parsing to per 1 hour but site not displaying. Other parts of code are working Is it ok if I write logs in database? Can anyone give me advices how to do it right? Here is my Javascript code in template/dashboard _categories = {{categories|safe}}; _values = {{values|safe}}; _data = {{data|safe}}; Highcharts.chart('pie', { colors: ['#558dfa', '#a1c1fe', '#4c72bc', '#3a61ad'], title: { text: '' }, chart: { type: 'pie' }, tooltip: { valueSuffix: '%' }, plotOptions: { pie: { allowPointSelect: false, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: false } }, series: [{ name: 'Percentage', colorByPoint: true, data: [ { name: 'Critical', y: {{range.0}} }, { name: 'Error', y: {{range.1}} }, { name: 'Information', y: {{range.2}} }, { name: 'Warning', y: {{range.3}} }, ] }] }); Highcharts.stockChart('container', { chart: { alignTicks: false }, rangeSelector: { selected: 0 }, series: [{ type: 'column', data: _data, }], dataGrouping: { units: [[ 'week', // unit name [1] // allowed multiples ], [ … -
Django Rest Framework different image size for different account tiers (Basic, Premium)
There are three bultin account tiers: Basic, Premium and Enterprise: Users that have "Basic" plan after uploading an image get: a link to a thumbnail that's 200px in height Users that have "Premium" plan get: a link to a thumbnail that's 200px in height a link to a thumbnail that's 400px in height a link to the originally uploaded image models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image def user_directory_path(instance, filename): return 'images/{0}'.format(filename) class Images(models.Model): title = models.CharField(max_length=250) image = models.ImageField(upload_to=user_directory_path) created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='author') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) class Profile(models.Model): MEMBERSHIP = ( ('BASIC', 'Basic'), ('PREMIUM', 'Premium'), ('ENTERPRISE', 'Enterprise') ) user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.CharField(max_length=10, choices=MEMBERSHIP, default='BASIC') def __str__(self): return f'{self.user.username} {self.membership} Profile' serializers.py from rest_framework import serializers from blog.models import Images, Profile class ImagesSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ('author', 'title', 'image') views.py class ImagesViewSet(viewsets.ModelViewSet): queryset = Images.objects.all() serializer_class = ImagesSerializer def get_queryset(self): user = self.request.user return Images.objects.filter(author=user) -
import dm.xmlsec.binding as xmlsec, dm`Module not found :
I am working on django project. I am running this project on a venv using the command : "python manage.py runserver". But getting the error "import dm.xmlsec.binding as xmlsec, modulenotfounderror "dm" ". I have tried installing the module using pip install dm in the venv but still not able to bypass this error. Sharing the screenshot of the same. enter image description here Any help is appreciated. -
Why does nginx not redirect to https?
I'm trying to deploy my Django application but I'm having issues with the redirect to https added in my nginx config by Certbot. This is what my config looks like: server { server_name somedomain.com; location /static/ { root /var/www/somedomain; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/somedomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/somedomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = somedomain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name somedomain.com; return 404; # managed by Certbot } With https the site works fine, but for http there is no response: curl http://somedomain.com curl: (28) Failed to connect to somedomain.com port 80 after 78173 ms: Operation timed out -
Django and HTMX active search issue
I'm trying to make an active search with HTMX in Django, and it's working, but happens that if I delete the search terms in the form the entire page is rendered twice and can`t fix it. This is ok: But this happens if I delete the text introduced in the form: view.py class SearchView(View): @staticmethod def get(request): search_term = request.GET.get('search', None) if search_term: roads = Road.objects.filter(name__contains=search_term).all()[:100] template = 'search_results.html' else: roads = [] template = 'pkes/search.html' return render(request=request, template_name=template, context={ 'roads': roads, }) search.html {% extends "pkes/base.html" %} {% block content %} <form action="/action_page.php"> <label for="search">Carretera</label> <input class="input" name="search" type="search" placeholder="Ej: EX-118" hx-get="/search" hx-trigger="keyup changed delay:500ms, search" hx-target="#search-results" hx-swap="innerHTML"/> <label for="kilometro">Kilómetro</label> <input class="input" name="kilometro"> <input type="submit" value="Enviar"> </form> <div id="search-results"> {% include "search_results.html" %} </div> {% endblock %} search_results.html {% for road in roads %} <div> {{ road.name }} </div> {% endfor %} Thanks!!! Django 4.1.6, Python 3.11.1, HTMX 1.8.5 Reference: rockandnull.com -
why is django-admin runserver giving me this error
I have no idea about this error . Please help i have set envoirment variable and pythonpath variable but its showing me error : C:\Users\Admin\AppData\Local\Programs\Python\Python310\python.exe: Error while finding module specification for 'main' (ValueError: main.spec is None -
How to make user inactive if not active for 1 day using django fsm
Need to change user status to inactive if not active for 1 day using django fsm library class UserValidity(models.Model): state = FSMField(default="active") name = models.CharField(max_length=10) date = models.DateField(auto_now_add=True) def state_inactive(self): if self.date < datetime.date.today(): self.state = 'inactive' return self.save() else: return True @transition(field=state, source="active", target="inactive", conditions=[state_inactive]) def state_change(self): print('State Inactive') -
Get Latest row values from MySQL Database in Django
I am working on a Django project. I am stuck in a situation, Where I want to retrieve latest row values of different attributes from MySQL database in django, but my query always return first row values. I am using orm query. I want latest row values entered by user through input form. Here is my code: views.py: def success(request): ip_value = NewDevice.objects.values('ip').latest('created_at') start_time_value = NewDevice.objects.values('start_time').latest('created_at') end_time_value = NewDevice.objects.values('end_time').latest('created_at') return response models.py: class NewDevice(models.Model): id = models.BigIntegerField(primary_key=True) ip = models.CharField(max_length=150) start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "live" Database Results: with live (id,ip,start_time,end_time,created_at) as (values (1 ,'1.1.1.1','10:57:00','18:23:00','13:22:29'), (2, '0.0.0.0','11:57:00','11:58:00','05:57:30'), (3 ,'10.10.10.10','13:49:00','13:50:00','08:49:20') ) Whenever my function def success executes, the query inside this function always print row 1 value which is: (1 ,'1.1.1.1','10:57:00','18:23:00','13:22:29') But I want always latest row values when record will insert into database. Kindly help to get rid of this issue. -
Django CSRF Failed: CSRF token missing or incorrect when using client on localhost
I am using django 3.2 , i had implemented csrf using below link Link Everything works fine when using same domain for client and server. But while testing locally i get the error when sending post, put or delete requests. I can see csrftoken in the request headers under cookie, but can't see it using document.cookie. csrfcookies is non httponly cookies, still i don't know why it not visible in document.cookie in client side. -
Wagtail - Image Optimisation ( How to do it with static and dynamically added image files?)
so I want to run my site with my images displayed as quickly as possible and the images are added either by giving the {% static "path/to/image.jpg" %} or by rendering the image tag for wagtail image uploads {% image image_name original as img %}. Currently, the site has considerably slowed down with lots of images, especially loading time for the images. Any possible options to optimise those images through Wagtail? It would be of great help. Thanks An example with images loading by static tag as well as image tag in wagtail. {% extends "base.html" %} {% load static wagtailcore_tags wagtailimages_tags %} {% block extra_css %} <link rel="stylesheet" href="{% static 'css/technologies.css' %}"> {% endblock %} {% block nav_projects %} class="active" {% endblock %}{% block content %} <div class="inner-page project-page"> <div class="inner-hero" style="background-image: url(/static/images/banner_a/project_bg.png);background-attachment: fixed;"> <div class="container-fluid inner-top-section mt-0 px-5"> <div class="row flex-lg-row-reverse align-items-center g-5 py-5 p-4"> <div class="col-10 col-sm-8 col-lg-6"> </div> <div class="col-lg-6"> <h1 class="display-5 fw-bold lh-1 mb-3">{{self.header_title}}</h1> <p class="lead">{{self.meta_content}}</p> <!-- <div class="d-grid gap-2 d-md-flex justify-content-md-start"> <a href="#" class="btn-two"><span class="txt">Know more</span></a> </div> --> </div> </div> </div> </div> {% if page.dblock_content %} <div class="d-block sub-hero position-relative" style="background-color: #4A4A4A"> <div class="bg-set-wrp"> <div class="left-bg-set"> <img class="zoom-fade" src="{% static 'images/project-elm/elm-1.png' %}" alt=""> </div> … -
how can i solve this in Django = UnboundLocalError at / local variable 'form' referenced before assignment
how can i solve this in Django UnboundLocalError at / local variable 'form' referenced before assignment def home(request): if request.user.is_authenticated: form = MeepForm(request.POST or None) if request.method == "POST": if form.is_valid(): meep = form.save(commit=False) meep.user = request.user meep.save() messages.success(request,('Meep has been posted')) return redirect('home') meeps = Meep.objects.all().order_by("-created_at") return render(request, 'home/home.html', {'meeps':meeps,'form':form}) else: meeps = Meep.objects.all().order_by("-created_at") return render(request, 'home/home.html', {'meeps':meeps,'form':form}) -
How to create a new pk if there is no pk in the table i refers to
I am working on a web project using django drf. There was a problem during the development, so I want someone who can help me. 😥 First, let me show you my models. Container class Container(models.Model): cont_no = models.CharField(primary_key=True, max_length=11) cont_sz = models.ForeignKey('Size', models.PROTECT, db_column='cont_sz') cont_type = models.ForeignKey( 'Type', models.PROTECT, db_column='cont_type') class Meta: managed = False db_table = 'container' Size class Size(models.Model): sz = models.CharField(primary_key=True, max_length=5) use_yn = models.BooleanField() class Meta: managed = False db_table = 'size' Type class Type(models.Model): type = models.CharField(primary_key=True, max_length=10) type_name = models.CharField(max_length=20) use_yn = models.BooleanField() class Meta: managed = False db_table = 'type' Import class Import(models.Model): wo_no = models.OneToOneField( 'Wo', models.PROTECT, db_column='wo_no', primary_key=True) cont_no = models.ForeignKey( Container, models.PROTECT, db_column='cont_no', blank=True, null=True) category = models.CharField(max_length=6) . . . class Meta: managed = False db_table = 'import' As you can see, the cont_no field in the Import table refers to the Container table. The following data exists in the Container table: cont_no | cont_sz | cont_type -------------+---------+------------ ABCD0000001 | 4000 | DRY ABCD0000002 | 2000 | DRY ABCD0000003 | 4000 | DRY I want a new value with pk 'ABCD0000004' in the Container table when the cont_no of the data present in the Import table is changed … -
Add extra file to database, path is wrong python django
Hello everyone. I am creating a website using Python Django and the main purpose of the website is to convert XML files to modified XML files. I have uploaded the files to the hosting server and when I try to perform the conversion, I need to add another file to the database record that was created. On my local server, the process works smoothly without any issues, but when I try to do it on the hosting server, I get an error message "SuspiciousFileOperation at /test/ Detected path traversal attempt in '/home/t/tkor470gma/converter/new_CUST.xml". My models.py looks like this: class Document(models.Model): document = models.FileField(verbose_name='Document (old structure with settings)',upload_to='documents/') document1 = models.FileField(verbose_name='Document (new structures without settings)',upload_to='documents/') author = models.ForeignKey(User,on_delete=models.CASCADE) resdocument = models.FileField(upload_to='documents/',blank=True) transaction_date = models.DateTimeField(auto_now_add=True) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['document','document1'] views.py This form uploads files to the database def model_form_upload(request): form = DocumentForm() pathresdoc = '' if request.method == 'POST': user = request.user form = DocumentForm(request.POST, request.FILES) obj = Document.objects.filter(author_id=user).order_by('-id') if obj.count() >= 1: return HttpResponse('it is impossible to convert first <button>Pay</button>') else: if form.is_valid(): instance = form.save(commit=False) instance.author = user form.save() create_file(request.user.id) respeople = instance.id add_file_to_database('/home/t/tkor470gma/converter/new_CUST.xml',respeople) pathresdoc = Document.objects.get(id=respeople).resdocument.path else: form = DocumentForm() return render(request, 'model_form.html', … -
Django Simple JWT logout view
I was trying to implement JSONWebTokenAuthentication using djangorestframework-simplejwt. After creating the access token I can authenticate with the token. Now I need to create a LogoutAPI view to revoke the token. I tried to delete and revoke the token but there is no reference in the documentation. How this token is managed? Now I copy the Token and paste it in the authorization section in Postman. I checked the cookie and there is no information of token. So how can I create a Logout view? Storing the token in cookie and delete it from the cookie will do the job? Guide me. -
django's clean method doesn`t load form errors
i have a problem with Django clean method because clean method of form doesn`t load error in template. Could someone help me ? template.html {% extends "index.html" %} {% block header %} <div id="container-register"> <div class="logo-register">Zarejestruj się</div> <div class="register-form"> <form method="post"> {% csrf_token %} {% for field in form %} {{ field }} {{ field.errors }} <br> {% endfor %} <input type="submit" value="Zarejestruj"> </form> </div> </div> {% endblock %} view.py class AddUserView(View): template_name = 'add_user.html' def get(self,request): return render(request, self.template_name,{ 'form': AddUserForm() }) def post(self,request): form = AddUserForm(request.POST) if form.is_valid(): User.objects.create_user( username=form.cleaned_data.get('username'), email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password'), first_name=form.cleaned_data.get('first_name'), last_name=form.cleaned_data.get('last_name') ) return redirect('/login') else: return render(request, self.template_name, context={ 'form': AddUserForm() }) forms.py class AddUserForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwa użytkownika'}), max_length=100) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Hasło'}), max_length=100) password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Powtórz hasło'}), max_length=100) first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Imię'}), max_length=100) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nazwisko'}), max_length=100) email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), max_length=100) def clean_username(self): if User.objects.filter(username=self.cleaned_data.get('username')).exists(): raise ValidationError('Ten login jest już zajęty') return self.cleaned_data.get('username') def clean_password_repeat(self): if self.cleaned_data.get('password') != self.cleaned_data.get('password_repeat'): raise ValidationError('Podane hasła różnią się od siebie!') return self.cleaned_data.get('password_repeat') I checked the page source to see if the errors class was added in the html file. -
Show popup message without reload page using Ajax in Django
`Hi all! I'm using Ajax in Django to add items to cart and wishlist without reloading the page. For user feedback without reloading the page, I need to call a popup message from their Ajax function. My view: def add_cart(request): basket = Basket(request) if request.POST.get('action') == 'POST': product_id = int(request.POST.get('product_id')) entered_quantity = int(request.POST.get('quantity')) product = get_object_or_404(Product, id=product_id) basket.add(product, entered_quantity) basket_qty = basket.__len__() response = JsonResponse({'qty': basket_qty}) return response JS function with Ajax: $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: add_cart, data: { product_id: prodid, quantity: $('#qty').val(), csrfmiddlewaretoken: window.CSRF_TOKEN, action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }); file messajes.html {% block messages %} <ul class="messages" id="messages-list"> {% if messages %} {% for message in messages %} <li> {% if message.tags %} <div class="alert alert-{{ message.tags }} msg fade show" role="alert">{{ message }}</div> {% else %} <div class="alert alert-info msg fade show" role="alert">{{ message }}</div> {% endif %} </li> {% endfor %} {% endif %} </ul> {% endblock %} Fade out message alerts function fade_alerts() { alerts = document.getElementsByClassName("alert msg"); var i = alerts.length; for (let elem of alerts) { i--; time = 3250+(1000*i); setTimeout(function() { … -
How to show messages for Integrity Error and similar database level errors in Django with DjangoRestFramework?
I had a unique constraint for a attribute on a model. Upon a post request to create it, if you enter a duplicate name, the server gives an Exception (which would be status 500). For now I am checking for the condition in the post request before creating the object. However I feel like this is not a good idea. I would want any kind of integrity error messages to be displayed in the response. Another idea is to use a try/except block and display whatever error/Integrity error occurs, but is there any other way to do this? Like not keeping the constraint in the model? or something else Is there any standard practice?