Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while working with two databases in Django: sqlite3.IntegrityError: NOT NULL constraint failed: wagtailcore_page.draft_title
I'm working on a Django Project with Wagtail which uses two databases. The first one is the standard sql lite database for all django models (called db_tool.sqlite3), the other one is also sql lite but for a wagtail integration (called db.sqlite3). I wanted to migrate to the db_tool.sqlite3 with the following command python manage.py make migrations python manage.py migrate --database db_tool but now I get the following error message regarding wagtail, which I never got before. django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailcore_page.draft_title First of all: I don't understand this, because I named the db_tool in particular and I wonder, why the wagtail integration raises an error when I try to migrate to db_tool. Second: I see no particular field at my wagtail-pages called draft_title and I don't have any draft page at the moment. Third: the error message also relates to a migration file of wagtail that can be found in the side-packages (see below). So maybe this is the root of the error, but I don't understand the correlation to the other error message, because since now it worked fine and I changed nothing exept of some content of my wagtail pages. File "C:\Users\pubr\.conda\envs\iqps_web\lib\site-packages\wagtail\core\migrations\0001_squashed_0016_change_page_url_path_to_text_field.py", line 23, in initial_data root … -
How can I add an Image to a Django Custom User Model (AbstractUser)?
I am trying to add 'image' to a class that extends AbstractUser. I would like to know how I could use fetch api to make a post request (vuejs) so that it calls on an views.py api and specifically uploads an image for a user. I understand how this would work when it comes to frontend but I do not know what my django views.py api would do assuming I only want it to take a file object and just add to the appropriate user. I have followed the below tutorial, however, they assume DRF is being used as opposed to an api simply made in views.py. This is why I am unsure about what my api will need to do with the image object I pass over using formData https://www.youtube.com/watch?v=4tpMG6btI1Q I have seen the below SO post but it does not directly address what my views.py api would do. That is, will it just store an image in a certain format? A URL? Add Profile picture to Django Custom User model(AbstractUser) class CUser(AbstractUser): image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return f"{self.first_name}" -
how to Don't repeat div into for loop in django template
i have questions and answers into for loop in django template that repeats itself from dictionary, and a button that i don't want to be repeated into the for loop, i searched everywhere on documentation but i found nothing, an exemple : {% for question in questions %} {{question}} {% for reps in questions %} {{reps}} {% endfor %} <div><input type="button" value="Next question"></div> {% endfor %} i want to don't repeat the input button into the for loop -
Django when I upload a image is not saved
I'm trying to create an auction system with django. But when I create a new item for the auction, the image is not saved, but the rest of the item does. But the media folder isn't created. SETTINGS.PY MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") URLS.PY urlpatterns = [ path("admin/", admin.site.urls), path("", include("core.urls")), path("users/", include("users.urls")), path("users/", include("django.contrib.auth.urls")), path("auction/", include("auction.urls")), ] if settings.DEBUG: """ With that Django's development server is capable of serving media files. """ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MODELS.PY class Auction(models.Model): object = models.CharField(max_length=50) description = models.CharField(max_length=256, default="") image = models.ImageField(upload_to="media/", null=True, blank=True) open_date = models.DateTimeField(auto_now_add=True) close_date = models.DateTimeField() total_bet = models.IntegerField(default=0) open_price = models.FloatField( default=0, ) close_price = models.FloatField(default=0) winner = models.CharField(max_length=256, default="") active = models.BooleanField(default=True) json_details_file = models.TextField(default="") tx = models.CharField(max_length=256, default="") def __str__(self): return self.object FORMS.PY class ItemForm(forms.ModelForm): class Meta: model = Auction fields = ["object", "description", "image", "close_date", "open_price"] widgets = { "close_date": DateTimeInput(attrs={"placeholder": "YYYY-MM-DD HH:MM"}) } VIEW.PY @login_required(login_url="login") def new_item(request): """ A function that will create a new item for te auction """ if request.method == "POST": form = ItemForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Item create") return redirect("homepage") else: form = ItemForm() return render(request, "auction/new_item.html", {"form": form}) new_item.html {% extends "base.html" %} {% … -
Get average of multiple ratings values from different model instances (Django)
I'm working on this web-app that lets a project manager rate a vendor after finishing a task/job. Here is the models.py content: class Rating(models.Model): RATE_CHOICES = [ (1, 'Below Expectation greater than 0.02'), (2, 'Meet Expectaion 0.02'), (3, 'Exceed Expectaions less than 0.02'), ] reviewer = models.ForeignKey(CustomUser, related_name="evaluator", on_delete=models.CASCADE, null=True, blank=True) reviewee = models.ForeignKey(Vendor, null=True, blank=True, related_name="evaluated_vendor", on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, null=True, blank=True, related_name='jobrate') date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=200, blank=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) class Job(models.Model): title = models.CharField(null=True, blank=True, max_length=100) project_manager = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="assigned_by") startDate = models.DateField(blank=True, null=True) deadlineDate = models.DateField(blank=True, null=True) status = models.CharField(choices=STATUS, default='In Preparation', max_length=100) evaluated = models.BooleanField(default=False) #Related Fields purchaseOrder = models.ForeignKey(PurchaseOrder, blank=True, null=True, on_delete=models.CASCADE) project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.CASCADE, related_name="Main_Project") assigned_to = models.ForeignKey(Vendor, blank=True, null=True, on_delete=models.CASCADE, related_name="Job_owner") class Vendor(models.Model): #Basic Fields. vendorName = models.CharField(null=True, blank=True, max_length=200) addressLine1 = models.CharField(null=True, blank=True, max_length=200) country = models.CharField(blank=True, choices=COUNTRY_CHOICES, max_length=100) postalCode = models.CharField(null=True, blank=True, max_length=10) phoneNumber = models.CharField(null=True, blank=True, max_length=100) emailAddress = models.CharField(null=True, blank=True, max_length=100) taxNumber = models.CharField(null=True, blank=True, max_length=100) mother_language = models.CharField(blank=True, choices=LANGUAGE_CHOICES, max_length=300) Here is my view.py: @login_required def vendors(request): context = {} vendors = Vendor.objects.all() context['vendors'] = vendors if request.method == 'GET': form = VendorForm() context['form'] = form return render(request, … -
Storing different types of data in a single django database column
I have a problem that I can't quite fix, I have a table built on the basis of a model: class MessageData(models.Model): messageID = models.IntegerField() fieldID = models.IntegerField() value = models.CharField(max_length=60) class Meta: verbose_name = 'MessageData' verbose_name_plural = 'MessagesData' I need to somehow, when creating a request, in some posts, in the value field, transfer the file and then save it to the media folder, and in some posts, the text is simply taken from the textarea, Meybe someone knows a simple method to implement this without adding new fields to the model? The data i get from this template using this method: def clientPage(request, link_code): if request.method == 'POST': files = request.FILES req = request.POST.copy() print(files) print(req) {% block content %} <div class="card bg-dark"> <div class="card-header"> <h5 class="text-light">From associate: {{ message }}</h5> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <div class="card-body"> <div class="form-group"> <label for="subjectInput" class="form-label mt-4 text-light">Subject</label> <input class="form-control" id="subjectInput" placeholder="Enter subject" name="subject"> </div> <div class="form-group"> <label for="Textarea" class="form-label mt-4 text-light">Text Area</label> <textarea class="form-control" id="Textarea" rows="3" name="textArea"></textarea> </div> <div class="form-group"> <label for="formFileMultiple" class="form-label">Multiple files input</label> <input class="form-control" type="file" id="formFileMultiple" name="file" multiple/> </div> </div> <div class="card-footer"> <button class="btn btn-success" type="submit">Send Data</button> </div> </fieldset> </form> </div> {% endblock %} -
How to disable transaction in Django Admin?
I used @transaction.non_atomic_requests for the overridden save() in Person model as shown below: # "store/models.py" from django.db import models from django.db import transaction class Person(models.Model): name = models.CharField(max_length=30) @transaction.non_atomic_requests # Here def save(self, *args, **kwargs): super().save(*args, **kwargs) And, I also used @transaction.non_atomic_requests for the overridden save_model() in Person admin as shown below: # "store/admin.py" from django.contrib import admin from .models import Person from django.db import transaction @admin.register(Person) class PersonAdmin(admin.ModelAdmin): @transaction.non_atomic_requests # Here def save_model(self, request, obj, form, change): obj.save() But, when adding data as shown below: Transaction is used as shown below. *I used PostgreSQL and these logs below are the queries of PostgreSQL and you can check On PostgreSQL, how to log queries with transaction queries such as "BEGIN" and "COMMIT": And also, when changing data as shown below: Transaction is also used as shown below: So, how can I disable transaction in Django Admin? -
how to add data to a list of dictionary
a = list(request.POST.getlist('users')) b = get_participants['participants'] output=[] for i in b: for k in a: if k in i: print(k) c={ "participants" : k, "attendance" : "Present" } # output.append(c) else: c={ "participants" : i, "attendance" : "Absent" } output.append(c) print(output) This is my code I have to add participants with respect to their attendance . In "a" Im getting list of participants those are present. In "b" Im getting all participants My logic wasnt going right plz correct me. a = list(request.POST.getlist('users')) b = get_participants['participants'] output=[] for i in b: for k in a: if k in i: print(k) c={ "participants" : k, "attendance" : "Present" } # output.append(c) else: c={ "participants" : i, "attendance" : "Absent" } output.append(c) print(output) I have tried this Output: [{'participants': 'rajesh.gupta@atmstech.in', 'attendance': 'Present'}, {'participants': 'rajesh.gupta@atmstech.in', 'attendance': 'Absent'}, {'participants': 'pranay.gharge@atmstech.in', 'attendance': 'Absent'}, {'participants': 'pranay.gharge@atmstech.in', 'attendance': 'Present'}] expected output: [{'participants': 'rajesh@gamil.in', 'attendance': 'Present'}, {'participants': 'pranay@gmail.in', 'attendance': 'Present'}] -
Django imagefield repeat
I added an index.html carousel for my django project. When I try to pull the database from django admin, there are a lot of pictures and it repeats one picture? [enter image description here](https://i.stack.imgur.com/CJXFa.png) [enter image description here](https://i.stack.imgur.com/p7OKh.png) [enter image description here](https://i.stack.imgur.com/gjTcy.png) Can you tell me where is the problem? -
Can a mobile application backend be built using Django & python?
Me and my friend are trying to create a mobile application. We'll be using flutter in the frontend. There are some doubts we've regarding the backend of the application. Can we create the backend using Django and python? We're planning to access the backend with the Api's. Did some googling where some said it is not possible to build because Django is a web framework also were some said it can be done if we're using it with Api. Our Stack: Frontend: Flutter Backend: (Python-Django) or (Nodejs-Express) Database: MongoDB NOTE: I want to keep my backend as clean as possible as in don't want to keep extra things which I will not be using in my project! -
Match student's time with TA's time slot to make a scheduling table
I'm trying to make a scheduling system for TAs and students at my school. The logic is every TA has an open period (from start_time to end_time on some days of the week, and 15-minute slots during that period. (I figured out how to output that in HTML already.) Every student also has a time they want to meet with an available TA whose time slot match with the student's time on the same day of the week. I'm having trouble with how to match student's time with TA's time slot and put student's name beside TA's time slot. Can anyone help, please? Thanks!! Here's my models, views.py, HTML, and web output. -
Django UpdateView Two Seperate Form Save (included inlineformset_factory)
I have a specific problem with my forms. I think it would be better to share my codes instead of explaining the problem in detail. However, to explain in a nutshell; inside my model I have field OneToOneField and model of that field has inlineformset_factory form. My new model also has a form and I want to save both forms. I get the following error when I want to save the offer update form: TypeError at /ru/mytarget/offer-update/T2GTTT053E9/ AdminOfferUpdateView.form_invalid() missing 2 required positional arguments: 'request_form' and 'request_item_formset' Models: request.py class RequestModel(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_requests") id = ShortUUIDField(primary_key=True, length=10, max_length=10, prefix="T", alphabet="ARGET0123456789", unique=True, editable=False) status = models.BooleanField(default=True) request_title = models.CharField(max_length=300) delivery_time = models.CharField(max_length=50) shipping_country = models.CharField(max_length=50) shipping_address = models.CharField(max_length=300) preferred_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) shipping_term = models.ForeignKey(ShippingTerm, on_delete=models.CASCADE) delivery_term = models.ForeignKey(DeliveryTerms, on_delete=models.CASCADE) request_statuses = models.ForeignKey(RequestStatus, on_delete=models.CASCADE, blank=True, default=1) is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) is_offer_created = models.BooleanField(default=False) updated_on = models.DateTimeField(auto_now=True) published_date = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.request_title) class Meta: verbose_name_plural = "Requests" verbose_name = "Request" def get_absolute_url(self): return reverse('mytarget:customer_request_details', kwargs={'pk': self.id}) class RequestItem(models.Model): request_model = models.ForeignKey(RequestModel, on_delete=models.CASCADE, related_name="request_items") product_name = models.CharField(max_length=300) product_info = models.TextField(max_length=2000, blank=True) target_price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) quantity = models.DecimalField(max_digits=10, decimal_places=2) … -
Send data from google sheet to a webhook url in json format on trigger column
Is there a way to trigger an action (i.e convert row data into json format and send it to a webhook URL) from googlesheets based on column values like dates? Triggers like when todays date equals date in column? WEBHOOK REQUEST EXAMPLE DATA { "data": { "header_image_url": "https://..." }, "recipients": [ { "whatsapp_number": "+91XXXXXXXXXX", "attributes": { "first_name": "James", "last_name": "Bond" }, "lists": [ "Default" ], "tags": [ "new lead", "notification sent" ] } ] } I am new to webhooks and API stuff, there form do not know much. -
what is the best way to use has_usable_password in Django 3 templates?
I would like to add condition in my template to see if user password is set or not. Something like this doesn't work for me because I cannot put it in my html: >>> a = User.objects.create_user('user1', 'user1@example.com') >>> b = User.objects.create_user('user2', 'user2@example.com', password='secret') >>> a.has_usable_password() False >>> b.has_usable_password() True I tried to put has_usable_password in html as template tag but it doesn't work: {% if user.has_usable_password == True %} password ok {% else %} password not set {% endif %} Something like this is also not working {% if user.has_usable_password %} passord ok {% else %} password not set {% endif %} But if I go to admin panel I see password not set -
Use filterset class in a nested route in Django REST Framework
We have a REST API created with Django and Django REST Framework. With the package django-filter I've created a FilterSet class which I want to use in a nested route. For illustration, we have model classes User, Post, Tag. A Post has one author (User) and can have many (or none) Tags. The following endpoints are present: /users/[id]/ /posts/[id]/ /users/[id]/posts/ The FilterSet class looks like this: class PostFilterSet(filters.FilterSet): tags = filters.ModelChoiceFilter(queryset=Tag.objects.all()) class Meta: model = Post fields = ("tags",) We use it in the viewset for Posts: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() filter_backends = [filters.DjangoFilterBackend] filterset_class = PostFilterSet Now this is working well and the list of posts can be filtered by tag, like this: /posts/?tags=some_tag In the UserViewSet we have a nested route created with the decorator action: class UserViewSet(viewsets.ReadOnlyModelViewSet): @action(methods=["get"], detail=True) def posts(self, request, pk): # logic to fetch posts for the given user return Response(serializer.data) We want to filter the list of posts for a given user (author) tagged by some tag: /users/[id]/posts/?tags=some_tag I want to use the PostFilterSet class in the nested route above. Is this possible? If yes, how should it be done? -
Unable to understand why the error is occurring
I have been trying to concatenate two strings and assign them to a cell in an excel sheet. I am however unable to understand why the below-shown error is occurring as I cannot find any error in the functioning of the rest of the code the error shown is: Traceback (most recent call last): File "C:\Users\AdvaitSNambiar\Desktop\Myfolder\SUTT task\Final\task1test-2-final.py", line 63, in <module> ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' if (h2 == 'A3'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' this was the concatenation I tried to perform my code is given below import openpyxl from openpyxl import load_workbook wb = load_workbook('names.xlsx') ws = wb.active i = 0 while(i<24): i = 2 while(i<24): idnum = ws['A' + str(i)] idnum1 = idnum.value idnum2 = idnum1[4:8] if (idnum2 == 'AAPS'): ws['D' + str(i)] = 'ECE' if (idnum2 == 'ABPS'): ws['D' + str(i) ] = 'Manu' if (idnum2 == 'A1PS'): ws['D' + str(i)] = 'chemical' if (idnum2 == 'A2PS'): ws['D' + str(i) ] = 'civil' if (idnum2 == 'A3PS'): ws['D' + str(i) ] = 'EEE' if (idnum2 == 'A4PS'): ws['D' + str(i)] = 'Mech' if (idnum2 == … -
Pass html in to another html
Hello dear community, First of all, I've been trying to solve the problem for x hours, but so far I've failed transiently. You are Tmm a last opening. I am currently involved in a project where we are developing a quiz game. I am responsible for the backend. We want users to be able to add questions to the game as well, but when a user adds a question, it should be saved to the database before the question. As soon as the user adds a question, the admin gets an email: "A new question has been received", and the email contains a link that leads to an html page (approve_question.html). Up to here everything works. However, the link only leads to an empty html page. I want added question then show on approve_question.html so admin can save in database after check so question will show in game then. my problem is i can't find question.html page (the question with four answers can then be entered here), with the content forward to approve_question.html. I'll add some more code to make it clearer. The question.html has one field for the questions and four for the answers. I would like to fill … -
While paginating my results of dictionary values in djnago I am getting an error as unhashable type: 'slice'
I am trying to paginate my results(dictionary values) to html page. While doing I am getting an error unhashable type: 'slice' views.py from django.shortcuts import render import urllib.request import json from django.core.paginator import Paginator def display(request): cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi','Bengaluru','Mangaluru','Chikkamagaluru','Chennai'] data = {} for city in cities: source = urllib.request.urlopen( 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=APIID').read() list_of_data = json.loads(source) data[city] = { "country_code": str(list_of_data['sys']['country']), "coordinates": { 'latitude': str(list_of_data['coord']['lat']), 'longitude': str(list_of_data['coord']['lon']) }, "temp": str(list_of_data['main']['temp']) + ' °C', "pressure": str(list_of_data['main']['pressure']), "humidity": str(list_of_data['main']['humidity']), 'main': str(list_of_data['weather'][0]['main']), 'description': str(list_of_data['weather'][0]['description']), 'icon': list_of_data['weather'][0]['icon'], } p = Paginator(data,3) page = request.GET.get('page') d = p.get_page(page) context = {'data': d} return render(request, 'display.html', context) Please help me to paginate the values in a dictionary I expect the paginated results of my dictionary values -
How do I override internal Django Installed app settings.py parameter
I am using django-otp via django-two-factor-auth and I am unable to override a very simple setting in settings.py that the django-otp package is requiring. Internally I can see that the django-otp is requesting OTP_TOTP_ISSUER to be set in the hosting app's settings.py. But for some reason, seems that the django-otp package is relying on some internal settings.py maybe also because the django-otp have internal "plugins" which are installed as apps in my django app. Trying to override their data seems to be futile... Any idea how can a setting be injected/overridden in internal "installed_app"? -
Find a get queryset values that existes in another queryset of tha same model
Iam tring filter permission queryset that exists in another Queryset of permission. How can filter that Queryset ####### My code staff_perm = instance.permissions.all(). designation_perms = instance.designation.permissions.all() # needed_designation_perms = designation_perms that exists in staff_perm Ex : Consider A and B are Querysets A = [1,2,3,4,5] B = [1,3,5,7,9] i want C = [1,2,3,4,5] -
Defining custom request - Swagger (Drf-yasg)
I have a use case, where the request required fields are different depending on one of the field value of the request. Example, if the value of move type in request is 'P', then some fields are mandatory, otherwise if value of move type is 'D', then some of the other fields are mandatory. How to create custom request for such use case using drf-yasg ? -
How to make API for filtering objects in django based on multiple key-value pairs in GET request?
I have an API url in "urls.py" folder of my django project :- path('tests/filter/<str:key1>/<str:value1>', FilterTests.as_view()) This works fine for the below code :- from rest_framework import generics from service.models import Test from service.serializers import TestListSerializer class FilterTests(generics.ListAPIView): queryset = Test.objects.all() serializer_class = TestListSerializer def get_queryset(self, *args, **kwargs): key1 = self.kwargs['key1'] value1 = self.kwargs['value1'] return Test.objects.filter(**{key1: value1}) The above code filters my Test objects based on only a single key value-pair passed in the get request. I now want to filter on a more than 1 key-value pairs. Eg:- Filter should be : name=john&type_test=algo&count=3 How should I design the api endpoint in django and not make the url too lengthy as well? Can I use a json or map, via request body? I am a beginer to django and api development so any help would be appreciated. -
How to publish app with Django React Native
This is my first time to deploy my app to app store. However, I cannot find the way to deploy Django and React Native app. Do I have to deploy separately? or possible deploy both at same time? Like using EAS or others? I tried EAS but Django file not located inside React Native Expo file. Do I have to move Django file inside expo file? -
How to display in the django template information of a manytomany model
I am practicing django but i am not able to display the following information from the database in the template. I have these 3 models (PURCHASE ORDERS, MOVEMENTS, RECEIPTS): class Ordenes_Compra(models.Model): orden_compra=models.IntegerField(primary_key=True) proveedor=models.ForeignKey(Proveedores, on_delete=models.CASCADE) comedor=models.ForeignKey(Centros, on_delete=models.CASCADE) fecha_documento=models.DateField() fecha_entrega=models.DateField() class Meta(): verbose_name='Orden de compra' verbose_name_plural="Ordenes de compra" class Movimientos(models.Model): movimientos = \[ ('ING', 'INGRESO'), ('SAL', 'SALIDA'), \] estados = \[ ('PRO', 'PROCESADO'), ('ANA', 'ANALIZADO'), ('PEN', 'PENDIENTE'), ('CAN', 'CANCELADO'), \] cantidad_um=models.DecimalField(decimal_places=3, max_digits=20) precio_por_um=models.DecimalField(decimal_places=3, max_digits=20) mat_um=models.ForeignKey(Materiales, on_delete=models.CASCADE, editable=True) orden_compra_mov=models.ForeignKey(Ordenes_Compra,on_delete=models.CASCADE) tipo_movimiento=models.CharField(max_length=3, choices=movimientos, blank=True, null=True) estado_movimiento=models.CharField(max_length=3, choices=estados, blank=True, null=True) class Meta(): verbose_name='Movimiento' verbose_name_plural="Movimientos" class Imagenes_Comprobantes_Moviemientos (models.Model): imagen_factura=models.ImageField(null=True, blank=True) factura=models.CharField(max_length=20) orden_compra_imagen=models.ManyToManyField(Ordenes_Compra) class Meta(): verbose_name='Comprobante' verbose_name_plural="Comprobantes" Each PURCHASE ORDER can have several RELATED VOUCHERS and several VOUCHERS can have different PURCHASE ORDERS. In the template, I am going to show a table with the MOVEMENTS, from which I want to give the information of the PURCHASE ORDERS that are related to that movement and the PROOFS related to that PURCHASE ORDERS: I was thinking of something like this, but it doesn't work and I'm totally lost in what would be the best way to obtain the information of the receipts related to the purchase order related to the movement in the template: THE SECOND FOR IS THE … -
Auto Increment in child model
models.py class Pallet_Mission(models.Model): code = models.AutoField(primary_key=True) load_type = models.CharField(max_length=20,null=True,blank=True) mission_no = models.CharField(max_length=255, null=True,blank=True) class PalletSubMission(models.Model): mission_id = models.CharField(max_length=255,null=True,blank=True) pallet_mission = models.ForeignKey(Pallet_Mission,on_delete=models.CASCADE,related_name='sub',null = True) point = models.CharField(max_length=255,null=True,blank=True) i have a parent and child model look like this. and my output look something like this "code": 52, "mission_no": "test1234", "load_type": "1234", "sub": [ { "id": 75, "mission_id": "s1", "point": null, "pallet_mission": 52 }, { "id": 76, "mission_id": "s2", "point": null, "pallet_mission": 52 } ], } Now my 'mission_id" are inserted manually. I want my child model's "mission_id" to be like auto increment like shows 's1' for the first data 's2' for the second data and so on . And it will reset in another set of data