Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-q Scheduled tasks not running properly
I am using Django-q schedulers to create scheduled task to run on every weekend. But whenever i am running my python development server and qcluster we are encountered with two issues-: i) creating two tasks entries in django_q_schedule model after running development server and qucluster ii) Instead on executing on the scheduled time, the scheduler executes its task immediately as qcluster starts then changes its next_run() time to the weekend time. Following is the code snippet i am using -: # Django-Q Cluster Q_CLUSTER = { 'name': 'Name', 'max_attempts': 1, 'retry': 14400, 'orm': 'default' } In my models.py -: from django_q.models import Schedule Schedule.objects.create(func='func()', schedule_type=Schedule.CRON, repeats=-1, cron='25 23 * * 6' ) Please help if anyone having any idea...... Thanks in advance. -
Django Nested Serializer - Understanding why two similar but different approaches have major performance difference
I am trying to use Nested Serializers by two approaches, however both the approaches have a major performance difference even though they have the same number of SQL queries to the database and are similar. I want to understand why this is happening Note I have used a DynamicFieldsModelSerializer to serialise only the necessary fields class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be serialized. Increases speed as you can omit fields that are not needed to be serialized """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) Approach 1 Serializer class Std_Mast_Serializer(DynamicFieldsModelSerializer): item_mast = Item_Mast_Serializer(fields=['id','code','name','pkg','rate','print_order']) installation_mast = Installation_Mast_Serializer(fields=['id','name_short','name_long']) class Meta: model = Std_Mast fields = '__all__' Django Silk - Performance Approach 2 Custom Related Field class NestedField(serializers.RelatedField): def __init__(self, **kwargs): self.serializer = kwargs.pop('serializer', None) self.serializer_fields = kwargs.pop('fields', None) if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer): raise TypeError(f'{self.serializer} is not a valid serializer … -
How to upload a file with lowercase columns in django
I have an upload thro' django-import-export. I have a department column for whose values I'd like to be converted to lowercase. I can't figure out how to do this. Please assist if you can. Here is the view for uploading the file. class uploadBooks(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadBooksForm() self.context['form'] = form return render(request,'libman/upload_books.html',self.context) def post(self, request): school_id = request.user.school.id#Gets the currently logged in user form = UploadBooksForm(request.POST , request.FILES) data_set = Dataset(school = request.user.school) if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportBooksResource(school_id)#Imports for the logged in user's school if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_books') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Books uploaded successfully.') else: self.context['form'] = UploadBooksForm() return render(request, 'libman/upload_books.html', self.context) -
How to handle the rollback of transaction atomic if the transaction fails
Hey i have this following transaction atomic insert query i want to delete the instance of Check Model on the rollback of this atomic transaction from django.dispatch import receiver from django.db.models.signals import post_save from check.models import Check, CheckSheet from django.db import transaction @receiver(post_save, sender=Check) @transaction.atomic def create_checksheets(sender, instance, created, **kwargs): if created: start_number = instance.start_number sheet_count = instance.sheet_count for i in range(sheet_count): check_sheet = CheckSheet.objects.create( batch_check_id=instance.pk, check_number=start_number+i ) -
is postgresql + solr a good idea for a web crawler + search engine?
I am building something like a search engine, with django. The webscraping part is handled by scrapy, with broad web crawlers running in parallel. They normalize the urls found and extract keywords from webpages, before storing them into a postgresql database. Postgres has excellent support from django. In order to actually handle the "searching" part, I am using apache solr to build indexes and efficiently retrieve data. Are there any downsides to this approach? Implementing nosql is going to be very hard, because django does not natively support nosql (except for mongodb which has third party support). What are my options? Can I use postgres or would I need to change my tools? The data collected by the crawler is expected to increase a lot as time progresses - there is no hard limit. The crawler indexes the open web. -
is there any way to use cryptography in web application
I want to develop web application which implies cryptography. can I apply cryptography algorithms like AES, DES, RSA techniques for encryption and decryption on web project? If yes what technologies should I use? -
Django CustomUser make emailfield a reference
In my Django application, I have a Person object and a User object. All of my Persons have e-mail addresses, but not all of them are also Users. Therefore, I'd like to not copy myself by adding an email field to my User model that simply contains the same as User.person.email, and I'd rather have it so that when User.email is called, it tunnels to User.person.email. I was wondering if there was a simple solution to this that I haven't found yet, that also works for authentication, for example. I've tried setting EMAIL_FIELD and USERNAME_FIELD to 'person.email', which doesn't work, and I've tried setting a property like such: @property def email(self): return self.person.email None of these worked for me. -
Django FileField store Keras .h5 file
I am trying to store a trained Keras model within a Django model FileField. Since Keras is not pickleable, I used the .h5 file format (https://www.tensorflow.org/guide/keras/save_and_serialize) to store the keras model. So basically just: kerasmodel.save('temp.h5') dat = open('temp.h5', mode='r') myFile = File(dat) mymodel.content.save('test', myFile) mymodel.content is the Django model FileField This causes the error: UnicodeDecodeError at /model/ 'charmap' codec can't decode byte 0x90 in position 1928: character maps to "undefined" I really dont care if Django can read this file or not, I just want to save it for later purposes. Since I can easily upload the file manually via the Django admin page to the model, it should be feasible. Thanks in advance -
The current URL didn't match any of these
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 … -
Django password reset link does not work - "A {% csrf_token %} was used in a template, but the context did not provide the value"
I am trying to implement the built-in password reset function from Django. I have implemented a microsoft authenticator and have succesfully managed to get my website to send a password reset email. However, when I click the link in the password reset email, my website automatically disconnects. In the error log, I get the following message: /usr/lib/python3.7/site-packages/django/template/defaulttags.py:63: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. urls.py path('admin/', admin.site.urls), path('', include('myapp.urls')), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_reset_form/', auth_views.PasswordResetView.as_view(), name='password_reset_form'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change_done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), password_reset_email.html {% csrf_token %} Someone asked for password reset for email {{ email }}. Follow the link below: {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} password_reset_confirm.html {% block content %} {% csrf_token %} {% if validlink %} <p>Please enter (and confirm) your new password.</p> <form action="" method="post"> {% csrf_token %} <table> <tr> <td>{{ form.new_password1.errors }} <label for="id_new_password1">New password:</label></td> <td>{{ form.new_password1 }}</td> </tr> <tr> <td>{{ form.new_password2.errors }} <label for="id_new_password2">Confirm password:</label></td> <td>{{ form.new_password2 }}</td> </tr> <tr> <td></td> <td><input type="submit" value="Change my password" /></td> </tr> </table> … -
JSON file upload in Django without saving
I want to upload, process and discard a JSON file without saving it in a database. views.py parser_classes(['FileUploadParser']) @api_view(['POST']) def upload_file(request): file = request.FILES.get('file') # process the file return JsonResponse('status':'successful') urls.py urlpatterns = [ path('api/upload_file/', views.upload_file), ] I am setting the header as Content-Type: multipart/form-data Then it is showing the error "Multipart form parse error - Invalid boundary in multipart: None" What is the correct way of uploading a JSON file in DRF ? Python version : 3.6.9 Django version : 3.2.3 -
Why “accounts/login/?next=/” is coming in url of Django on local development server ? | Way to remove “accounts/login/?next=/” from the url
Why “accounts/login/?next=/” is coming in url of Django on local development server ? | Way to remove “accounts/login/?next=/” from the url . I have used class based views and used LoginRequiredMixin. Can anyone tell me why the path changes from /login to accounts/login/?next=/ path('login/', CustomLoginView.as_view(), name='login'), -
How to get tasks id of Django Periodic Task Object [django-celery-beat]
I'm new using Django and celery. I'm using django admin panel to launch the task directly by selecting each individual PeriodicTask model object. I need to get the ID of the task selected. enter image description here I have something like this: from django_celery_beat.models import PeriodicTask get_task = PeriodicTask.objects.get(id=[NumericID]) -
nginx django gunicorn 404 static file not loading
I have been trying to solve this error for almost 13 hours, looking for thousands of stackoverflow questions and questions of other communities but I still can't find the answer. What I'm trying to do is solve nginx not serving static files. as I said on the top, I tried thousands of answers and none of them seem to work for me. I post only the scripts in nginx /sites-available/ because I think that is the primary script for this question. server { listen 80; server_name localhost 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static { autoindex on; alias /home/ngx/pid/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I use gunicorn for loading django and also the frontend is made with react so without main.js I can't do anything. ngx is not a default user - I made it and also I followed this DigitalOcean tutorial.(Although I didn't follow all of them - I edited after reading answers by other people. Directory /home/ngx/pid (django root) ㄴ diary (project root - settings.py, wsgi.py etc.) ㄴ djenv (virtualenv) ㄴ frontend (react) ㄴ manage.py ㄴ static (made by python3 manage.py collectstatic) Error URL: http://example.com/static/css/index.css http://example.com/static/frontend/main.js <- React … -
How to annotate a Django QuerySet with a custom Function?
I need to annotate a queryset using a custom function agr_suitable_code on a model field. which looks like this def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') def agr_suitable_code(on_distro_code): upper_str = on_distro_code.upper() return strip_accents(upper_str) nothing special here, the function takes a string and returns it with some changes. Then I try to annotate with it as the following query cannot be achieved without this agr_like_code annotated field. related_params[distro.id] = table.objects.filter( ProductId__in=[map["ProductId"] for map in related_maps_by_distro.values("ProductId")] ).annotate( agr_like_code=Func(F("DistributionParameterId__Code"), function=agr_suitable_code), prod_to_param_exists= Exists(AgrDistributionProductParameter.objects.filter(ProductId=context['product'], DistributionParameterId__Code=OuterRef( "agr_like_code")).values('id')), has_agr_param=Case( When(Q(agr_like_code__in=agr_parameter_codes) & Q(DistributionParameterId__Code__in=agr_param_map_codes_distro) , then=2), When(Q(agr_like_code__in=agr_parameter_codes), then=1), default=0, output_field=models.IntegerField(), etc .. I have tried to formulate this line agr_like_code=Func(F("DistributionParameterId__Code"), function=agr_suitable_code) in many ways but with no success. The current error I'm receiving is django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near '<'. (102); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I know about Django documentation suggesting writing custom SQL query like class ConcatPair(Func): ... function … -
How can subtract two dates on django
I want to substract two dates at the same TYPE OF REGISTER image I want to substract PAR DATES but i have 4 dates how can i do? views.py ## sentencia 1 sentencia ="exec [PR].[dbo].[PT_PR]" + "'" + maquina + "','" + str(rec) + "','" + orden + "'" + ",'" + str(fecha_i) + "'," + "'" + str(fecha_f) + "'" cr = cursor.execute(sentencia) resultstable = namedtuplefetchall(cr) fecha_total = fecha_f - fecha_i -
Django (Accidental deletion of socket file, need to recreate)
Yesterday evening, I accidentally highlighted one too many files which I needed to delete from my Django environment and I accidentally caught the .sock file of my test production .sock file. I have since tried everything I can think of to recreate the .sock file with no avail. Does anyone know of which method I should be following to recreate the sock file? As a last resort, I tried to manually create the .sock file and tried to run this command: gunicorn --workers 3 --bind unix:/home/testapp/test.sock test.wsgi:application Although, I receive an error during the boot phase, ValueError("%r is not a socket" % addr) which is understandable as I manually tried to recreate the file as a last resort option. I have tried to rebooting nginx, reloaded the daemon, and tried to restart gunicorn, hoping that the .sock may be automatically recreated within my project folder, but I'm not having any luck. Any tips would be most appreciated! Thank you :-) -
How to get foreign key values in Django?
models.py: class Publisher(models.Model): name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher) views.py: book = Book.objects.get(pk=1) I need the publisher id and publisher name of this book. How to get them? -
Delete post after 24 days or 1 Day
I am building a Simple BlogApp and I am stuck on an Problem. What i am trying to do :- I am trying to delete the post according to user's choice , Suppose a user select delete after 1 day then i am trying to delete it automatically after 1 day BUT failed many times. models.py class Blog(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=300) time = models.CharField(max_length=30,choices=TIME) date_added = models.DateTimeField(default=timezone.now) class Image(models.Model): blogs = models.ForeignKey(Blog,on_delete=models.CASCADE) images = models.FileField(upload_to='files') views.py def delete_post(request): blogPost = Image.objects.filter(blog__user=request.user) d = timezone.now() - timedelta(hours=1) d1 = timezone.now() - timedelta(days=1) for foo in blogPost: if foo.blog.time == '24H': showing = Image.objects.filter(blog__user=request.user).filter(date_added__gte=d) elif foo.blog.time == '1D': showing = Image.objects.filter(blog__user=request.user).filter(date_added__gte=d1) context = {'showing':showing} return render(return ,'posts.html', context) BUT i try to run this then it is showing nothing BUT when user selects 1D then hide after 1 Day BUT it is not working. I have no idea how can i do it. Any help would be Appreciated. Thank You in Advance. -
Django loads image only with hardcoded path
So Django loads image only if I have hardcoded src value of img tag. This is my template with hardcoded image path (works fine): {% load static %} {% block content %} <p>{{ product.title_text}}</p> <p>{{ product.description_text }}</p> <p>{{ image.image }}</p> <img src="{% static 'my_app/images/product_images/some_image.jpg' %}" alt="{{ image.name }}"> {% endblock %} But if I change image path to the dinamic variable which value actually is the same path, nothing shows up. No errors, just no image. <img src="{% static image.image %}" alt="{{ image.name }}"> Any suggestions please? Thanks in advance. -
Django with legacy database user table
I am trying to integrate Django with an already existing database. I am using mysql database. When I ran the migrations, django has added its default tables like auth_permission, auth_user etc. I have a table in my database called tb_user which has the usname, psword and more additional fields. Since django default auth_user also has the username and password, how these two will work together? When I register a new user, the user will be stored in both tables? Is this an issue at all? I have posted a new question with more details and issues here. You can see the models. Django running migrations on legacy database -
Detected path traversal attempt when associating and saving a FileField to a model instance in Django
I'm trying to generate a pdf file and associate it with a Django model FileField. The process shown below works on a Django local development server, but on a deployment server (Nginx + Gunicorn) I get a SuspiciousFileOperation exception: Detected path traversal attempt in '/home/user/media/properties/1/myfile_1.pdf', which traces back to the model_instance.save() line. From the docs I understand that the error is raised if the path contains '..' to safeguard against path traversal attempts: def generate_filename(self, filename): """ Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirname).parts: raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" % dirname) return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename))) However, I don't see where my code contains such a relative path and don't know how to overcome the error. Settings.py MEDIA_URL = "/media/" MEDIAFILES_DIRS = ["/home/user/media"] MEDIA_ROOT = "/home/user/media" File operation myfile = open(f'{settings.MEDIA_ROOT}/temp/myfile_{model_instance.id}.pdf') django_file = File(myfile, name=f'myfile_{model_instance.id}.pdf') model_instance.myfile = django_file model_instance.save() models.py def directory_path(instance, filename): return f'{settings.MEDIA_ROOT}/properties/{instance.id}/{filename}' class MyModel(models.Model): myfile = models.FileField(blank=True, null=True, upload_to=directory_path) -
Django running migrations on legacy database
I am working with a legacy database and I have created a custom user model. I am working to set up the register and authentication funcs. I have created the user manager and in user model there are some fields that I have added for django like is_staff, is_active, date_joined. When I run migrations, the legacy table still does not have the columns I have added in the model. Should It actually alter the legacy database? class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=40) usname = models.CharField(max_length=40, blank=True, null=True, unique=True) psword = models.CharField(max_length=255, blank=True, null=True) # added columns is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = TbUserManager() USERNAME_FIELD = 'usname' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'tb_user' Also, when I am creating the superuser, I get the following error django.db.utils.OperationalError: (1054, "Unknown column 'tb_user.password' in 'field list'") Although The user manager looks like this class TbUserManager(BaseUserManager): def create_user(self, email, psword=None, **kwargs): if not email: raise ValueError('Users must have a valid email address.') if not kwargs.get('usname'): raise ValueError('Users must have a valid username.') user = self.model( email=self.normalize_email(email), usname=kwargs.get('usname') ) user.psword(psword) user.save() return user def create_superuser(self, email, psword, **kwargs): user = self.create_user(email, psword, **kwargs) user.is_superuser = … -
can't display images in template django, HELP ME PLEASE
hello i am working on a django project i am trying to save the images entered by the user in my database and this works fine, but when i try to display them they do not display even though my configuration seems correct here is my code: panneaux/model.py from django.db import models # Create your models here. class Panneaux(models.Model): nom = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) nbr_objet = models.DecimalField(decimal_places=2, max_digits=100, default=0) image_Panneaux = models.ImageField(upload_to='images/') panneaux/form.py from django import forms from .models import Panneaux class PanneauxForm(forms.ModelForm): nom = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", } )) description = forms.CharField( required=False, widget=forms.Textarea( attrs={ "class": "form-control", } ) ) image_Panneaux = forms.ImageField() class Meta: model = Panneaux fields = '__all__' panneaux/view.py from django.shortcuts import render from .models import Panneaux from .forms import PanneauxForm from django.shortcuts import redirect import cv2 import numpy as np # Create your views here. def create_panneaux(request): context = {} if request.method == "POST": form = PanneauxForm(request.POST, request.FILES) if form.is_valid(): nomP = form.cleaned_data.get("nom") descriptionP = form.cleaned_data.get("description") image_PanneauxP = form.cleaned_data.get("image_Panneaux") obj = Panneaux.objects.create( nom = nomP, description= descriptionP, image_Panneaux= image_PanneauxP ) obj.save() form= PanneauxForm() print(obj) return redirect('./ui-notifications.html') else: form= PanneauxForm() context['form'] = form return render(request, "./ui-tables.html", context) def latestPanneaux(request): context = {} … -
Django polymorphic inline - Double trouble in Django Admin
I'm redesigning an online shop in Django and I had to create a model for custom fields. This is how models.py looks like: import uuid from django.contrib import admin from django.db import models from polymorphic.models import PolymorphicModel class BaseModel(models.Model): class Meta: abstract = True id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) class Product(BaseModel): [various standard fields] class Price(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class BaseCustomField(BaseModel, PolymorphicModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='custom_fields') name = models.CharField(max_length=64) def __str__(self): return f'{self.name}: {self.value}' class CustomBooleanField(BaseCustomField): value = models.BooleanField() class CustomCharField(BaseCustomField): value = models.CharField(max_length=64) [other custom fields, they all look more or less the same] From the shell I can create products and assign them any price and custom field without any problem, so the models should be OK. The problems begin when I want to create products from Django Admin, which will be my only choice when I upload the site to the production server. from nested_admin import NestedModelAdminMixin, NestedTabularInlineMixin, NestedStackedInlineMixin from polymorphic.admin import PolymorphicInlineSupportMixin, StackedPolymorphicInline from .models import Product, Price, BaseCustomField, CustomBooleanField, [...] class BaseModelAdmin(admin.ModelAdmin): readonly_fields = ['created', 'modified', 'created_by'] ordering = ['-created'] def save_model(self, request, obj, …