Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filters open_hours close_hours SyntaxError: positional argument follows keyword argument
I was trying to make filter method to check if my Place(model is below) is open right now. I defined fields open_hours and close_hours. Algorithm looks pretty well for me(First conditions applies to 21:00-23:00 hour and second 21:00-01:00) but Since I'm kind a new in Q and F objects I get syntaxError. line 81 Q(open_hours__lt = current_time) & Q(close_hours__gt = current_time)) ^ SyntaxError: positional argument follows keyword argument class Place(models.Model): name = models.CharField(max_length=50) lat = models.FloatField() lng = models.FloatField() address = models.CharField(max_length=50) district = models.CharField(max_length=50, choices=DISTRICTS) link = models.URLField(help_text="www.websiteurl.pl") open_hours = models.TimeField() close_hours = models.TimeField() week_day = MultiSelectField(choices=DAYS) additionalInfo = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.name def hasToBeOpenedRightNowFilter(self, queryset, name, value): now = datetime.datetime.now() current_day = now.strftime("%A") #current_day current_time = now.time() #current_time queryset_day = queryset.filter(week_day__contains = current_day) #queryset filtered after day query_time_1 = queryset.filter(open_hours__lt = F('close_hours'), #queryset filtered after first condition Q(open_hours__lt = current_time) & Q(close_hours__gt = current_time)) query_time_2 = queryset.filter(open_hours__gt = F('close_hours'), #queryset filtered after second condition Q(open_hours__lt = current_time) | Q(close_hours__gt = current_time)) queryset_time = query_time_1 | query_time_2 #merge two querysets with time conditions queryset_true = queryset_time & queryset_day #merge queryset with filter after day if not value: queryset = queryset.exclude(id__in=queryset_true.values('id')) return queryset return queryset_true -
Unable to limit choices of form field to a specific user
As the title states, I am unable to limit the choices of a form field based on a specific user. For example, in the choices for the enrolled field of the form all “riders” are selectable to all “users”, rather than just the “riders” that are “owned” by the user. I’ve tried this question and answer that essentially asks the same question, as well as some other possible solutions that deal with m2m model fields, limit_choices_to, but have not been successful. Any advise would be greatly appreciated. models.py class Event(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, null=True) description = models.TextField(max_length=255, null=True, blank=True) start = models.DateTimeField(null=True, blank=True) end = models.DateTimeField(null=True, blank=True) enrolled = models.ManyToManyField('riders.Rider', related_name='events', blank=True) def __str__(self): return self.title model.py (different app) class Rider(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthdate = models.DateField(verbose_name=None, auto_now=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.last_name + ', ' +self.first_name views.py @login_required def enroll(request, event_id): event = Event.objects.get(id=event_id) if request.method != 'POST': form = EventForm(instance=event) else: form = EventForm(instance=event, data=request.POST) if form.is_valid(): enroll = form.save(commit=False) enroll.save() form.save_m2m() return HttpResponseRedirect(reverse('riding_schedule:view_events')) forms.py class EventForm(forms.ModelForm): class Meta: model = Event fields = ['title', 'start', 'end', 'enrolled'] labels = {'text':''} widgets = { 'enrolled': forms.CheckboxSelectMultiple() } -
How to create test for UserProfile form in django
I'm new to Django and I'm nor sure what I'm doing wrong. I'm trying to run tests for my form "UserProfileForm" and the test fails all time and I don't know why. Can anyone help? this is my forms.py from .models import UserProfile from dobwidget import DateOfBirthWidget class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = [ 'profile_img', 'subscribe', 'bio', 'dob', 'telephone', 'contact_by_phone', 'contact_by_email' ] widgets = { 'dob': DateOfBirthWidget(), } this is my models.py from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_img = models.ImageField(upload_to='images', default="images/default_profile.png") subscribe = models.BooleanField(blank=True, default=False) bio = models.TextField(blank=True) dob = models.DateField(max_length=8, null=True, blank=True) telephone = models.CharField(max_length=20, null=True, blank=True) contact_by_phone = models.BooleanField(blank=True, default=False) contact_by_email = models.BooleanField(blank=True, default=False) def __str__(self): return self.user.username And this is the test that I'm trying to run from django.test import TestCase from .forms import UserProfileForm class TestUserProfileForm(TestCase): def test_can_create_a_profile(self): valid_data = { 'profile_img':"images/perfil.jpg", 'subscribe':False, 'bio':'asdjklsad asdkj;s', 'dob':'2019-03-03', 'telephone' : '12324', 'contact_by_phone' : True, 'contact_by_email' : True, } form = UserProfileForm(data=valid_data) self.assertTrue(form.is_valid()) -
Django: "no module named __sqlite3" and "Could not find a version that satisfies the requirement sqlite3"
I am making a site with the django framework on godaddys linux vps which is running centos 6.1. I installed python 3.6.9, installed vitualenv, installed django, and updated sqlite3 to version 3.29.0. Despite this when I run the command "python3 manage.py runserver" I get the following error: (djangovenv) [mrdandybpf@s132-148-80-127 blackpepperfries]$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/local/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mrdandybpf/public_html/djangovenv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, … -
How to use a Django form prefix with urlencode?
I have a template like this: <form action="/" method="GET" id="some_form"> {{ formA.as_ul }} {{ formB.as_ul }} <button>regular button</button> <button id="special_button">special button</button> </form> And I make an ajax call like this: $('#special_button').on('click', function(e) { e.preventDefault(); $.ajax({ method: "POST", data: $('#some_form').serialize(), ... }); }); The problem comes in the view that handles the ajax call: class SomeView(View): def post(self, request): formA = FormA(request.POST, prefix='formA') print(formA) # only shows inputs from formA querystring = formA.data.urlencode() print(querystring) # prints formA and formB I want to create a querystring containing only parameters from formA, but for some reason when I call formA.data.urlencode(), it gives me the values from both forms. What am I missing here? -
How to install Django in a virtual environment Python (Windows 7) from a local computer folder from a terminal?
Please answer the question. When installing Django in a Python 3.7 virtual environment (Windows 7), the package downloads from the Internet. But sometimes it happens that there is no access to the Internet. And if, for example, the installation package is located in the C: \ python_works \ Django-2.2.5.tar.gz folder on the computer, is it possible to install Django in the Python 3.7 virtual environment from this folder and how to do it, if possible? Thank you in advance for your reply. -
Parameterized property in Django
For example, I have two models: class Page(models.Model): # Some fields ... @property def title(self): return PageTranslation.objects.get(page=self, language=language).title # I can not pass property to the parameter class PageTranslation(models.Model): page = models.ForeignKey(Page) title = models.CharField() And some DRF view, which get_queryset method looks like this: def get_queryset(self): return Page.objects.all() And serializer: class PageSerializer(serializers.ModelSerializer): class Meta: model = Page fields = (..., 'title',) # title = property I want to return QuerySet with Page model instances, and use title property in serializer, but I can not pass language (that is set somewhere in the request — headers, query param, etc) there. What is the correct way to do this? -
I can POST to Django REST API using form-data but not using JSON
I have a simple app with one model in it, which is connected to REST API. I can easily access it and post new data using PostMan, where I fill in the data in form-data. But when I try to access it using curl or using PostMan 'raw' option providing json there the API returns me the response this field is required So the command I provide in curl is curl localhost:8888/api/mymodel -d "{'sender_id': '123'}" and I get back 'sender_id':['this field is required']' While if I post it via postman (form-data), everything works fine. What am I doing wrong? -
Django stipe js blocking of inline script
I'm trying to implement stripe payment system in Django. For adding card payments, I followed the guide in this link. After adding HTML markup in Django template and CSS and JS code as separate static files, I got the following console error in Firefox: Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”) What I understand from above error message is that, <script src="https://js.stripe.com/v3/"></script> JS file contains links to other JS files and Firefox blocks such connections. It should be noted that, at this stage test credit card payment is working as expected and amount debited by client is added to my stripe account's test balance. To address this blocking problem, I followed the instructions in this link. As such, I added following meta tag to my Django template: <meta http-equiv="Content-Security-Policy" content="connect-src https://api.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com; script-src https://js.stripe.com" /> After adding above Content-Security-Policy directives, Firefox console no longer shows aforementioned blocking errors, but this time my static JS files are blocked. I have modified directives as below for allowing my JS files (added 'self' to 'script-src' directive): <meta http-equiv="Content-Security-Policy" content="connect-src https://api.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com; script-src 'self' https://js.stripe.com" /> And this time before mentioned inline-script … -
How to get current url with filter parametres?
I have an url like this : http://127.0.0.1:8000/uk/events/?title=qwerty&age_filter=1&date_filter=2` How to get current url with filter parametres without language code? `/events/?title=qwerty&age_filter=1&date_filter=2` When I am trying request.resolver_match.url_name I am getting /events/. -
Is the following enough to protect my secret key and database password for heroku deployment?
I have added the environment variables through to get secret key database name and password. Now anything else to make it more secure.Let me know. Used "Advance system settings" and under that added environment variables in "User variables" . Also this is going to be my first deployment on 'heroku' that's why following a tutorial. SECRET_KEY = os.environ['DB_SECRET'] databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfoliodb', 'USER': os.environ.get['DB_USER'], 'PASSWORD': os.environ.get['DB_PASS'], 'HOST': 'localhost', 'PORT': '5432', } } -
How to link to the most recent object of a model in Django
I'm making a polling app and have a generic list view which is linking to generic detail views correctly, but I would like to have a button which links directly to the most recently submitted poll. I've got a few lines of code: #Views def currentIssue(req): ciLink = motion.objects.filter(submitTime__isnull=False).latest() return render(req, 'voting/motion_detail.html', context={'ciLink': motion}) #urls path('current-issue', views.currentIssue, name='current-issue'), This returns an empty version of the template, but I can't work out how to link to the most recent motion. Anything I've tried fails to work, and often breaks the links in the generic list view. Thank-you in advance for any help -
What does djangos unique=true actually do?
I assume it verifies that the field is unique to all other entries in the same table. But what happens if there actually is a collision? Does django just crash? Or does it just keep rerunning the default generator until it has found a value that is unique? Can I just use any crappy random number/string generator I want and assume that django will ensure that a unique value is always set? In which case, if all values are taken, does it just fall into an endless loop? -
AWS ElasticBeanstalk Django - module 'bcrypt' has no attribute 'checkpw'
I am getting this error on my AWS Server if bcrypt.checkpw(password, usrPassword): Exception Type: AttributeError at /api/user/login/ Exception Value: module 'bcrypt' has no attribute 'checkpw' Request information: USER: AnonymousUser I installed the PIP Bcrypt Library pip install bcrypt But Still I am getting same error -
Django Dynamically Remove form from formset with jQuery (extension of previous SO question)
I followed the examplespresented in SO question code. It works for me, but as I am not too good with jQuery I am having issues extending this dynamic add to also allow a user to remove forms. My template HTML is: {% csrf_token %} {{ form_2.management_form }} <div id="form_set"> {% for form in form_2 %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ form_2.empty_form }} </table> </div> <input type="button" value="Remove" id="remove"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ form_2.empty_form }} </table> </div> The jQuery script I used to get the Add More button to work was taken from the linked SO as $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }) This code works really nicely, I just wanted some code to allow users to remove forms also. My naive attempt was $('#remove').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').remove($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) - 1); }) </script> But this isn't working. I have seen things online here which allow removal, but the code is very verbose and not easy for me to follow, and the remove function isn't working. Any jQuery implementations I could use … -
DRF serializer to group data by attributes into arrays
I would like to create a Django Rest Framework serializer which can group my data based on attributes of each object. My models are described as follows: class Courses(models.Model): coursenum = models.AutoField(db_column='courseNum', primary_key=True) coursecode = models.CharField(db_column='courseCode', max_length=10, blank=True, null=False) class Meta: managed = False db_table = 'courses' class Sections(models.Model): sectionnum = models.AutoField(db_column='sectionNum', primary_key=True) semester = models.CharField(max_length=1, blank=True, null=False) section = models.CharField(max_length=2, blank=True, null=False) class Meta: managed = False db_table = 'sections' class Teachers(models.Model): teachernum = models.AutoField(db_column='teacherNum', primary_key=True) teachername = models.CharField(max_length=60, blank=True, null=False) class Meta: managed = False db_table = 'teachers' class Timeslots(models.Model): timeslotnum = models.AutoField(db_column='timeSlotNum', primary_key=True) starttime = models.TimeField(db_column='startTime', blank=True, null=False) endtime = models.TimeField(db_column='endTime', blank=True, null=False) class Meta: managed = False db_table = 'timeslots' class Venues(models.Model): venuenum = models.AutoField(db_column='venueNum', primary_key=True) venuename = models.CharField(db_column='venueName', max_length=6, blank=False, null=False) class Meta: managed = False db_table = 'venues' class Slots(models.Model): daynum = models.IntegerField(db_column='dayNum', primary_key=True) venuenum = models.ForeignKey(Venues, models.CASCADE, db_column='venueNum') timeslot = models.ForeignKey(Timeslots, models.CASCADE, db_column='timeSlot') coursenum = models.ForeignKey(Courses, models.CASCADE, db_column='courseNum', blank=True, null=True) teachernum = models.ForeignKey(Teachers, models.CASCADE, db_column='teacherNum', blank=True, null=True) sectionnum = models.ForeignKey(Sections, models.CASCADE, db_column='sectionNum', blank=True, null=True) class Meta: managed = False db_table = 'slots' unique_together = (('daynum', 'venuenum', 'timeslot'),) Using a simple Model serializer with nested sibling serializer calls, I can get the data as … -
Mobile css boilerplate for Django?
I noticed mobile-django is incompatible with the latest releases of Django. Are there any good resources for a css boilerplate for Django mobile development? -
In Django i'm trying templates folder but it is not going in templates folder. i facing following error. please help to solve this
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/check.html Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: webapp/ [name='index'] check [name='check'] admin/ The current path, check.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django-MySQL, 5 dynamic dependent dropdown list using only one model
I have a search field where I have 5 drop downs that will help me filter my search results. In my database, (MySQL) I have one Equip model with 21 columns that is the only model to be used in the search parameters. I only need to use 5 of the 21 columns to get the results needed, they are: eqtype, eqmfg, eqeff, eqmfgmodeldescrip and eqconfig. The first drop down is filter by eqtype and the second is filter by eqmfg, the third by eqeff, the fourth by eqmfgmodeldescrip , and the fifth by eqconfig. As I have it coded now, they return all options for their respected fields. However, I am trying to set the second drop down dynamically meaning that depending on the first drop down (eqtype) only those eqmfg should be displayed in the second drop down that match the respective eqtype selected. The third would be based on the first and second selections. The fourth would be based on the first, second, and third selections. The fifth would be based on the first, second, third, and fourth selections. Seeing that I have just gotten into coding, (started 4 months ago) I've been trying several tutorials that … -
SessionNotCreatedException at / Message: Unable to find a matching set of capabilities
I am trying to deploy a app (selenium with geckodriver python3). I am getting following trace back: Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/app/mp3/views.py" in search 20. driver = webdriver.Firefox(options=options, executable_path=geckodriver) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py" in init 167. keep_alive=True) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in init 156. self.start_session(capabilities, browser_profile) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in start_session 251. response = self.execute(Command.NEW_SESSION, parameters) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py" in execute 320. self.error_handler.check_response(response) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py" in check_response 242. raise exception_class(message, screen, stacktrace) Exception Type: SessionNotCreatedException at / Exception Value: Message: Unable to find a matching set of capabilities -
How to use django-push-notifications with an APNS .p8 certificate
Has anybody used the django-push-notifications library recently? It looks useful, but it seems like it needs an update. The documentation at https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst only discusses how to generate the required .pem file from a .p12 certificate, but now Apple gives you a .p8 certificate. Any ideas how to get this working? -
Creating a custom super user as part of a class Im taking
I'm currently taking a custom rest API class that is teaching me to build my own custom REST APIs for authentication, as well as creating custom user models. Im running into a slight problem with the following code base: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. 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) encrypts the passwords as a hash """ user.set_password(password) """ This allows you to specify which database to use for the user accounts. Django Supports multiple Databases!!! 8D """ user.save(using=self._db) return user def create_superusr(self, email, name, password): """ Create and save a new superuser with given details """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser, PermissionsMixin): """ Database model for users in system """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): """ Retrieve Full Name of User""" return … -
Django modelformset_factory() adding field manually in views
Disclaimer: I am new at Django so I'm sure my code is ugly. Problem: My current Model is built as follows: class person(models.Model): email = models.EmailField() date = models.DateField() phone_number = models.IntegerField() name = models.CharField(max_length = 50) belongs_to_group = models.ForeignKey(Group, related_name='group', on_delete=models.SET_NULL, null=True) belongs_to_user = models.ForeignKey(User, related_name='user', on_delete=models.SET_NULL, null=True) def __str__(self): return self.student_name I have built a modelformset_factory for this using the following code: personModelFormset = modelformset_factory( person, fields=('email', 'date' , 'phone_number', 'name'), extra=1) This makes the fields the form renders in the HTML email, date , phone_number, and name. This means that to successfully save the form to the database, I need to also add the fields belongs_to_group and belongs_to_user manually since the website user shouldn't be able to edit these (they should be automatically generated). Attempted Solution: To try to do this, I used the following view: def classes(request): #add form creation method here user = request.user group = value #taken from another form if request.method == 'POST': form_2 = personModelFormset (request.POST) if form_2.is_valid(): for form in form_2: form.belongs_to_group = value form.belongs_to_user = user form.save() return redirect('home') But this does not append the information to the form. This method works for me in a normal modelform, so I … -
Django form with two submit buttons with ajax
I use this question and all works: Referencing multiple submit buttons in django However when I use ajax, it fails, here is my code: html <form method="post" id="idForm" name="fmr1" action = "/myproject/save/" enctype="multipart/form-data"> .... <input type="submit" name="save" value="Save"> <input type="submit" name="calc" value="Calculate"> </form> js $("#idForm").submit(function(e) { e.preventDefault(); // avoid to execute the actual submit of the form. var frm = $('#idForm'); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert(data.mylist) }, error: function (data) { alert("ajax fails") } }); }); views if request.method == 'POST' and 'calc' in request.POST: print("runs calc form") mylist= [5] return JsonResponse({'mylist':mylist}) Question Now the difficulty is in "'calc' in request.POST", so it does not run when I add ajax or id="idForm" to the form. I need "'calc' in request.POST" since I have to run "save" as well. Both will have to run inside one method in views. Do you have any idea how to make it run? -
How to validate modalform for errors and show them in the same modalform?
I have a django form to create/update records that is showed on a bootstrap modal (launched through JQuery script), I can create records but when I enter information that already exists in de DDBB I get the error: "django.db.utils.IntegrityError: duplicate key value violates unique constraint DETAIL: Key (descripcion)=(OC) already exists." I understand the error is because I set the propierty of the field in the model as unique. I have tried to override the clean() method in the form to catch the errors, that works partially, now I don't receive the integrity error message but I receive the form clean as a result but not in the modal, in his case is showed in this way: form What I'm looking for is validate the information in the modalform and in case of error (like duplicate values) show the message in the same modal and not continue with the form submission. I'm very noob on JQuery and any idea or guide will be very useful. Thanks in advance. As a reference the code I have until now is: The model: class Categoria(models.Model): descripcion = models.CharField( max_length=100, help_text='Descripción de la categoría', unique=True, ) def __str__(self): return '{}'.format(self.descripcion) def save(self): self.descripcion=self.descripcion.upper() super(Categoria, self).save() …