Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you know if your Django app is doing too much
How do you know if your Django app is doing too much and needs to be broken up into several apps? For example an 'employee' app might list all employees, employee of day, employee of week, employee month, employee of year, calculate performance, and more stuff. -
Modifying shared data in Django app
I have a simple Django application: users may view and modify certain datathat is stored in mysql database. Of course, situation when several users concurrently attempt to modify same piece of data is common so it's necessary to correctly process this situation. In simple python code (or in Java, which I've been used earlier for several years) I would simply create critical section around the code that works with shared data using standard threading mechanisms ("synchronized", locks and so on): lock.acquire() try: # modify shared data finally: lock.release() But as far as I know, Django proposes a lightweight approach and it can be configured to have several worker processes (not even threads). That makes locks useless. So my question is: what is the common way to protect concurrent modifications shared data in Django app? What are the best practices in this spot? Several important points: Data is large enough and is stored in several tables in database, so db-level stuff like "select for update" is not an option. Moreover, I don't want to use db-specific queries in order to have future ability of changing db engine without complex code modifications. I need to protect data on python level. Critical section … -
Data loss in Select2 M2M Field in Django Admin on Validation error
I am using Django Jet for admin with Django 1.8.17. It uses Select2 for FK and M2M fields. But in m2m fields the saved data is lost when a validation error occurs in change form in admin. Change Form with saved data, m2m values are set- m2m field data lost on validation error- There was data loss issue in select2 many to many widget when using the back button, which has been fixed in Django 1.8.8. But I am experiencing data loss issue with select2 on validation error. How to correct this ? Any hints on what can be possibly wrong ? -
Django: Annotate a date and time field and filter
I have a django model that has a date field and a separate time field. I am trying to use a filter to find a value on the latest record by date/time that is less than the current record's date time. How do I use annotate/aggregate to combine the date and time fields into one and then do a filter on it? models.py class Note(models.model): note_date = models.DateField(null=True) note_time = models.TimeField(null=True) note_value = models.PositiveIntegerField(null=True) def get_last(n): """ n: Note return: Return the note_value of the most recent Note prior to given Note. """ latest = Note.objects.filter( note_date__lte=n.note_date ).order_by( '-note_date', '-note_time' ).first() return latest.note_value if latest else return 0 This will return any notes from a previous date, but if I have a two notes on the same date, one at 3pm and one at 1pm, and I send the 3pm note to the function, I want to get the value of the 1pm note. Is there a way to annotate the two fields into one for comparison, or do I have to perform a raw SQL query? Would something like Concat for string work: Note.objects.annotate( my_dt=Concat('note_date', 'note_time') ).filter( my_dt__lt=Concat(models.F('note_date'), models.F('note_time') ).first() -
Mezzanine mobile site menu remove
I use Mezzanine with responsive bootstrap. When I visit the site for the first time with a mobile device I get the default Mezzanine menu where it says: This is the mobile homepage... View Full Site. So if I want to continue I need to click the View Full Site button and than I get my website. How can I get rid of this Mezzanine Menu since I don't need it. I want users to go directly to my website.. PS: this menu only appears the first time in a browser than once clicking View Full Site it does not appear anymore. In my header I have: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0"> -
Prevent django from creating all tables in all databases
I have a django app and am using two separate databases. I have default that will hold things like Users, Sessions and whatever else, and then I have another database, movies, that I will fill with all the data from my movies model. I set up a custom database router like this: class CustomRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'movies': return 'movies' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'movies': return 'movies' return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._state.db == obj2._state.db: return True return False def allow_migrate(self, db, app_label, model_name, **hints): if app_label == 'movies': return db == 'movies' return 'default' Everything seems to work great except that I don't want my movies database to even include tables for Django's Users, Sessions or anything. I only want it to have movie data. -
Order Filtered Results by Total Occurrence
I am currently working on a search for my Django site and want to take a query then see how many time it appears in a posts name and description and return the results with the posts with the query appearing the most on top (ie if I search for "car" a post with car mentioned 5 time should appear before a post that mentions "car" once). Here is my views.py: def stack_list(request, query): context_dict = {} stacks_list = Stack.objects.filter( Q(name__icontains=query) | Q(description__icontains=query) ).annotate(total_occurance=Count('name')+Count('description') ).order_by('total_occurance').distinct() context_dict['stacks_list'] = stacks_list return render(request, 'stack/index_search_results.html', context_dict) and my html: {% for stack in stacks_list %} <p>{{ stack.name }} {{ stack.description }}</p> {% endfor %} However when I try a query, it doesn't organize it in descending order. Any ideas on where I'm going wrong? -
Render Form ViewSet Django Rest Framework
I would like to do the following: With my model class User(models.Model): id = models.AutoField(primary_key=True) field1 = models.CharField(max_length=100) fk1 = models.ForeignKey(Group) goes on After this, I created my Serializer, which looks like: class UserSerializer(serializers.ModelSerializer): class Meta: model = UserSerializer fields = (...) ... Lastly, I create my ViewSet, which should look like this: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer but now, how would I be able to create a viewSet and, for example, generate a form with my class? My final idea is to be able to do something like: def my_view(request): my_form = UserViewSet.as_view({'get': 'list'}(request)) # from here either to be able to use .render().content # or, inside the template, render with {% render_form my_form %} Is this possible? Thank you -
Vim filetype settings for python affecting htmldjango also
I have the following settings in my vimrc let python_highlight_all=1 augroup vimrc_autocmds autocmd! autocmd FileType python highlight Excess ctermbg=DarkGrey guibg=Black autocmd FileType python match Excess /\%80v.*/ autocmd FileType python set nowrap augroup END but the problem is that the same settings are applied to files of type htmldjango which are template files of django . i have set the following parameters also in my vimrc set hidden set number set nowrap set autochdir set splitbelow set splitright set nocompatible set foldmethod=indent set foldcolumn=3 set nofoldenable set tabstop =4 set shiftwidth =4 set softtabstop =4 set expandtab set pastetoggle=<F5> set laststatus=2 set encoding=utf-8 let s:vim_home ='/home/xxxxx/.vim' set scrolloff=3 set autoindent set smartindent set confirm set visualbell set history=1000 set showmatch set incsearch set hlsearch set ignorecase set smartcase set mouse=a set showcmd set ruler set nobackup set writebackup execute('set backupdir='.s:vim_home.'/backup') execute('set directory='.s:vim_home.'/temp') set wildmenu set wildmode=list:longest set wildignore+=.DS_Store,Thumbs.db set wildignore+=*.so,*.dll,*.exe,*.lib,*.pdb set wildignore+=*.pyc,*.pyo set wildignore+=*.swp" set backspace=indent,eol,start set whichwrap+=<,>,h,l set listchars=eol:$,tab:>-,trail:-,extends:>,precedes:<,nbsp:%,conceal:. set complete=.,w,b,u,t set completeopt=longest,menuone,preview filetype plugin indent on syntax on colo molokai what can i do to prevent it? Thanks -
Collapsing duplicate foreign key values in Django migrations
I have a Django app that I need to perform a migration on. Here's a representational schema of what I need to modify: class A(Model): c = ForeignKey(C) ... class B(Model): c = ForeignKey(C) ... class C(Model): x = CharField() y = CharField() z = CharField() class Meta: unique_together = (('x', 'y', 'z'),) z is no longer relevant to the uniqueness of the foreign key C. So I am going to drop the field z and change the unique requirement to just x and y. But first I need to do a data migration that drops the upcoming duplicate entries, and I need to fix up all of the ForeignKeys to point to that single consolidated entry. I'm looking if there is a better way than what I'll outline in my answer below. I'm not entirely satisfied with my answer as it doesn't have any safeguards of dropping a foreign key that is still in use -- other than the algorithm itself. (Like, what if there is also another foreign key relationship to C I overlooked.) -
In the Django generic detailview where does contect's index cone from?
d example below where does context's index 'book_list' comes from, if is arbitrary what is the naming convention? class PublisherDetail(DetailView): model = Publisher def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context -
Change form field value on 'def form_invalid' using class based views.
I'm working with a CreateView from django class based views for a form submit, and I have a special validation defined on the clean method: class MyModelCreateForm(forms.ModelForm): quantity = forms.IntegerField( label='quantity', ) class Meta: model = MyModel def __init__(self, *args, **kwargs): initial_quantity = kwargs.pop('initial_quantity') super(MyModelCreateForm, self).__init__(*args, **kwargs) self.fields['quantity'].initial = initial_quantity def clean(self): # Don't take care of random_int definition if self.cleaned_data['quantity'] != random_int: raise forms.ValidationError( 'There is a bug', ) The 'quantity' field has a default initial value (initial_quantity), and, if this number is diferent of 'random_int', the form will be invalid and the view will return the form with 'form_errors' for show to the user. Ok, in that point, I need to set the value of the 'quantity' field to 'random_int', and then, the next time that the user submits the form, the view response will be handle by the form_valid method. I tried to edit the 'quantity' field value on the 'form_invalid' method, but is not working. The error is correctlu raised but, the value of the 'quantity' field is 'initial_quantity' yet: views.py class MyModelCreateView(CreateView): model = MyModel form_class = MyModelCreateForm def get_form_kwargs(self): kwargs = super(MyModelCreateView, self).get_form_kwargs() kwargs.update({'initial_quantity': 10}) return kwargs def get_form(self, form_class=MyModelCreateForm): form = form_class(**self.get_form_kwargs()) return … -
Install mysqlclient on Windows with cygwin for django serevr
I really hope someone can help me. I'm trying to install a Django server on a Windows 10 machine using cygwin. So far I managed to get the test serevr running, and I want to hook it up to a MySql server instance running on the Windows machine. Since I'm using Python3 I need the mysqlclient driver, as stated in the Django documentation I tried installing it using pip, but I get a gcc error: $ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.9.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient: started Running setup.py bdist_wheel for mysqlclient: finished with status 'error' Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-r0034q8_/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpv8u4dfwopip-wheel- --python-tag cp34: running bdist_wheel running build running build_py creating build creating build/lib.cygwin-2.6.0-x86_64-3.4 copying _mysql_exceptions.py -> build/lib.cygwin-2.6.0-x86_64-3.4 creating build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/__init__.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/compat.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/converters.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/connections.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/cursors.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/release.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb copying MySQLdb/times.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb creating build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.cygwin-2.6.0-x86_64-3.4/MySQLdb/constants running … -
How to specify authentication info to memcache with django?
I use rediscloud to provide memcache support to my django install. It allows to set SASL authentication username and password (not sure if the sasl thing could be an issue). I didn't found the correct syntax to supply them from django: CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "pub-memcache-********.com:17****", "username": "user", "password": "pass" } } What's the correct syntax then ? -
Django dealing with a model fields
I'm new to Django and I'm trying to learn as I go. And I've ended up in a situation where I can't figure out what is the best way forward. snippet from models.py: class ProjectMeta(models.Model): project = models.ForeignKey(Project) architect = models.CharField(max_length=200) landscape = models.CharField(max_length=100, blank=True) engineer = models.CharField(max_length=200, blank=True) client = models.CharField(max_length=100) consultant = models.CharField(max_length=100, blank=True) size = models.DecimalField(max_digits=5, decimal_places=2, blank=True) location = models.CharField(max_length=200) date = models.DateField() STATUS = ( ('CP', 'Competition'), ('UC', 'Under construction'), ('CO', 'Completed'), ) status = models.CharField(max_length=2, choices=STATUS, default=1) And this is the view: class ProjectDetailView(DetailView): model = Project def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) context['projectmeta_list'] = ProjectMeta.objects.all() return context But if I want to output ProjectMeta in the template I could iterate over projectmeta_list. {% for metadata in projectmeta_list %} <p>Architect: {{ metadata.architect }}</p> {% endfor %} But this require alot of repeating myself, and I wont work. Because lets say the architect field is empty, I would get Archiect: printed to the page. Is there a built-in way of converting a model into a dict or list, so I can iterate over it and only print out fields that aren't empty to the page? I've been looking at get_fields(), would that work? https://docs.djangoproject.com/en/1.10/ref/models/meta/#retrieving-all-field-instances-of-a-model … -
How to get the correct URL for an image in Django
Hello I'm new in Django and I am trying to build a simple e-commerce application. in this app I want a user to upload an item photo which they want to sell. I want to display all the items in the home page, when you hit on the item name it redirect to the item details page. User can add a new item with fields title,item image,and discription. I want to show a thumnail of the uploaded image in the home page near the title and the original image in the item details page, but in my try the image is not appearing in the details page. models.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from PIL import Image class Item(models.Model): posted_user = models.ForeignKey('auth.User') item_name = models.CharField(max_length=200) item_image = models.ImageField(upload_to='img') item_discription = models.TextField() posted_date = models.DateTimeField( default=timezone.now) forms.py from django import forms from .models import Item import re from django.contrib.auth.models import User class SellItemAddForm(forms.ModelForm): class Meta: model = Item fields = ('item_name', 'item_discription', 'item_image') urls.py from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.item_list, name='item_list'), url(r'^item/(?P<pk>\d+)/$', views.item_detail, name='item_detail'), url(r'^item/new/$',views.item_new, name='item_new'), url(r'^item/(?P<pk>\d+)/edit$', views.item_edit, name='item_edit'), … -
Django fails to return Response on a TeamCity build
So here's the deal: We have a Django server which we interact with using REST api. We built a testing environment for end-2-end testing using protractor. I am trying to make a build in TeamCity in order to run this test suite. All of our services, frontend and backend, are being executed completely as part of the TeamCity build, and almost everything works fine. Protractor connects to several backend services and servers without a problem, until it tries to retrieve a simple json from Django server. The server is trying to return a json containing only 2 strings, and I can see in the logs that the function that prepare this result is being called (meaning the Django server received and processed the request). This function is trying to return a 'Response' with a list of 2 strings, and usually, in development environment, it works fine. But this case, while running in TeamCity, it's failing, probably due to timeout. When I made some tests, I found out it can take 1 minute to return this simple result to the frontend server. I shut down the Django server, and re-run it on the same machine TeamCity runs on. Then, when trying … -
Non-deterministic Sqlite error in Django unittest
I'm getting this non-deterministic error from Sqlite when I run a Django unittest: File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/src/myproject/myapp/models.py", line 2789, in get_or_create_category parent=parent, File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 146, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 484, in get_or_create return self.get(**lookup), False File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 398, in get num = len(clone) File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 106, in __len__ self._result_cache = list(self.iterator()) File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/query.py", line 317, in iterator for row in compiler.results_iter(): File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 775, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor.execute(sql, params) File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/src/buildbot/slave/myproject_runtests/build/.env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 362, in execute return Database.Cursor.execute(self, query, params) InterfaceError: Error binding parameter 0 - probably unsupported type. The code triggering the error looks like: @staticmethod def get_or_create_category(): parent = ParentModel.get_or_create_category() return MyModel.objects.get_or_create( slug=c.SOME_SLUG, defaults=dict( name='Some Name', parent=parent, ) )[0] Specifically, the line MyModel.objects.get_or_create(. However, I'd say about 90% of the time, this runs fine. Why would this code be causing Sqlite to break in this way? -
Writing own Online programming judge script
I was trying to create a bash script to compile, time limit, run time error and wrong answer. Now I am having 2 problems: 1) How to prevent malicious system calls like fork etc. 2) How to set time limit. Also, I will be calling this script through a django python rest api and based on the return value I will return appropriate value. Is there anything better that I can do? Following is my code and I run it like this bash a.sh a.cpp out1.txt out2.txt err.txt temp.txt c 2 abc inputFile=$1 outputFile=$2 expectedOutputFile=$3 errorFile=$4 tempFile=$5 language=$6 timeLimit=$7 executableName=$8 echo $inputFile $outputFile $expectedOutputFile $errorFile $tempFile $language $timeLimit $executableName if [ "$language" == "c++" ] then echo "compiling code" g++ $inputFile > $tempFile 2>&1 -o $executableName status=$? echo $status if [ "$status" -ne 0 ] then echo "compilation error" exit 101 #compilation error fi echo "Compilation successful" echo "Running File" ./$executableName > $outputFile 2>&1 status=$? echo "Running code status" $status if [ "$status" -ne 0 ] then echo "Running code error" exit 103 #runtime error fi diff $outputFile $expectedOutputFile > $tempFile 2>&1 status=$? echo "Comparing output" $status if [ "$status" -ne 0 ] then echo "Wrong output" exit 104 #runtime … -
Best practice for ignoring permissions in django-rest-framework tests that don't concern permissions, i.e. data tests
I'd like to be able to cleanly ignore permissions in some django-rest-framework tests. Is there a best practice for doing this? There is force_authenticate for forcing authentication, but I couldn't find the same equivalent for permissions. Currently, we're using the below test mixin to monkey patch the permissions, but I don't 100% like this approach, because if we're super() overriding the test class's setUp or tearDown we have to remember to call super() or else the monkey patched method isn't returned to it's original state, and it will fail other tests that do need permissions as a result. Also, all test classes that should ignore permissions need this mixed in. Current mixin solution: from unittest.mock import MagicMock from utils.permissions import CrudPermissions class MockPermissionsAllowAnyMixin(object): """ Mixin to allow for ignoring permissions in view tests. """ def setUp(self): self.has_permission = CrudPermissions.has_permission CrudPermissions.has_permission = MagicMock(return_value=True) def tearDown(self): CrudPermissions.has_permission = self.has_permission One solution idea (not sure about this): One idea would be to use settings.py with a feature flag, and have permissions turned OFF if settings/dev.py and ON in settings/prod.py then in tests that do need permissions override the setting with the below snippet. I'm not sure this is a good solution either though. … -
Can I build my form without using Django form?
I'm using Django and I just did a big form Using HTML5 and bootstrap. Can I still send the form via the post method to django if I'm not using it to generate the form? Should I definitely redo my form using Django? -
Django url matches everything to one View
I have a very strange problem with Django. I have a folder views like here: Django: split views.py in several files . Everything was working fine for a long time, until now when I added another file with a view (let's say a file viewsa.py with a View1). Now every request is matched to this new View1. Even if I post to some gibberish url (http://example.com/some_url_that_does_not_exist) - this url is stilled matched to View1. If I remove the line from viewsa import View1 from __init__.py everything goes back to normal... If anybody has a slightest idea why this happens I will be very grateful. -
How to make centralized Login server with Django
Where I work currently there are many Django projects, each running on their own VPS, and each is running under their own subdomain (foo.example.com, bar.example.com, ...) as shown in the following diagram: What I want to do is to have a central Django Server that manages all the login process (authorization and authentication) for each application, and when a user logins in foo.example.com and then goes to bar.example.com, his session keeps active and doesn't need to enter credentials again (user/password), the same if the user logs out, he couldn't see anything on the other projects until he logins in again. Similar as what Google does when you login on gmail.com and go to youtube.com or blogger.com (or more similar to what I want to do: you login in google.com and go to drive.google.com, photos.google.com, calendar.google.com) or any other Google's site, your session keeps active. Is there any django-package or any other way that would help me accomplish it? -
How to access list of dictionaries from mashape using python(django)?
I am sending a URL as request and in response I am getting back a list of dictionary and I am unable to loop through the values. def profile_model(request): response = unirest.get(url,header) #url and header is defined outside the function contents = response.raw_body for i in contents: print i['items'] print i['profiles'] return render(request,"profile_model.html",{}) In debug mode I am seeing Name:contents Value: str: { "items" : [ 13184519, 13184195, 13183948, 13184350, 13183946, 13184208], "profiles" : [ "slezyr", "stefek99", "amlib", "vyrotek", "xenophonf", "TheGrumpyBrit"] } I am getting TypeError: string indices must be integers, not str.If I remove quotes in items I will get undefined variable 'items' -
django - clean dynamic field
I have model like this: class Order(models.Model): order_type = models.ForeignKey(OrderType) quantity = models.IntegerField(max_digits=10, decimal_places=4) product = models.ForeignKey(Product) And in form I added filed dynamically like this: class OrderForm(ModelForm): class Meta: model = Order fields = [ 'order_type', 'product' ] widgets = { 'order_type': Select(attrs={'class': 'form-control'}), 'product': Select(attrs={'class': 'form-control'}), } def __init__(self, types=[],*args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) if "AMOUNT" in types: self.fields['quantity'] = IntegerField( NumberInput(attrs={'class': 'form-control'}) ) And in CreateView I overwrite post. And from frontend I'm sending ajax with data or not (if data is sent, I want to generate form with addition quantity field) then I replace old form with this new: class OrderCreateView(CreateView): model = Order form_class = OrderForm def post(self, request, *args, **kwargs): self.object = None d = request.POST.get('DATA', None) if d is not None: form = self.form_class( types=["AMOUNT"], **self.kwargs ) return render( request, 'form.html', {'form': form} ) else: form = self.form_class(**self.kwargs) return render( request, 'form.html', {'form': form} ) return super(OrderCreateView, self).post(request, *args, **kwargs) And it works. I get new form with quantity. But when I'm trying do sumbit this form. I got an error null value in column "quantity" violates not-null constraint Must I doing somethign else to make it works? Custom clean this field?