Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django template language inside script tag using django-jsRender
As I know, there is no way to use Django template language inside Javascript block so I searched for a way how to do it, I found a Django app on GitHub called Django-jsrender but unfortunately, there isn't enough documentation for this app and when I tried to use it I couldn't and this is my code: -
Django serializer "field is required"
I want a serializer to return all the distinct countries. It just query's the db and returns it. But it always return "field is required" on the "countries" field. This is my serializer: class AdminCountrySiteSerializer(serializers.ModelSerializer): countries = serializers.ListField() class Meta: model = Site fields = ["countries"] def get_countries(self): return list( Site.objects.values_list("country", flat=True) .order_by("country") .distinct() ) test class: def test_get_all_distinct_countries(self): self.client.force_login(self.admin_user) url = reverse("admin-site-countries") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data["countries"]), 3) view: class AdminSiteCountryView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), IsSoundTalksCS() def get_serializer_class(self): return AdminCountrySiteSerializer @swagger_auto_schema( responses={200: openapi.Response(_("Successfully fetched all the countries."),)} ) def get(self, request): """ GET all distinct countries """ serializer_class = self.get_serializer_class() # serializer = serializer_class(data=request.data) serializer = serializer_class(data={"request": request}) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_200_OK,) -
Django Ajax not updating data properly
I am trying to create a like button for my posts in my post list, however, i need to refresh the page every time for the number of likes and button to change. I do not know what's causing this behavior as I am sending all the posts to the post list html file in my view. My 'likes' is a ManyToMany field for the Post model. my post_like view: @login_required def post_like(request,id): data = dict() post = get_object_or_404(Post, id=id) user = request.user if request.method == 'POST': if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) return JsonResponse(data) my ajax javascript code: $(document).ready(function (e) { $(document).on("click", "#likeBtn", function (e) { e.preventDefault(); var pk = $(this).attr("value"); var tk = $(this).attr("data-token") $.ajax({ type: "POST", dataType: 'json', url: $(this).attr("data-url"), data: {'id':pk, 'csrfmiddlewaretoken': tk}, success: function (data){ $("#post-list div").html(data.posts); }, error: function(rs, e){ console.log(rs.responeText); }, }); }); }) Thanks for all the help in advance! -
Django Logging SystemLogHandler how to encrypt
I use logging.handlers.SysLogHandler in my Django app. I need encrypted data whenever log occurs and send it after encryption. So, do you have any suggestion or solution for this? -
How to save a serial number generated in alert message during form submission in database?
views.py from django.contrib import messages import datetime import random def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) apply_online.save() return render(request,'users/applyonline.html') I want to save the serial number that is being generated i've saved others by creating their view like idcard=request.POST.get('idcard') and respectively created their model as idcard=models.CharField(max_length=100,blank=True, null=True) I'm just confused on how I can do the same for messages? -
How can I use a single enum for django model and graphql mutation arguments?
I've defined Django models with fields containing text choices corresponding to enums. The GraphQL API provides mutations (which are not derived from models directly) with arguments of type enum which shall accept the same values as the models only. How can I get rid of my dublication? models.py: class SomeModel(models.Model): class SomeEnum(models.TextChoices): A = "A", _("Option A") B = "B", _("Option B") enum_field = models.CharField( max_length=1, choices=SomeEnum.choices, default=SomeEnum.A, ) schema.py: class SomeEnumSchema(graphene.Enum): A = "A" B = "B" class SomeMutation(graphene.Mutation): class Arguments: some_enum = SomeEnumSchema(required=True) -
Django get all post of a parent category
I'm a begginner in django 3 and i decide to create a simple blog to pratice what i learned . I created a post model with a foreignkey category , and a model category with a self foreign key . Everething work well and i find a way to create my menu , the problem is when i click on the parent i want to have all post for the submenu . For example , I have this menu : *Informatic * Django * HTML - CSS *Graphic If i'm clicking on django , i have all my django post , same for html-css but now i want to have all informatic post , posts who have django + html-css together . I can modify my model Post and instead to have a field with category in foreign key , i could use a manytomanyfield . But i don't want it , because i can forgot to put in informatic or in other category . So what could I do, in a simple way ? Can you explain to me what and how todo , and where i need to put code I'm not sure what code do you need … -
update API request from django view
Hy guys, I'm trying to do this in a django app : my idea is simple: show a map with a marker who shows ISS's position. Every second, the marker should move because the data change. I know I can do that by calling the ISS API in Javascript but i would like to call the datas from my view with python module render. Thus, I would like to update my view without refreshing the page. My view is : def ISS(request): r =requests.get("https://api.wheretheiss.at/v1/satellites/25544").json() pos = { "latitude": r["latitude"], "longitude": r["longitude"] } return render(request, 'blog/pos_iss.html', locals()) and my template : <div id="mapid"></div> <style type="text/css"> #mapid { height: 500px; } </style> <script type="text/javascript"> const attribution = '&copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors'; const TileUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; const tiles = L.tileLayer(TileUrl, { attribution }); const lat = {{ pos|get:"latitude"|stringformat:"f" }}; //update here const long = {{ pos|get:"longitude"|stringformat:"f" }}; const mymap = L.map('mapid').setView([lat, long], 4); tiles.addTo(mymap) function getISS() { var marker = L.marker([lat, long]).addTo(mymap); } getISS(); </script> I would like the latitude and longitude to update every seconds. I think there something to do with Ajax but I don't know how. It's my first ask on stack, don't hesitate to give me a piece of … -
How to fill author or user name using python shell
I was trying to fill my author field using python shell, in shell i was typing this: Post.objects.create(title='second blog post', author="yashm", body='done via python shell') I already created a superuser named as 'yashm', but still im getting this error (see picture) Models.py file from django.db import models class Post(models.Model): title = models.CharField(max_length = 120) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title[:50] -
Django error in cmd while using python manage.py runserver
the error i'm getting is E:\coding\fyp\travel>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "D:\anacondapython3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "D:\anacondapython3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\anacondapython3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\anacondapython3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\anacondapython3\lib\site-packages\django\core\management\base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern [<URLResolver <URLPattern list> (admin:admin) 'admin/'>, <URLResolver <module 'app1.urls' from 'E:\\coding\\fyp\\travel\\app1\\urls.py'> (None:None) ''>, <URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. System check identified 1 issue (0 silenced) my settings.py: """ Django settings for travel project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import psycopg2 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&d+2s#z#yxa(5vx-0+vn^(pn^115afs+csfnq0uv%w94dbth_w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
WinError 193 %1 is not a valid Win32 application: when deploying Django on Apache
I am on windows server 2012. I have built an API on Django rest-framework and I am trying to deploy it using WAMP and mod_wsgi. I have tested the API by running 'python manage.py runserver' and it's giving the expected output. The issue is when I am deploying it on WAMp using mod_wsgi I am able to start WAMP service but when I try to reach 'localhost' it's giving me the following error: below is the Traceback : Environment: Request Method: GET Request URL: http://localhost:8089/ Django Version: 3.0.5 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'API'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\core\handlers\base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\python376\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in … -
Integrating MediaWiki with Django
I have a Django site(say: 'xyz.com'), it contains one app as of now, however some more may be added in the future. I want to create a wiki, preferably using MediaWiki, such that it's gets displayed on 'xyz.com/wiki', and the wiki-pages like 'xyz.com/wiki/topic1' and so on. I have searched a lot for this, and I am unable to find a way to do this. The only way I can think of doing this is creating a wiki independently and then adding a redirect button on my django site. I saw a few posts suggesting to use django-wiki but I saw their demo site, and no offence, it looks hardly like a 'wiki'. I am on python 3.8.2 and django 3.0.3. Any help/suggestion is appreciated! -
Creating tables for users in Django
I am creating a medical inventory system with Django. In this system, there are several. I want to create medicine tables ,in database, for the users. Every user has their own table. How can I make this? I am using mysql. users/model.py from django.contrib.auth.models import AbstractUser from django.db import models user_type = ( ('pharmacist', 'Pharmacist'), ('manager', 'Medical Repository Manager'), ) class CustomUser(AbstractUser): user_type = models.CharField(max_length=50, choices=user_type) def __str__(self): return self.username Note: Every user can add or delete medicine from their table. Because this is an inventory management system. -
How to using the form in 2 pages
Guys i am new to django and want to learn how to keep the same entry field in 2 different pages. In forms.py: class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = Student fields = ['name',] In views.py def studinfo(request): form = StudentForm(request.POST) if request.method == "POST": if form.is_valid(): form1 = form.save(commit=False) name = form1.name background=Student.objects.get(stud_name=name) context={'profile':background ,} return render(request, 'main/stud_info.html', context) return render(request, 'main/main.html', context={'form':form}) in stud_info.html where it shows the results i also included: <form class="form-inline"> <input class="form-control mr-sm-2" type="search" aria-label="Search"> <button class="btn btn-outline-warning" type="submit">OK</button> </form> but it does not work as i do not know how to make it implement the function of studinfo(request). I do not want to create the same function and pass to the form. How automatically make it implement the same function in aother page? I hope i could explain what i want to learn. I apologise for any unclear explanation as Django is new for me and keep learning. -
How do i create a model for the alert message generated unique number?
views.py from django.contrib import messages import datetime import random def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) I've generated unique number for each form submission ,how do i create a model to save it in the database so that i can use it as a reference -
Django Postgres migration: Fastest way to backfill a column in a table with 100 Million rows
I have a table in Postgres Thing that has 100 Million rows. I have a column that was populated over time that stores some keys. The keys were prefixed before storing. Let's call it prefixed_keys. My task is to use the values of this column to populate another column with the same values but with the prefixes trimmed off. Let's call it simple_keys. I tried the following migration: from django.db import migrations import time def backfill_simple_keys(apps, schema_editor): Thing = apps.get_model('thing', 'Thing') batch_size = 100000 number_of_batches_completed = 0 while Thing.objects.filter(simple_key__isnull=True).exists(): things = Thing.objects.filter(simple_key__isnull=True)[:batch_size] for tng in things: prefixed_key = tng.prefixed_key if prefixed_key.startswith("prefix_A"): simple_key = prefixed_key[len("prefix_A"):] elif prefixed_key.startswith("prefix_BBB"): simple_key = prefixed_key[len("prefix_BBB"):] tng.simple_key = simple_key Thing.objects.bulk_update( things, ['simple_key'], batch_size=batch_size ) number_of_batches_completed += 1 print("Number of batches updated: ", number_of_batches_completed) sleep_seconds = 3 time.sleep(sleep_seconds) class Migration(migrations.Migration): dependencies = [ ('thing', '0030_add_index_to_simple_key'), ] operations = [ migrations.RunPython( backfill_simple_keys, ), ] Each batch took about ~7 minutes to complete. Which would means it would take days to complete! It also increased the latency of the DB which is bing used in production. -
How to remove duplicates from Django QuerySet with MySQL database and related models
I use MySQL database in Django, so i can't use .distinct() to remove duplicates from QuerySet. I want to display each computer name with latest values of ip and last_on time. Models.py class Computer(models.Model) name = models.CharField() def __str__(self): return self.name class ComputerData(models.Model) pc = models.ForeignKey(Computer, on_delete=models.CASCADE) ip = models.GenericIPAddressField(null=True) last_on = models.DateTimeField() def __str__(self): return self.last_on.strftime('%Y-%m-%d %H:%M:%S') Views.py def computerlist_request(request): return render(request = request, template_name = "main/computerlist.html", context={"pc": Computer.objects.all(), "pcdata": ComputerData.objects.all()}) computerlist.html {% for p in pc, data in pcdata %} <tr> <td>{{pc.name}}</td> <td>{{data.ip}}</td> <td>{{data.time|date:"Y-m-d H:i:s"}}</td> </tr> {% endfor %} -
Carousel slider showing images in list with django
I’m new to django and I am creating a website which shows the product images on the home webpage in the form of a Carousel slider (bootstrap 4). {%extends 'blog/base.html'%} {%block content%} <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> <li data-target="#myCarousel" data-slide-to="3"></li> <li data-target="#myCarousel" data-slide-to="4"></li> <li data-target="#myCarousel" data-slide-to="5"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for p in products %} {% if forloop.counter == 1 %} <div class="item active"> {% else %} <div class="item"> {% endif %} <img src="{{ p.image.url }}" alt="Image" width="460" height="345"> <div class="carousel-caption"> <h3>{{ p.name }}</h3> <p>{{ p.description }}</p> </div> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> {%endblock content%} But this code only shows all the images in a straight line without the buttons on the side. I have provided the output: Images in Line I want all the images in the slider format with the navigation buttons Thanks -
MemoryError while saving large list of dicts in the Django database
At the very moment I try to save a 0.4mb list of complex objects to a json field I get a MemoryError exception. Does it really use so much ram memory to dump that into the database? It is a mysql database. I agree that data should not be stored in this way, but that's how the project is and I need to think of alternative ways of storing the data, but before changing the design I would like to know if there are workarounds for this memory error if this is an issue with django or python. Thanks in advance -
django- stream inside a template
I have a "Start Camera" button on my Index page. If clicked on that, I need to show Webcam feed on the same page (Index) and detect faces from the video. "Stop Camera" should stop the webcam. $(function() { $('.start-camera').on("click", function(e){ $(".item-container").html('<img src="/video_feed">'); }) }) urls.py urlpatterns = [ url(r"^$", views.index, name="index"), url(r'^admin/', admin.site.urls), url(r'^video_feed/', views.video_feed, name="video_feed"), ] views.py def index(request): return render(request, "web_app/index.html") def video_feed(request): return HttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') I am not mentioning the python scripts that contain the OpenCV code. That part is working correctly. The problem I am facing is: "video_feed" will keep serving HttpResponse until "Stop Camera" is pressed and the [img src= "/video_feed"] is removed from the DOM. But I cannot find a way back to index.html and actually see the webcam feed. If I could load the HttpResponse inside the index.html page, then my problem would be solved. But I have limited experience working with Django and cannot get my head around it. In Flask, I can just do this: @app.route('/video_feed') def video_feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame') This URL mapping does not return a view but only loads the response in the current index.html page. In Django, whenever I am registering a URL, I … -
How to fetch first form data and set that data in second form?
I have models Offer & OfferItem as below and I need to create an Offer and OfferItem at same template page. My problem is I want to save offer_form first then set saved offer record as related on itemOffer field then save offeritem_form how can I do it? Or may be my models and logic is completely wrong, if so is there any other way to do it? *I exclude HStoreField, cuz I will need to save multiple OfferItems at same page (may be I am wrong again I don't know) Here is my models etc. Models; class Offer(models.Model): offerCreate = models.DateTimeField(auto_now=False, auto_now_add=True) offerOwner = models.ForeignKey(User, on_delete=models.CASCADE) offerNumber = models.CharField(max_length = 150) offerCondi = models.TextField() offerTotal = models.FloatField() def __str__(self): return self.offerNumber class Meta: verbose_name = 'Offer' verbose_name_plural = 'Offers' class OfferItem(models.Model): itemOffer = models.ForeignKey('sales.Offer', on_delete=models.CASCADE) itemName = models.CharField(max_length = 150,null=True) itemProduct = models.ForeignKey('products.Product', on_delete=models.CASCADE) itemLeadtime = models.CharField(max_length = 150) itemCost = models.FloatField() itemPrice = models.FloatField() itemCurrency = models.ForeignKey('products.Currency', on_delete=models.CASCADE) itemQuantity = models.IntegerField() itemOfferprice = models.FloatField() def __str__(self): return self.itemName class Meta: verbose_name = 'OfferItem' verbose_name_plural = 'OfferItems' View; def createofferView(request): offer_form = CreateOfferForm(request.POST or None) offeritem_form = CreateOfferItemForm(request.POST or None) if offer_form.is_valid() and offeritem_form.is_valid(): offer_form.save() offeritem_form.save() messages.success(request, 'Success!') return … -
Django form sends mail twice
when creating a user from Django admin Panel, I am trying to send a mail that they have been added to the site. But, mail is getting triggered twice. Below is my code # Models.py class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin, TimestampedModel): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_staff = models.BooleanField(default=False, help_text='Allow the user access to the admin site') is_superuser = models.BooleanField( default=False, help_text='User has all permissions' ) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) # force_password_change= models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __unicode__(self): return self.email def __str__(self): if self.first_name == '' and self.last_name == '': return '{0}'.format(self.email) return '{0} ({1})'.format(self.get_full_name(), self.email) @property def token(self): return self._generate_jwt_token() def get_full_name(self): return "{0} {1}".format(self.first_name, self.last_name) def get_short_name(self): return self.first_name def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') def generate_password(self): password = User.objects.make_random_password() self.set_password(password) self.save() return password class Meta: verbose_name="Site Admin" verbose_name_plural= 'Site Admins' # Forms.py class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': "The two password fields didn't match.", } email= forms.EmailField(max_length=50, help_text="Required") password1 = forms.CharField(label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password confirmation", widget=forms.PasswordInput, help_text="Enter the same password as above, for verification." ) class Meta: model = … -
creation of tools or website for application deployment task
i’m python beginner and i want to make python tools for below requirement OR wanted to complete below task with Django website. Task: need to deploy some application which is on server over 400 machines and all are connected to VPN (IP is changing) so i have doubt how to implement/handle this with python any suggestion/guidance or steps. few challenges : suppose if all machines are not coming online then need to separate offline machines from list and get report of (online)completed machines. -
How to display custom errors in the template
I have function with custom errors, how to display these errors in the template def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponse('error') else: # messages.success(request, 'match') user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('You don\'t have access to this page') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) I mean maybe try to do something like that,what i should use istead HttpResponse and how to implement in the template {% if form_auth.errors %} {% for field in form_auth %} {% for error in field.errors %} <div class="ui red message"> {{error}} </div> {% endfor %} {% endfor %} {% endif %} -
How to avoid storing in the database if an error occurs in the next iteration step
Input data is a list of dictionaries. The list can consist of several hundreds of dictionaries and looks like this. data = { "vendor_name": "Ullamcorper Duis LLP", "country": "Belgium", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "jack@gmail.com", "contact_name": "Jack Jhonson", "primary": true }, { "email": "jack2@gmail.com", "contact_name": "Jack Jhonson", "primary": false } ] }, { "vendor_name": "Habitant Associates", "country": "Turkey", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "eget.metus.eu@elitdictum.edu", "contact_name": "Trevor Smith", "primary": true }, { "email": "at.risus.Nunc@iaculis.ca", "contact_name": "Madonna Z. Kemp", "primary": false } ] }, .... .... ] Since some fields (for example, vendor_name) must be unique and if n-element and n+1 item are equal, the error "Vendor already exists" appears. And this is correct, of course. It so happens that some information is written into the database before the error occurs. But I need the writing to be done on the all or nothing principle. views.py class CsvToDatabase(APIView): serializer_class = VendorsCsvSerializer def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None for contact in data['contacts']: if contact['email']: contact['email'] = contact['email'].lower() for module in data['modules']: if module['module']: module['module'] = …