Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Migrations Error : django.db.migrations.exceptions.NodeNotFoundError
I tried to add a new app in my django project and when I tried to make migrations the following error occured: django.db.migrations.exceptions.NodeNotFoundError: Migration masters.0001_initial dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') Now I checked why this error occured and I found out that it's because in Masters app I have this: dependencies = [ ('auth', '0011_update_proxy_permisssions'), ] I am not sure where this file exists, also I tried checking the last deployed version of the app and it has the same dependency but I couldn't find the file in the previously deployed version too. How can I rectify it ? -
Python Anywhere website no longer serving my products images
I have a deployed e-commerce site using pythonanywhere and the product images are no longer being served: You can visit the site to see what I mean at: www.ultimatecards5.com When I run the project locally it works perfectly: The code bases for both the deployed website and the local version are exactly the same. My settings.py: import os from dotenv import load_dotenv load_dotenv() # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = str(os.getenv('SECRET_KEY')) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'shop.apps.ShopConfig', 'search_app.apps.SearchAppConfig', 'cart.apps.CartConfig', 'stripe', 'crispy_forms', 'order.apps.OrderConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize' ] 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', ] ROOT_URLCONF = 'perfectcushion.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search_app', 'templates/'), os.path.join(BASE_DIR, 'cart', 'templates/'), os.path.join(BASE_DIR, 'order', 'templates/') ], #to make the apps templates available throughout the project 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'shop.context_processors.menu_links', #adding the location of our context_processor.py file 'cart.context_processors.counter', … -
drf serializer data not showing all fields data properly
id field and name field not showing in result. in models.py: class Group(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) admin = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ManyToManyField(User, related_name='groups_user') def __str__(self): return self.name in serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') class GroupSerializer(serializers.Serializer): admin = SimpleUserSerializer() class Meta: model = Group fields = ('id','name','admin') views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def getSomeGroup(request): allGroup = Group.objects.all().count() randomGroupId = random.sample(range(allGroup), 3) randomGroup = Group.objects.filter(id__in=randomGroupId) serializer = GroupSerializer(randomGroup, many=True) #print(serializer) return Response(serializer.data) the result comes like this: [{"admin":{"id":1,"first_name":"asif","last_name":""}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}}] why id and name field not showing? -
How to merge two id's from same model in django?
I have a Model Market class Market(models.Model): market = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_market = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_market', on_delete=models.SET_NULL, default=None) def __str__(self): return str(self.market) I want to merge two id's EX: 258 and 855 of the Market model. I tried to merge using union, update but couldn't able to do it. -
Django filtering over a tsvector column
My Django application has a backend postgres database with a tsvector column that whose values are already computed and indexed. I want to use Django's ORM to do a full text search over that column with a query that would look something like this: SELECT [fields] FROM [table] WHERE tsvector_column @@ plainto_tsquery('TEXT HERE'); The problem I am running into is, when I use annotate and SearchVector, Django seems to re-to_tsvector over the tsvector column, resulting in an error. This is what I am doing: Posts.objects.annotate(search=SearchVector('THE_TS_VECTOR_COLUMN'),).filter(search='SEARCH TEXT') How would one do this in Django? Thanks! -
How to make it such that if there are errors in the form, all the data I have keyed into the field remains and only the error pops out
How to make it such that if there are errors in the form, all the data I have keyed into the field remains and the error shows for me to edit what I need to edit. Because it is very user-unfriendly if people press submit, and everything they have previously typed has to be retyped again due to an error that caused them to need to submit the form again. just like when we post a stackoverflow question, if there are errors in our question eg time limit, whatever we have typed previously remains Let me know if you require more code. html <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <button class="submit-button btn btn-lg btn-primary btn-block" type="submit">Submit</button> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} views.py def create_blog_view(request): context = {} user = request.user if request.method == 'POST': form = CreateBlogPostForm(request.POST or None, request.FILES or None) if form.is_valid(): obj.save() return redirect('HomeFeed:main') else: context['form'] = form return render(request, "HomeFeed/create_blog.html", context) -
Django Fargate. The requested resource was not found on this server
I have seem The requested resource was not found on this server, like a thousand times but none of the awnser match my problem. I made this app from statch, and add a Dockerfile for it. FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /www COPY requirements.txt /www/ RUN pip install -r requirements.txt COPY . /www/ EXPOSE 80 CMD [ "python", "manage.py", "runserver", "0.0.0.0:80" ] Then i run this: docker build -t pasquin-django-mainapp . docker run pasquin-django-mainapp I did that in my local environment, not woking. Y push this Dcokerfile to ECR and then use it in ECS + Fargate, same bada result. I dont know what else todo. Somebody, help! thanks! ps: From docker-compose works just marvelous! -
How can I run Django server on a real server?
I am using VPS ssh server and I have in it a Django project. But the problem is that the command python3 manage.py runserver runs server localy. So if I have finished my project and want to post it on internet, what is the command? -
How to serve media files in production with Django and Heroku?
I just Uploaded my Django Blog to Heroku, and in the Blog I have a members app where users can create an account and upload an profile picture. But I have a problem each time I push a change to the app, by heroku git, all the media files, and therefore the profile picture goes away. What Can I do to preserve those media files? -
django forms not showing checkboxes
this is how my forms.py is class CreateMedicalRecordForm(forms.ModelForm): class Meta: model = MedicalRecords fields = ("title", "file", "doctor", "patient", "doctor_access", "general_access") widgets = { "title": forms.Textarea(attrs={"rows": "", "class": "form-control"}), "file": forms.FileInput(attrs={"class": "form-control col-md-9"}), "doctor": forms.Select(attrs={"class": "form-control col-md-9"}), "patient": forms.Select(attrs={"class": "form-control col-md-9"}), "doctor_access": forms.CheckboxInput(attrs={"class": "checkbox-toggle"}), "general_access": forms.CheckboxInput(attrs={"class": "checkbox-toggle"}), } labels = { "title": "Description (Optional)", "patient": "Self or Relative", "general_access": "General Access For Record", "doctor_access": "Doctor Access For Record", } in template checkboxes are not showing it just get the Label and the checkbox is invisible, no matter how I'm using as form.as_p or loop through the form fields still the same result(not showing). -
How to use Explainx library in django rest framework. Can anynone please help me
I want to use explainx library from explainX.ai (ARTIFICIAL INTELLIGENCE) in django rest framework import explainx i really waant to use it in django but i didnt know how to use it in django... please help me -
Hosting multiple Django instances on a VPS
I'm moving away from WordPress and into bespoke Python apps. I've settled on Django as my Python framework, my only problems at the moment are concerning hosting. My current shared hosting environment is great for WordPress (WHM on CloudLinux), but serving Django on Apache/cPanel appears to be hit and miss, although I haven't tried it as yet with my new hosting company. - who have Python enabled in cPanel. What is the easiest way for me to set up a VPS to run a hosting environment for say, twenty websites? I develop everything in a virtualenv, but I have no experience in running Django in a production environment as yet. I would assume that venv isn't secure enough or has scalability issues? I've read some things about people using Docker to set up separate Django instances on a VPS, but I'm not sure whether they wrote their own management system. It's my understanding that each instance Python/Django needs uWSGI and Nginx residing within that virtual container? I'm looking for a simple and robust solution to host 20 Django sites on a VPS - is there an out of the box solution? I'm also happy to develop one and set up … -
Django Rest Framework and Knox Login view works with Postman but returns 400 with Vue.js
I created a backend API using Django, django-rest-framework and Django-rest-knox, I am also using Vue.js for my frontend. Serializers.py class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Invalid Details.") Views.py class LoginAPI(generics.GenericAPIView): authentication_classes = [BasicAuthentication] permission_classes = [permissions.AllowAny] serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) Urls.py urlpatterns = [ path('api/login/', LoginAPI.as_view(), name='login') ] Vue.js action in store.js const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { username: { username: authData.username }, password: { password: authData.password } } } fetch(`${baseURL.domain}/login/`, requestOptions) .then(response => response.json()) .then(response => { console.log('Request Sent', response) localStorage.setItem('user', response.token) // store the token in localstorage }) .catch(err => { localStorage.removeItem('user') // if the request fails, remove any possible user token if possible }) }) The problem with this is that the code works very fine when I try it with postman, but whenever I run the API in the browser, it returns a 400 error. POST http://127.0.0.1:8000/api/login/ 400 (Bad Request) Error: Request failed with status code 400 -
how to get sum row into xls by xlwt
I have a tuple like t = ((a,b,1,2),(a,b,3,4),(a,c,1,3),(c,d,3,6)) I used xlwt's wb to write a .xls file. But now I neeed add a sum row below like: C1 | C2 | C3 | C4 a | b | 1 | 2 a | b | 3 | 4 a | c | 1 | 3 c | d | 3 | 6 total: | 8 | 15 How to do this? -
Can Django apps have separate localisation domains?
I'm building a group of websites that will each share two common apps. I want to be able to localise the text in each site, as per client requirements. Using i18n / l10n localisation is working well for this, but I'd like to separate out the translation strings for each app to make it both easier to manage, and prevent string clashes between apps. In other environments (e.g. WordPress) I can specify a separate domain for each app. From what I can tell, I've only got the domains 'django' (for all server-side code) and 'djangojs' (for browser JS). Is there some way of specifying a different domain for each app, so that I can split them appropriately? Sure, I can abuse the l10n context with pgtext() but that means I lose the ability to manage contextual differences within each app. I'd much rather use domains, which is what they're meant for, and keep contextual markers for their intended purpose. -
Django- How to check formset field values in ModelForm init?
I'm new to Django. I can check form data using if field in self.data and grab field value like product_id = int(self.data.get('product')) that's all I know. I really don't have any idea how to check dynamic formset data and grab field value in __init__ method. I did a lot of searching and didn't understand how to do it. Please help me to get out of it, I will be grateful. class PurchaseOrderForm(forms.ModelForm): class Meta: model = PurchaseOrder class PurchaseOrderDetailsForm(forms.ModelForm): class Meta: model = PurchaseOrder_detail fields = ('product', 'product_attr', 'order_qnty', 'recvd_qnty', 'amount_usd', 'amount_bdt', 'unit_price', 'sales_price', 'commission_price') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'product' in self.data: product_id = int(self.data.get('product')) self.fields['product_attr'].queryset = ProductAttributes.objects.filter(product_id=product_id) PurchaseOrderItemsFormset = inlineformset_factory(PurchaseOrder, PurchaseOrder_detail, form=PurchaseOrderDetailsForm, fields='__all__', fk_name='order', extra=1, can_delete=True) Rendered Forms: <table class="table"><input type="hidden" name="PurchaseOrder-TOTAL_FORMS" value="3" id="id_PurchaseOrder-TOTAL_FORMS"> <input type="hidden" name="PurchaseOrder-INITIAL_FORMS" value="2" id="id_PurchaseOrder-INITIAL_FORMS"> <input type="hidden" name="PurchaseOrder-MIN_NUM_FORMS" value="0" id="id_PurchaseOrder-MIN_NUM_FORMS"> <input type="hidden" name="PurchaseOrder-MAX_NUM_FORMS" value="1000" id="id_PurchaseOrder-MAX_NUM_FORMS"> <thead> <tr> <th>Product</th> <th>Product attr</th> <th>Order Qnty</th> <th>Recv. Qnty</th> <th>Amount ($)</th> <th>Amount (৳)</th> <th>Cost Price</th> <th>Sale Price</th> <th>Comm. Price</th> <th>Delete</th> </tr> </thead> <tbody> <tr class="formset_row-PurchaseOrder dynamic-form"> <td><input type="hidden" name="PurchaseOrder-0-order" value="1" id="id_PurchaseOrder-0-order"> <input type="hidden" name="PurchaseOrder-0-id" value="1" id="id_PurchaseOrder-0-id"> <div id="div_id_PurchaseOrder-0-product" class="form-group"> <div class=""><select name="PurchaseOrder-0-product" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="" class="setprice product select2widget form-control django-select2 select2-hidden-accessible" style="width:100%" required="true" id="id_PurchaseOrder-0-product" data-select2-id="id_PurchaseOrder-0-product" tabindex="-1" aria-hidden="true"> … -
New Entry of Data overwrites all past entries in column , how do i correct this?
Using Django, when the User fills out the webform, one of the saved Data overwrites all pass entered data for that column. How do i stop it from overwriting it the other past data for that column ? Models.py file below, from django.db import models from django.utils import timezone from django.contrib.auth.models import User class ansquestions(models.Model): m_invested = models.CharField(max_length=100) p_return = models.CharField(max_length=100) years = models.CharField(max_length=100) inflation_yes_no = models.CharField(max_length=100) date_answered = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) results = models.ForeignKey('results', on_delete=models.CASCADE, null=True) # null=True def __str__(self): return self.m_invested + ' ' +self.p_return class results(models.Model): # second table for output and add other data from ansquestions table as foreign keys r_output = models.CharField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.r_output # Important : this dunder method above __str__(self) for r_ouptput was how the actual r_output value gets displayed on admin interface. important since it was foreign key Here is the 2nd View Function, This is where i'm having the trouble with the latest.objects('id') command, i found this as a solution, but it's overwriting all of the rows for that "Results" Column def formulafv(request): if makeup_infl=='no': i_return = (float(perc_r)) elif makeup_infl=='yes' and int(years_i)<=5: i_return = (2+float(perc_r)) elif makeup_infl=='yes' and int(years_i)>5 and int(years_i)<=9.99 … -
How to connect Django media storage to Dokku persistence storage?
I deployed my Django app on server with Dokku. Staticfiles seems to be working as CSS is perfectly fine in admin dashboard, I can upload file but I cannot reach the file. I discovered that I should be using Dokku persistence storage anyway. So I set it up (I suppose). Then I setup my Nginx. Before Nginx, Django was showing "page not found" for the file path. Now, I get "The page you were looking for doesn't exist.". How can I correctly connect my app to persistence storage? Static and media settings on Django # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR / "staticfiles") # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = [str(APPS_DIR / "static")] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] # MEDIA # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR / "media") # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = "/media/" Nginx media.conf settings location /media/ { alias /var/lib/dokku/data/storage/dokkuappname:/media; } dokku storage:list dokkuappname result dokkuappname volume bind-mounts: /var/lib/dokku/data/storage/dokkuappname:/media -
use variable in django DB subquery
I have been working on this but I can't seem to get there. I would like to make a query that will do the calculations in the database, store the results in variables I can pull back into Django environment. Objective is: qs = TimeLog.objects.filter(user_id=1, date__gte='2021-01-01').values() run a subquery on qs to calculate: 2a) Sum the hours_worked for the year(year_hours) 2b) Sum the wages for the year (year_wages) 2c) Sum the hours_worked for the the current month (month_hours) 2d) Sum the wages for the current month (month_wages) Here are some of things I have been trying qs.aggregate(Sum('wages')) qs.aggregate(year_wages=(F('time_worked') * F('hourly_rate'))) qs.filter(date__lte='2021-01-01').aggregate(Sum('wages'), Sum('time_worked')) Is there a way to do this in one query using DB expressions like F expression or Q objects or any other way so that it is handled by the DB and pull the variables (year_hours, month_hours, year_wages, month_wages) back in Django environment. Thanks in advance. NOTE I'm using PostgreSQL. -
Should I make 2 Form for readonly and update Django
I have a form for an account and I wish to make it ReadOnly and Updatable. Should I make a separate form for readonly then load them create a separate view? Or is there a DRY solution for this? -
How to override admin's password change view logic?
Django docs says to use path('accounts/', include('django.contrib.auth.urls')) but I don't want it to have "accounts/" url instead I only want it to remain as "admin/". However I tried overriding it as seen like so # project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('admin/password_change/', CustomPasswordChangeView.as_view(), name='password_change'), ] from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class CustomPasswordChangeView(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('password_change_done') template_name = 'registration/password_change_form.html' title = _('Password change21312312313132133') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user print(kwargs['user']) print(self.success_url) return kwargs def form_valid(self, form): form.save() # Updating the password logs out all other sessions for the user # except the current one. update_session_auth_hash(self.request, form.user) return super().form_valid(form) I tried to change the title variable value so that I would see if it worked but it doesn't seem to use the custom view that I've made. Any idea why and how to fix it? -
Django admin postgres Error: must appear in the GROUP BY clause
I have below django model, class DetectionJob(models.Model): """A detector job """ owner = models.ForeignKey(Account, on_delete=models.CASCADE) media = models.ForeignKey(UploadedMedia, related_name='jobs', on_delete=models.CASCADE) detector_api_id = models.CharField( max_length=36, blank=True, help_text="Detection API Task ID (UUID)", ) FACE_MANIPULATION = 'face_manipulation' And below django admin page, class DetectionJobAdmin(admin.ModelAdmin): readonly_fields = ('created_at', 'updated_at') admin.site.register(DetectionJob, DetectionJobAdmin) I am keep getting below error, column "detector_detectionjob.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "detector_detectionjob"."id", "detector_detectionjob"... I am using postgres as database. There are multiple links on which people ask about similar error but I did not find anything relevant to my problem. Kindly advise what I am doing wrong? -
How can I get the username of the logged in user in Django?
I'M new to Django, looking to get first name and last name of the logged-in user in Django, login method am using LDAP authentication. when i login as admin i was able to see the LDAP user in User information tab. Tried request.user.first_name didn't work, is there any other method to get the details? -
How to deal with Nan Values in Postgresql with Django REST API
I have copied a pandas dataframe to PostgreSQL, Now the DB has Nan Values entered by the df, this is easy to solve in pandas but i was wondering how to do this in a DB as i have a huge DB and dont want to again write data to DB. The Django REST Framework is throwing the error 'Out of range float values are not JSON compliant: nan'. I'm using React at the frontend. -
Django model instance of abstract model class raises error when calling super()
I have an abstract model: class CustomModel(models.Model): update = True class Meta: abstract = True def delete(self, *args, **kwargs): try: super().delete(*args, **kwargs) except models.ProtectedError as e: protected_objects_to_return = '' first = True for protected_object in e.protected_objects: if not first: protected_objects_to_return + '/' first = False protected_objects_to_return = protected_objects_to_return + "[{}]{}".format(protected_object._meta.verbose_name, protected_object) raise CustomValidation(_("No fue posible eliminar el registro porque existen registros dependientes: {}".format(protected_objects_to_return)), self.__class__.__name__, status.HTTP_400_BAD_REQUEST) And a model class derived from the abstract class: class Family(CustomModel): name = models.CharField(max_length=100, unique=True, verbose_name=_("Nombre de Familia")) code = models.CharField(max_length=10, verbose_name=_("Clave")) commission = models.PositiveIntegerField(null=True, blank=True,default=0, verbose_name=_("Comisión")) length_field = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Longitud de Campo")) type_field = models.CharField(max_length=20, choices=FIELD_TYPE_CHOICES,default='ALPHANUMERIC', verbose_name=_("Tipo de Campo")) commission_type = models.CharField(max_length=30, choices=COMISSION_TYPE_CHOICES,default='FIXED_COMMISSION', verbose_name=_("Tipo de Comisión")) is_commission = models.BooleanField(default=False, verbose_name=_("Tiene Comisión?")) tabulator = models.OneToOneField(Tabulator, null=True, blank=True, on_delete=models.PROTECT, related_name='family', verbose_name=_("Tabulador")) product_or_service_sat = models.ForeignKey(ProductServiceSAT, null=True, blank=True, on_delete=models.PROTECT, related_name='families', verbose_name=_("Producto o Servicio SAT")) unit_of_measure_sat = models.ForeignKey(UnitOfMeasureSAT, null=True, blank=True, on_delete=models.PROTECT, related_name='families', verbose_name=_("Unidad de Medida SAT")) is_active = models.BooleanField(default=True, verbose_name=_("Esta Activo?")) code_tc = models.PositiveIntegerField(null=True, blank=True, verbose_name=_("Código de Migración")) class Meta: verbose_name = _("Familia") verbose_name_plural = _("Familias") def __str__(self): return "[{}] {}/{}".format(self.id, self.name, self.tabulator) def save(self): if self.is_commission: if self.tabulator is None: self.tabulator = self.create_tabulator(self.name, self.commission_type) super().save() def create_tabulator(self, name, commission_type): tabulator = Tabulator(name=name, commission_type=commission_type) tabulator.save() return tabulator The …