Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update Django model field by CSV file upload via change_form.html override
Django is still not my superpower, so I hope that some of you could help me to find a way to achieve my goal, which is: I need to find a way to get "Upload file" feature at Django admin change_form.html template. By uploading that file my app would be able to update body of the specific instance of Content model (with fields id, title and body). I already implemented solution for similar problem, which is how to add new objects by clicking custom "Upload csv" button in admin panel. I achieved it by following this solution: I added this in app's admin.py file: from .models import Content class CsvUploadForm(forms.Form): csv_file = forms.FileField() class CsvUploadAdmin(admin.ModelAdmin): change_list_template = "admin/change_list.html" def get_urls(self): urls = super().get_urls() additional_urls = [ path("upload-csv/", self.upload_csv), ] return additional_urls + urls def changelist_view(self, request, extra_context=None): extra = extra_context or {} extra["csv_upload_form"] = CsvUploadForm() return super(CsvUploadAdmin, self).changelist_view(request, extra_context=extra) def upload_csv(self, request): if request.method == "POST": form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): if request.FILES['csv_file'].name.endswith('csv'): try: decoded_file = request.FILES['csv_file'].read().decode( 'utf-8') except: self.message_user( request, "Can not decode the file, please check its content if valid CSV format", level=messages.ERROR ) return redirect("..") content_body = decoded_file content_title = request.FILES['csv_file'].name try: csv.reader(content_body.splitlines()) except: self.message_user( request, … -
Does default isolation level setting in Django depend on database?
I read Isolation level in Django documentation and it says as shown below: Like PostgreSQL itself, Django defaults to the READ COMMITTED isolation level. So, if I use Django with MySQL whose default isolation level is REPEATABLE READ: Is the default isolation level setting in Django also REPEATABLE READ? Or Is the default isolation level setting in Django READ COMMITTED? -
Error when importing models into test.py file, django
I'm trying to create a test.py file for some of my database methods in a current django project. I need to import my models.py file, but the import statement I'm using below (which follows the official Django example) is causing an error. Both test.py and models.py are already in appFolder, so is that the issue? from appFolder.models import Class1,Class2,Class3 Using only 'import models' didn't work when I ran it earlier. How can I resolve this? (I have also been running the file with the command './manage.py test' if that's relevant) -
How to create custom validation within custom model field type?
I am trying to make a school management system where super users who can add new students (and teachers later on) on the database have to also enter the student's courses. However, I want to use validation for different purposes: Students need to take at least and a maximum of 1 option from the English and Math field (which does not need any further validation if left as it is) Students need to take at least 1 science and a maximum of 2 --> Needs validation to ensure courses are not taken twice. Students can pick any 3 courses from Science, Art, and Society, but cannot take the same courses twice. I apologize if this question is silly or for any errors in the code as I started learning django and html 3 days ago to complete a school project. I read the django documentation in hopes for an answer but I couldn't find what I was looking for. class Student(models.Model): student_number = models.PositiveIntegerField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100) class English(models.TextChoices): LANGLIT = 'LL', _('Language and literature') LIT = 'L', _('Literature') english = models.CharField(max_length=2, choices=English.choices, default=English.LANGLIT) class Math(models.TextChoices): AA = 'AA', _('Analysis & Approaches') AI = … -
Problem with permissions on macos when i try to work in django shell
Im open shell with python manage.py shell, import model and try to make response to db (its remote) and have this problem: connection to server at "192.168.0.110", port 5023 failed: could not open certificate file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.crt": Permission denied If i make sudo su i have this problem: OperationalError: connection to server at "192.168.0.110", port 5023 failed: private key file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.key" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root Than i make chmod 600 config/extra/ and restart shell. After this: OperationalError: connection to server at "192.168.0.110", port 5023 failed: private key file "/Users/zadro/Work/urrobot_back_end/config/extra/backdev.key" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root How can i fix this?... -
Refresh Values on Django Template using repeated AJAX calls
I have a django webapp where I want to update a field with random values after every 10 seconds. Here's the code structure: views.py temp_values = [1, 2, 3, 3, 4, 5, 5, 6, 6, 7] def get_temp(): return temp_values[random.randint(0, 6)] def ajax_data(): data = {'temp': get_temp()} json_data = json.dumps(data) return Response(json_data, mimetypes='application/json') template.html <div class="container"> <div class="section"> <div class="col grid_1_of_3"> <h3>Temperature</h3> <input type="checkbox"> On/Off <br> <label>Current: </label><input type="text" placeholder="{{ v }}" disabled="disabled"><br> <form action="" method="POST"> {% csrf_token %} <script src="http://code.jquery.com/jquery-3.0.0.js"></script> <script language="javascript" type="text/javascript"> function updateValue() { $.ajax({ url:"/ajax_data", }); } $(document).ready(function(){ var v = setInterval(updateValue,1000); }); </script> {{ form.as_p }} <button type="submit">Set</button> </form> <img src="{% static 'img/graph.png' %}" alt="graph"/> </div> There is a current temp field & a set temp field (for which I have created a form which posts request on submit button click). However console keeps throwing 404 url not found error. Please let me know where I am I going wrong -
Like button only work when clicked on but cant unlike post object using ajax in Django
I'm trying to work Django with ajax to stop the reload of page when a post object is liked by a user, but somehow when the like button is clicked it update the button as liked, but when i click the button to unlike the post doesn't unlike. I'm wondering how i could do it better to stop this malfunction. why does it only toggle to like but doesn't back to unlike ? My likeview def Addlike(request,post_id): if request.method == 'POST': post = Post.objects.get(id=post_id) is_liked = False if post.like_page_post.filter(id=request.user.id).exists: post.like_page_post.remove(request.user) is_liked = False else: post.like_page_post.add(request.user) is_liked = True return JsonResponse({'is_liked':is_liked,'count_likes':post.like_page_post.all().count()}) Ajax function function likeajax($this) { var id = $this.attr("id"); var count_likes = $('#count_likes'); var like_icon = $('#like_icon'); $.ajax({ headers: {'X-CSRFToken': document.getElementById('csrf').querySelector('input').value}, method: 'POST', url: "{% url 'page:like' page.id %}", dataType: "json", data: { }, success: function (data) { if(data.is_liked) { like_icon.html('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="blue" width="22" height="22" class="dark:text-gray-100" ><path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" /></svg>'); count_likes.text(data.likes_count); } else { like_icon.html('<svg … -
How to reduce inventory when creating a purchase instance in Django?
I'm working on a Django project that is a simple restaurant management system. One of the key functionalities is to record inventory and purchases. I'm looking to add functionality where once I create a Purchase instance, my program automatically reduces the inventory by the amount used in that purchase. I've been scratching my head a bit and poking around the internet but I'm honestly not sure exactly where to start. This is my first Django project so would greatly appreciate a bit of direction. See below for my models.py and views.py. Models.py class Inventory(models.Model): ingredient_name = models.CharField(max_length=30) price = models.DecimalField(max_digits=5, decimal_places=2) units_avail = models.IntegerField() def __str__(self): return self.ingredient_name + " avail: " + str(self.units_avail) def get_absolute_url(self): return "/inventory" class MenuItem(models.Model): menu_item_name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.menu_item_name + " with Price: " + str(self.price) def available(self): return all(recipe_req.enough() for recipe_req in self.reciperequirement_set.all()) def get_absolute_url(self): return "/menu" def cost(self): item_cost = 0 for recipe_req in self.reciperequirement_set.all(): item_cost += recipe_req.ingredient.price return item_cost def profit(self): item_cost = self.cost() item_profit = self.price - item_cost return item_profit class RecipeRequirement(models.Model): ingredient = models.ForeignKey(Inventory, on_delete=models.CASCADE) menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return self.ingredient.ingredient_name + " in " + self.menu_item.menu_item_name def … -
как парсить url картинки с сайта ? python и вывести её в консоль [closed]
<img class="bookkitem_cover_img" src="https://s13.knigavuhe.org/2/covers/40052/1-1@2x.jpg?1" alt="Юдифь"> html -
Hello, I am facing an error I am facing while using Django templates
Heyy, I wanted some help with an error I am facing while using Django templates. I am facing a Template Syntax Error "Invalid block tag on line 77: 'else'. Did you forget to register or load this tag?" <!-- Logged In --> {% if request.user.is_authenticated %} <div class="header__user"> <a href="profile.html"> <div class="avatar avatar--medium active"> <img src="https://randomuser.me/api/portraits/men/37.jpg" /> </div> <p>{{request.user.username}}<span>@{{request.user.username}}</span></p> </a> <button class="dropdown-button"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"> <title>chevron-down</title> <path d="M16 21l-13-13h-3l16 16 16-16h-3l-13 13z"></path> </svg> </button> </div> {% else %} <!-- Not Logged In --> <a href="{% url 'login' %}"> <img src="./assets/avatar.svg" /> <p>Login</p> </a> {% endif %} Can you please help me fix this? Thank you ! -
How would you achieve this Dynamic updating
I have this simple form "Manufacturers" have a DB, "Models" have a DB with a ForeignKey to Manufacturers. There are indoor and outdoor systems which are simply provided in the Models DB FIRST Dynamic updating - This is what I want to happen with the above. When "Indoor Manufacturer" is selected, "Indoor Model" shows relevant records on "Indoor Model". Ditto for "Outdoor Manufacturer" & "Outdoor Model" SECOND Dynamic updating - But to make the form a tad easier, when the Checkbox "Indoor/ Outdoor Unit Same Manufacturer" is clicked, it locks "Outdoor Manufacturer" to what is selected in "Indoor Manufacturer" - it still needs to update "Outdoor Model" selection though I'm not entirely new to Django, but still very much a Beginner. I can manage the First Part using HTMX but then I run into a brick wall with trying to combine the First Part & the Second Part. I suspect I'm reaching the limits of my ability here and may be using HTMX incorrectly, so look for advice on how others would approach this? -
How to prevent my queries from getting out of order when I show them in the template with a nested loop
I am making a query to the database, ordering it by date and then sending it to the template, but it is displayed out of order in the template. I think the problem is the nested loop. When i take out the nested loop it worked but i really need the loop to be there. How can I make it work? This is the query from the view: recibos=grupo.recibos.all().order_by('-fecha_pago') This is the template code: {% if recibos %} <table class="table table-responsive-sm table-sm table-hover datatable"> <thead> <tr> <th>Responsable</th> <th class="text-center">Fecha</th> <th class="text-center">Monto</th> <th class="text-center">Forma de Pago</th> <th class="text-center"></th> </tr> </thead> <tbody> {% for recibo in recibos %} <tr> <td> <div>{{recibo.responsable.nombre}} {{recibo.responsable.apellido}}</div> <div class="small"><span>&nbsp;&nbsp;<i class="fa-solid fa-graduation-cap"></i></span> {% for alumno in recibo.alumnos.all %} {% if not forloop.last %} {{alumno.nombre}}, {% else %} {{alumno.nombre}} {% endif %} {% endfor %} </div> </td> <td class="text-center"> <div>{{recibo.fecha_pago}}</div> </td> <td class="text-center"> <div>${{recibo.importe|floatformat:"2g"}}</div> </td> <td class="text-center"> <div>{{recibo.forma_pago}}</div> </td> <td class="text-center"> <div>botones</div> </td> </tr> {% endfor %} </tbody> </table> {% else %} <br> {% if filtro == True %} <div class="alert alert-warning text-center"> <strong>No hay resultados para este filtro</strong> </div> {% else %} <div class="alert alert-warning text-center"> <strong>No hay recibos para esta familia</strong> </div> {% endif %} {% endif … -
Django migrate Oracle DB
I have a Django App (Python 3.8 // Django 3.2.15) currently using an MSSQL DB Server (with the 3rd Party Microsoft Connector) and would like to migrate it to Oracle. Completely new and empty oracle 19c instance with my own new/empty schema. Connection seems to be working according to manage.py and when migrating I instantly get the Error: Applying contenttypes.0001_initial...Traceback (most recent call last) django.db.utils.DatabaseError: ORA-00900: invalid SQL statement (even though the migrations and contenttype table are created) Anyone got any idea? I have not made any modifications to the migrations and even when running a specific app migration it fails with the same issue... (the only options I use for the DB are the recommended threaded and use_returning_into) -
how to save the user that entered a form in Django?
I have a form in a Django application. I want to save a user with the form and associate that data with the user in the database. This seems like something you should be able to do but I can't find anything in the docs and no information anywhere else. any help would be very much appreciated. -
i don't know if these models are setup correctly for django ecommerce
` from django.db import models from phonenumber_field.modelfields import PhoneNumberField Create your models here. CATGORIES_CHOICE = ( ("Sports"), ("Fashion"), ("Electronics"), ("Fishing"), ("Books"), ("Cosmetics"), ("Games"), ("Pets"), ("Outwear"), ("Lingerie"), ("Medicals") ) ORDER_HISTORY_CHOICE = () class User(models.Model): email = models.EmailField(unique=True) password = models.CharField(max_length=15) phone_number = PhoneNumberField(region="US") address1 = models.TextField() address2 = models.TextField(blank=True,null=True) created = models.DateTimeField(auto_now_add=True) class Store(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=100,default="official store") created = models.DateTimeField(auto_now_add=True) class Product(models.Model): store_id = models.ForeignKey(Store,on_delete=models.CASCADE) #product_id = models.IntegerField(unique=True,max_length=13) title = models.CharField(max_length=110) description = models.TextField(null=True, blank=True) price = models.DecimalField(max_digits=15,decimal_places=2) discount = models.DecimalField(max_digits=2,decimal_places=2,default=0.00) available = models.IntegerField() category = models.CharField(choices="",max_length=20) # image = models.ImageField(upload_to="images") condition = models.CharField(choices="",max_length=20) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) @property def sales_price(self): return "%f" %(float(self.price * (1 - self.discount))) class CartItem(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) order_number = models.IntegerField(unique=True,default=7) ordered = models.BooleanField(default=False) items = models.ManyToManyField(CartItem) created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() class Review(models.Model): created_by = models.ForeignKey(User,on_delete=models.CASCADE) product_id = models.ManyToManyField(Product,on_delete=models.CASCADE) rating = models.DecimalField(max_digits=2,decimal_places=1,default=0.0) label = models.CharField(max_length=100) comment = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class BlogPostInfo(models.Model): title = models.CharField(max_length=100) written_by = models.CharField(max_length=70) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Saved(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) products = models.ManyToManyField(Product) class History(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) products = models.ManyToManyField(Product) status = models.CharField(choices="",max_length=20) ` -
django view function is not showing data of print command
i have make a function in django view and its working fine but there are print functions in it and it is not showing in terminal before it is showing perfectly but no data is printing in terminal but function is working fine for example def uplink(request): print("******************") a=5 b=6 c=a+b print(c) this is just a example function is doing the operation and stored the data but not showing print command datai have never faced this issue -
Django i18n, using template inside python string, how to translate
I need to translate some emails in a django app and I was wondering what is the best way to tag for translation something like this: subject_template = ( 'Enlèvement programmé le {{ pickup.pickup_date|date:"l d F"|lower}} {{ pickup.timeslot }} - ' + "{{ pickup.display_id }}" ) This is a part on an email in a pythons script, however template are used inside the string, so I cannot really use gettext isn't it ? Maybe one of you ended up in a similar situation, if you have a solution that would be neat. -
Iterate through a complex dictionary with python
I would like to browse this dictionary especially the lines sub-array my_dict= { "alla": "koko", "messages": [ { "env": "dlo", "detail": "cons" } ], "commandes": [ { "comande_numero": "lkm02", "date": "14/10/2022", "lignes": [ { "product": "mango", "designation": "04 pacquets of mango", "quantite": 14 }, ...... ] } ] } I tried all_product=my_dict['commandes'] for one_ligne in all_product.lignes: // my code but i have an error, So how to browse the rows sub-array located at the dictionary level -
Integration the bank payment system
I am trying to integrate the Bank's payment system on my Django-based website. As it said in documentation, I need to send parameters to their server (and then the new window should appear and the client should fill his card credentials there). Documentation (part 1): Documentation (part 2): Documentation (part 3): I am new in integration such services (payment) and need some help or broad explanation what to do, why do to that, and how. Additionally, I was pretty sure that the following code wouldn't work fine but why. import requests def send_request(): url = 'https://ecomm.pashabank.az:18443/ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.184.1.132&msg_type=SMS' response = requests.post(url) print(response) send_request() causes raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='ecomm.pashabank.az', port=18443): Max retries exceeded with url: /ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.172.184.123&msg_type=SMS (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)'))) Overall, I need help of everything happening behind the scenes. Huge thanks in advance guys! Note: I have also received some certifications from bank (I assume to assure the connection safety). But how I use it and when? -
how to append to list below example given and output also?
This is the data: data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}] data2=[{"hobby":"football","food":"any"},{"hobby":"basketball","food":"any"}] list1=[] expected Output: list1:[{"name":"vikash","roll":39,"hobby":"football","food":"any"},{"name":"kumar","roll":3,"hobby":"basketball","food":"any"}] Please help me! -
File Browser-File,Media Management
Hi everyone my question is how can I write file browser code or is it writeable im new on Django and I making control panel and how can I add or write to control panel -
Role choice field data ins't saved for UserRegsitrationForm django
The following error message appears after I submit the SignUpform: 'NoneType' object has no attribute '_inc_path' This issue is related to the role choice field of my CustomUser model. The models function perfectly without the role field and all forms are displayed and saved correctly. I suspect my choice field form does not pass/save correctly the input values to the CustomUser model. Any input would be highly appreciated. Models.py: class CustomUser(AbstractUser): display_name = models.CharField(verbose_name=("Display name"), max_length=30, help_text=("Will be shown e.g. when commenting")) ... country = CountryField(blank=True, null=True) ... role = models.CharField(choices = ROLES, max_length = 50, default = "regular_user",) ... class Meta: ordering = ['last_name'] def get_absolute_url(self): return reverse('account_profile') def __str__(self): return f"{self.username}: {self.first_name} {self.last_name}" ``` forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label=_("First name")) last_name = forms.CharField(max_length=30, label=_("Last name")) display_name = forms.CharField(max_length=30, label=_("Display name"), help_text=_("Will be shown e.g. when commenting.")) role = forms.ChoiceField(choices = ROLES, label="Role", initial='Regular_user', widget=forms.Select(), required=True) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.display_name = self.cleaned_data['display_name'] user.role = self.cleaned_data['role'] user.save() users/create.html: {% extends "wagtailusers/users/create.html" %} {% block extra_fields %} ... {% include "wagtailadmin/shared/field_as_li.html" with field=form.role %} ... {% endblock extra_fields %} settings.py: AUTH_USER_MODEL = 'userauth.CustomUser' WAGTAIL_USER_CREATION_FORM ='userauth.forms.WagtailUserCreationForm' WAGTAIL_USER_EDIT_FORM = 'userauth.forms.WagtailUserEditForm' WAGTAIL_USER_CUSTOM_FIELDS = ['display_name',... 'role', … -
django-pytest ModuleNotFoundError
I'm running django==4.0.7 and python==3.10 and django-pytest==0.2.0. When I run my app using the command python manage.py runserver it works fine. But when I run the command pytest I get module not found error. in the settings.py file I've imported the following: from corsheaders.defaults import default_headers so when i run pytest i get the following error. from corsheaders.defaults import default_headers ModuleNotFoundError: No module named 'corsheaders' Whereas it is corsheaders is already installed django-cors-headers==3.13.0. my pytest.ini [pytest] DJANGO_SETTINGS_MODULE = app.settings python_files = tests.py test_*.py *_tests.py What is going wrong? How could I resolve it? -
Django: Filtering items in generic.ListView
I'm creating a game website and i have these models for games: class Game(models.Model): accountant = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='games') title = models.CharField(max_length=50) bank_money = models.IntegerField() player_starting_money = models.IntegerField() golden_card_amount = models.PositiveIntegerField( validators=[ MinValueValidator(100), MaxValueValidator(1000) ] ) now i want every user to see their own games at dashbard: class DashboardView(mixins.LoginRequiredMixin, generic.ListView): template_name = 'games/dashboard.html' model = models.Game how can i do this (show every user their own games, not all games)? -
Displaying in PDF unique values and count of each unique values
I am having a hard time displaying in pdf all unique values of the category and subcategory versus count of each category under the three tight columns which are the severity. Severity has three options (in Bold). The PDF should have four columns: Accident Causation | Accident Causation Sub Category | Damage to Property | Fatal | Non-Fatal Views def fetch_resources(uri, rel): path = os.path.join(uri.replace(settings.STATIC_URL, "")) return path def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class GenerateInvoice(View): def get(self, request, *args, **kwargs): try: incident_general = IncidentGeneral.objects.filter(user_report__status = 2).distinct('accident_factor') #you can filter using order_id as well except: return HttpResponse("505 Not Found") data = { 'incident_general': incident_general, } pdf = render_to_pdf('pages/generate_report_pdf.html', data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Accident Causation" #%(data['incident_general.id']) content = "inline; filename='%s'" %(filename) content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") Models class AccidentCausation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.category class AccidentCausationSub(models.Model): accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.CASCADE) sub_category = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.sub_category class IncidentGeneral(models.Model): …